Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop
#4
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
Reply


Messages In This Thread
while loop - by Blob - Nov-12-2019, 11:03 AM
RE: while loop - by perfringo - Nov-12-2019, 11:25 AM
RE: while loop - by jefsummers - Nov-12-2019, 12:21 PM
RE: while loop - by ichabod801 - Nov-12-2019, 12:46 PM
RE: while loop - by Blob - Nov-14-2019, 04:09 PM
RE: while loop - by ichabod801 - Nov-14-2019, 04:45 PM
RE: while loop - by Renym - Nov-15-2019, 01:50 PM
RE: while loop - by jefsummers - Nov-15-2019, 01:59 PM
RE: while loop - by ichabod801 - Nov-15-2019, 02:03 PM
RE: while loop - by the_ophidian_order - Nov-15-2019, 03:42 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020