Python Forum
while with a conditional test
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while with a conditional test
#1
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
Reply
#2
Hello and welcome to Python and the forum!

Edited the post, I missed a point in your code, sorry.
Reply
#3
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
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to test and import a model form computer to test accuracy using Sklearn library Anldra12 6 3,069 Jul-03-2021, 10:07 AM
Last Post: Anldra12
  How to write test cases for a init function by Unit test in python? binhduonggttn 2 3,067 Feb-24-2020, 12:06 PM
Last Post: Larz60+
  How to write test cases by Unit test for database configuration file? binhduonggttn 0 2,512 Feb-18-2020, 08:03 AM
Last Post: binhduonggttn

Forum Jump:

User Panel Messages

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