pythontruthiness

Anyone know why I'm getting a "Process finished with exit code 0"?


I'm trying to run this program but for some reason, whenever I enter 0, the program stops running. I expect a "You've guessed too low, please try again " as the input is less than the random number generated. Can anyone help and explain? Also, feel free to critique my code so that I can make it better. Much appreciated.

# Generate random number for player to guess.
import random

number = random.randint(1, 3)
print(number)

# Ask player's name and have player guess the number.
welcomeUser = input("Hi, welcome to 'Guess a Number!'. Please tell us your name ")

userName = str(welcomeUser)
userGuess = int((input("Guess a number from 1 - 3 ")))

# Cycle through player's guesses until player enters correct number.
while userGuess:
    if userGuess > number:
        print("You've guess too high, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            break
    elif userGuess < number or userGuess == 0:
        print("You've guessed too low, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            break
    else:
        print("Congratulations " + userName + "! " + "You've guessed correctly! ")
        break

Solution

  • 0 is falsey, i.e. it evaluates to False in a boolean expression. Therefore, the while loop starting with

    while userGuess:
    

    will be skipped if userGuess is 0. It doesn't look like you need to check for any conditions in your loop, so changing that to

    while True:
    

    should suffice. BTW, Process finished with exit code 0 just means the program exited without any errors.