7-6 三个出口
1. 项目
7-5 电影票
有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费;
3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问
用户的年龄,并指出其票价。
以另一种方式完成练习 7-4 或练习 7-5,在程序中采取如下所有做法。
在 while 循环中使用条件测试来结束循环。
使用变量 active 来控制循环结束的时机。
使用 break 语句在用户输入'quit'时退出循环。
2. 代码
age = "" prompt = "Hello, How old are you?" #在 while 循环中使用条件测试来结束循环 while age != 'quit': age = input(prompt) if age != 'quit': age = int(age) if age <= 3: ticket_fee = 0 print("You are free for watch movie...\n") elif age > 3 and age <= 12: ticket_fee = 10 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n") elif age > 12: ticket_fee = 15 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n")
age = "" # 使用变量 active 来控制循环结束的时机 active = True prompt = "Hello, How old are you?" while active: age = input(prompt) if age == 'quit': active = False else: age = int(age) if age <= 3: ticket_fee = 0 print("You are free for watch movie...\n") elif age > 3 and age <= 12: ticket_fee = 10 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n") elif age > 12: ticket_fee = 15 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n")
age = "" prompt = "Hello, How old are you?" while True: age = input(prompt) if age == 'quit': # 使用 break 语句在用户输入'quit'时退出循环 break else: age = int(age) if age <= 3: ticket_fee = 0 print("You are free for watch movie...\n") elif age > 3 and age <= 12: ticket_fee = 10 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n") elif age > 12: ticket_fee = 15 print("You should pay " + str(ticket_fee) + "$ to watch movie.\n")
3. 执行结果
D:\python编程:从入门到实践\venv\Scripts\python.exe "D:/python编程:从入门到实践/第7章 用户输入和while循环/parrot.py" _______________________________3rd_________________________________ Hello, How old are you?1 You are free for watch movie... Hello, How old are you?33 You should pay 15$ to watch movie. Hello, How old are you?quit Process finished with exit code 0