Oct-25-2022, 05:11 PM
(This post was last modified: Oct-25-2022, 08:49 PM by deanhystad.)
Don't do this
if statements are bad. They make code difficult to understand and they make programs run slow. But if statements are a necessary evil. Use them when needed. Avoid using when you don't.
while user_input != RNumber: # To get here, user_input must be greater than or less than RNumber. It cannot equal RNumber if user_input > RNumber: user_input = int(input("choose a lower number: \n")) # <-- one of these will run elif user_input < RNumber: # | user_input = int(input("choose a higher number: \n")) # <- elif user_input == RNumber: print("the number you chose is correct (", RNumber, ")") # <- This will never runYou could do this (but you shouldn't)
while user_input != RNumber: if user_input > RNumber: user_input = int(input("choose a lower number: \n")) elif user_input < RNumber: user_input = int(input("choose a higher number: \n")) # Make this if statement look at the new value of user_input. Still doesn't # work if the first guess is correct, if user_input == RNumber: print("the number you chose is correct (", RNumber, ")")You should do this:
while user_input != RNumber: if user_input > RNumber: user_input = int(input("choose a lower number: \n")) elif user_input < RNumber: user_input = int(input("choose a higher number: \n")) # Only way to get here is to guess correctly. print("the number you chose is correct (", RNumber, ")")The only way to exit the loop is to guess the correct number. If the loop is done, the user guessed the number. No need for any check.
if statements are bad. They make code difficult to understand and they make programs run slow. But if statements are a necessary evil. Use them when needed. Avoid using when you don't.