if-elif-else statement not executing - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: if-elif-else statement not executing (/thread-15132.html) |
if-elif-else statement not executing - laila1a - Jan-05-2019 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!") RE: if-elif-else statement not executing - buran - Jan-05-2019 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':
RE: if-elif-else statement not executing - stullis - Jan-05-2019 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!") RE: if-elif-else statement not executing - laila1a - Jan-05-2019 Thank you! RE: if-elif-else statement not executing - buran - Jan-05-2019 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. |