Python Forum
while with a conditional test - 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: while with a conditional test (/thread-9552.html)



while with a conditional test - driep - Apr-16-2018

Hallo,

I am new to python and am busy studying the while loop.

I have the following bit of code:
age = ""
prompt = "\nPlease enter your age: "
prompt += "\n(Enter 'quit' to end the program.) "

while age.lower() != 'quit':  # this is to make sure that if the user enters Quit quiT etc. it will be correctly processed
    age = input(prompt)
    print("Age: " + age)
    if int(age) < 3:
        print("\tYour ticket is FREE !")
    elif 3 <= int(age) <= 12:
        print("\t-->Age = " + age)
        print("\tYour ticket will be $10 !")
    else:
        print("\t-->Age = " + age)
        print("\tYour ticket will be $15 !")
Running the code and entering a valid integer value, the code executes fine

But when entering 'quit' as the input, the while loop does not terminate as expected but execute the first if statement and then, as expected, produce an error:
"Age: quit
Traceback (most recent call last):

File "<ipython-input-30-17864134defc>", line 8, in <module>
if int(age) < 3:

ValueError: invalid literal for int() with base 10: 'quit'"

Can anyone indicate the (probably) obvious reason why the while loop does not terminate


RE: while with a conditional test - j.crater - Apr-16-2018

Hello and welcome to Python and the forum!

Edited the post, I missed a point in your code, sorry.


RE: while with a conditional test - stranac - Apr-16-2018

That's because you're getting input after the loop has already been entered.

One way to fix this would be to get input once before the loop is started, and then get it again at the end of each iteration:
age = input(prompt)
while age.lower() != 'quit':
    # do stuff
    age = input(prompt)
Another option is using a for loop with iter():
for age in iter(lambda: input(prompt).lower(), 'quit'):
    # do stuff



RE: while with a conditional test - driep - Apr-16-2018

Thank you @stranac, it solved my problem.

I also got the iter with lambda working although this is still higher grade for me ;-)

Regards,

Phlip