I am going through a book (python crash course) and doing exercises.
I have a problem when inside a code, for a certain part I need to set variable set to string and then change it to integer.
Here is the attempt which brings error ( I need a help with this one) :
prompt = " Tell me your age : "
prompt += "
(Once finished type 'quit')"
#define variable and set to 'nothing' so python has something to compare
info_from_user = ""
# loop while the variable is not 'quit'
while info_from_user != 'quit':
info_from_user = input(prompt)
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
Successful examples, only for your reference and full understanding:
**1. using variable set to 'True' i.e. we set a variable named 'active' and set it to 'True'. The look while active: **
prompt = "
Tell me your age : "
prompt += "
(Once finished type 'quit')"
#define variable and set in True
active = True
# apply loop that will be active as long as active is true using if/else
while active:
info_from_user = input(prompt)
# condition to stop the loop active if user inputs quit
if info_from_user == 'quit':
active = False
# else change variable to integer so python can compare user input with numbers.
else:
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
2. using break , i.e. when user inputs 'quit' then break
prompt = "
Tell me your age : "
prompt += "
(Once finished type 'quit')"
#define empty variable so python got something to check against
info_from_user = ""
while info_from_user != 'quit':
info_from_user = input(prompt)
if info_from_user == 'quit':
break
else:
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
question from:
https://stackoverflow.com/questions/65924346/can-i-exit-from-loop-without-using-break-or-without-using-variable-set-to-tru 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…