Nov-12-2019, 12:46 PM
(This post was last modified: Nov-12-2019, 12:47 PM by ichabod801.)
You obviously know if statements, you just need to know what to check. Let's assume the secret number is always no negative. This is easy. There is a string method called isdigit that returns True if all the characters in the string are digits. So you could do:
guess = input("Guess: ") if guess.isdigit(): guess_count += 1 if int(guess) == secret_number: # moved the int conversion to here. print("You win!") break else: print('Please enter a positive integer.')One thing a try/except block will do that this won't is allow for white space. That is, ' 1' will work with the try/except solution, but not here. But there is a strip method of strings that removes all white space at the beginning or end of a string. You can add that right to the input call, which returns a string:
guess = input("Guess: ").strip() if guess.isdigit(): guess_count += 1 if int(guess) == secret_number: # moved the int conversion to here. print("You win!") break else: print('Please enter a positive integer.')To handle negative integers, you could just check for a leading '-' character:
guess = input("Guess: ").strip() if guess.isdigit() or (guess[0] == '-' and guess[1:].strip().isdigit()): guess_count += 1 if int(guess) == secret_number: # moved the int conversion to here. print("You win!") break else: print('Please enter an integer.')As you can see, this code is more complicated than try/except. But depending on the situation, the try/except method can get more complicated.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures