Python Forum

Full Version: if-elif-else statement not executing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, I'm new to programming so sorry in advance if my mistake is a stupid one.
I am having trouble making my if-elif-else statement execute properly in my dice rolling simulator, it always defers to the statement for the else part, no matter the input. For example, if the user inputs 1 to play again, they will be told the input is not valid. Same thing if they input 2 in order to stop playing.
Here is my code:

from random import randint


def diceRollingSimulator():
    dice = randint(1, 6)
    print(dice)


diceRollingSimulator()
answer = input("Would you like to play again? (enter 1 for yes or 2 for no): ")
if  answer == 1:
    diceRollingSimulator()
elif answer == 2:
    print("Thanks for playing!")
else:
    print("Not a valid input!")
input() will return str. In your if/elif conditions you compare str to int. so it's never True and else clause is executed.
You can either convert answer to int e.g. answer = int(input(...)) or alterntaively, compare answer to str, e.g. if answer == '1':
The input() function always returns a string. Because strings are not numbers, they cannot be compared. To fix this, you need to cast the input to a number type:

from random import randint
 
 
def diceRollingSimulator():
    dice = randint(1, 6)
    print(dice)
 
 
diceRollingSimulator()
answer = int(input("Would you like to play again? (enter 1 for yes or 2 for no): "))
if  answer == 1:
    diceRollingSimulator()
elif answer == 2:
    print("Thanks for playing!")
else:
    print("Not a valid input!")
Thank you!
answer = int(input("Would you like to play again? (enter 1 for yes or 2 for no): "))
Note that it will raise an exception if input is not valid for conversion to int with base 10.