Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 while loop
#1
I'm currently doing a tutorial on while loops, I followed along fine, but I always try to add something of my own to each code he teaches, so my brain has to think rather than just copy, but I'm stuck on something I want to add...

secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    guess = int(input("Guess: "))
    guess_count += 1
    if guess == secret_number:
        print("You win!")
        break
else:
    print("Fail!")
This is as per the tutorial. As you can see it works fine for numbers input, but at the moment if someone adds a non-numerical character it just responds with an error. I wanted to add something that would give a reply along the lines of "Invalid answer, numbers only please." then revert back to the first guess in the loop.

I realize it's probably quite basic for you guys but it's difficult for me psychologically to move on until I have done it (weirdo), I tried several different ideas and "wasted" a good couple hours on it (at least I've learnt what wont work), but it's possible that it just requires something I haven't learnt yet.

It's my first post, so I'm hoping you guys suffer noobs gladly. Pray
Quote
#2
Such a situation is called 'validation'. There are several threads in this forum where this subject is well explained.

Short explainer: for these situations one can take advantage of EAFPL (Easier to ask for forgiveness than permission). You try to do something and only if error happens you deal with it.

If you try to convert into int something which is not base 10 Python throws ValueError. You just handle this situation.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote
#3
Indeed. Not knowing what you have or have not covered, recommend you put your input inside a try...except block. The basic structure is:
try :
    number = int(input("Enter an Integer: "))
    print(f"{number} is a good integer!")
except ValueError :
    print("Ya call that an Integer?")
Will leave to you how to put that in your while loop so you can circle back and get a different value. With try...except you also have else and finally for structuring the code.
Quote
#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.
baquerik likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#5
(Nov-12-2019, 12:46 PM)ichabod801 Wrote: There is a string method called isdigit that returns True if all the characters in the string are digits.

So would you say this is the clearest and most efficient way of doing it? I would like to keep the code as clean as possible and I know ease with which it can be read is important, in case some poor sap has to decipher my code at later date.
Quote
#6
I was just trying to show you how to do it without using try/except, in case you hadn't gotten that far in learning Python yet. I thought that might be the case because you said you got the original code from a tutorial. In general I tend to choose the simpler code. For checking if something is an integer, I tend to go with try/except. If I'm in a situation where the 'try' and 'if' solutions have similar complexity, or performance really matters, I'll go with 'if' if I expect there to be a lot of errors, and 'try' if I expect there to be few errors.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#7
Hi,
I have an issue with the same code posted by Blob:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    guess = int(input("Guess: "))
    guess_count += 1
    if guess == secret_number:
        print("You win!")
        break
else:
    print("Fail!")
However, for some unknown reasons, I receive this error message:

SyntaxError: 'break' outside loop
ichabod801 wrote Nov-15-2019, 02:01 PM:
Please post all code, output and errors (in it's entirety) between their respective tags. I did it for you this time, Here are instructions on how to do it yourself next time.
Quote
#8
The break statement is used to break out of a loop. You have an if statement, but no loop.
Also pls use python tags when posting code. That keeps the formatting - otherwise impossible to detect indentation problems.
Quote
#9
If you have the indentation correct (as shown with the tags I added), you should not be getting that error. Double check the indentation of the code you are actually running.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#10
If you want to capture the input and quote it back to the user in the error message, grab the input and convert it to integer in separate lines:

secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    try:
        entered_value = input("Guess a number: ")
        guess = int(entered_value)
        guess_count += 1
        if guess == secret_number:
            print("You win!")
            break
    except ValueError:
        print(f"{entered_value} is not a valid integer")
else:
    print("Fail!")
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)