How to write a loop with conditions

Hello, I have to write a loop that prompts a user for their age in a program that outputs an admission price for a cinema ticket (depending on the user’s age)

I have just started writing basic loops like this one below, but I don’t even know where to start regarding creating loops where there are conditions, can someone point me in the right direction please?

Regards
Simon

prompt = "\nPlease enter the pizza topping you would like: "
prompt += "\n(Enter ‘quit’ when you have finished) "

while True:
topping = input(prompt)

if topping == 'quit':
	break
else:
	print(f"Please enter another topping!")

Hey Simon,
Is you intention to write an infinite loop that will endlessly prompt users to enter toppings unless they type quite?
Otherwise, I don’t see the need for a loop as yet.
so basically, a while loop goes as follows: while expression. The expression should be something that evaluates to true or false, that’s what you’re calling a condition. If the expression evaluates to True, the loop will continue, else it will stop. The loop shall be evaluated on every iteration or cycle that it runs.
So if you know any python expressions that evaluate to True or False, they are a perfect fit in the while loop expression. Most of those expressions will be comparisons though.

But you can find all this information in any python tutorial online, first try looking up for those and then come back when something else goes wrong.

Good morning Tobias, thankyou for your quick response.

To clarify, the task is to write a program with a loop that prompts the user to enter their age, then the program has to calculate the cinema ticket price based on the user’s age, and then quit if the user decides to quit.

This is what I’ve done so far but I am in a bit of a mess: I think the break is outside the loop in this instance.

prompt = "\nPlease enter your age so we can calculate your ticekt price: "
prompt += "\n(Enter ‘quit’ when you have finished) "

while True:
age = input(prompt)

if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20

if age == 'quit':
	break

else:
print(f"your admission price is{price}!")

Be lucky,
Simon

input returns a string and you compare it to int. This will rise TypeError. Have you tried to run this code before posting here?

Please put code between tags.

Sorry Aivar, here is the code at the moment, it’s a bit of a mess

prompt += "\n(Enter 'quit' when you have finished) "

while True:
	age = input(prompt)

if age < 4:
	price = 0
elif age < 18:
	price = 25
elif age < 65:
	price = 40
elif age >= 65:
	price = 20

	if age == 'quit':
		break
else:
		print(f"your admission price is{price}!")```

Regards
Simon
prompt = "\nPlease enter your age so we can calculate your ticket price: " 
prompt += "\n(Enter 'quit' when you have finished) "

while True:
	age = input(prompt)

elif age < 4:
	price = 0
elif age < 18:
	price = 25
elif age < 65:
	price = 40
elif age >= 65:
	price = 20


else:
		print(f"your admission price is{price}!")

It’s usually good idea to have plan articulated in natural language. Then it can be translated into programming language Python.

I would describe it something like this: while response is not ‘quit’ find price using response and conversion rules.

Simple enough. So how we write while response is not 'quit' in Python? Using walrus operator (assignment expression):

prompt = 'Please enter your number. To exit enter "quit".\n'
while (response := input(prompt).lower()) != 'quit':
     # find price using answer and conversion rules

This loop will run until ‘quit’ is entered. I made answer lowercase so that user can exit also with ‘Quit’, ‘QUIT’ etc.

How do I find price? First of all, if I want to compare answer with integer I must convert into integer:

prompt = 'Please enter your number. To exit enter "quit".\n'
while (response := input(prompt).lower()) != 'quit':
    age = int(response)
    # find price

Keep in mind that if user enters something which can’t be converted into integer (‘stop’) ValueError will be raised (except ‘quit’ which will break the loop).

To use rules one can have long if-elif-else comparison chain. Or use some data structure like dictionary, tuple, list etc. Data structures are more maintainable (in case rules change). Following are conversion rules expressed in dictionary: less than 5 years price is zero, less than 10 years 5 and less than 20 years 10:

conversion = {5:0, 10:5, 20:10}

Modern Python dictionaries are now guaranteed to have insertion order, so we can iterate over key, value pairs and if age is less than key then corresponding value is price (alternatively we can use tuple of tuples or list of lists or mix them):

prompt = 'Please enter your number. To exit enter "quit".\n'
conversion = {5:0, 10:5, 20:10}

while (response := input(prompt).lower()) != 'quit':
    age = int(response)
    for age_limit, price in conversion.items():
        if age < age_limit:
            print(f'Your price is {price}')

There are two problems with that. One is minor (we iterate over all key, value pairs even if we have found the price) and one major - no price starting from 20. So how to address them? Using break and else: branch of for-loop:

prompt = 'Please enter your number. To exit enter "quit".\n'

conversion = {5:0, 10:5, 20:10}

while (response := input(prompt).lower()) != 'quit':
    age = int(response)
    for age_limit, price in conversion.items():
        if age < age_limit:
            print(f'Your price is {price}')
            break                                     # breaking the loop if price is found
    else:                                               # no break
        print('Your price is 8')                

Try this.

prompt = """
Please enter your age so we can calculate your ticket price:
(Enter 'quit' when you have finished) """

while True:
	age = input(prompt)
	if age == 'quit':
		break
	age = int(age)
	if age < 4:
		price = 0
	elif age < 18:
		price = 25
	elif age < 65:
		price = 40
	elif age >= 65:
		price = 20
	print(f"your admission price is{price}!")

Notice the differences? Including the changes in indentation.

Brilliant, thankyou so much Steven, that has sorted it

Be lucky
Simon

Thankyou for your help Aivar

Much appreciated,
Simon