7-6 三个出口
1. 项目
7-5 电影票
有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费;
3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问
用户的年龄,并指出其票价。
以另一种方式完成练习 7-4 或练习 7-5,在程序中采取如下所有做法。
在 while 循环中使用条件测试来结束循环。
使用变量 active 来控制循环结束的时机。
使用 break 语句在用户输入'quit'时退出循环。
2. 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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" ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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" ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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. 执行结果
1 2 3 4 5 6 7 8 9 10 11 | 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 |
分类:
python编程:从入门到实践
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律