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')