222|0

7

帖子

0

TA的资源

一粒金砂(中级)

楼主
 

《Python编程:从入门到实践(第3版)》读书笔记6:用户输入和while循环 [复制链接]

本帖最后由 逝逝逝 于 2025-3-4 23:34 编辑
第7章     用户输入和while循环

7.1    input()函数的工作原理

在 Python 中,‘input()’ 函数用于从标准输入(通常是键盘)读取用户输入,并将输入内容以字符串形式返回。

1. 基本工作原理
程序暂停:当执行到 ’input()`‘时,程序会暂停,等待用户输入。
输入确认:用户输入后需按 回车键(Enter),输入内容会被读取。
返回值:输入的文本会作为字符串返回(不包含末尾的换行符)。

示例

  • name = input("请输入你的名字:") # 显示提示信息并等待输入
  • print(f"你好,{name}!")

2. 输入内容处理
始终返回字符串:无论输入数字、符号还是文本,’input()‘ 均返回字符串。
类型转换:需手动转换数据类型(如 ‘int()’、‘float()’、‘list()’ 等)。

示例

  • age = input("请输入年龄:")
  • age_int = int(age) # 转为整数(若输入非数字会报错)

3. 安全输入与错误处理
验证输入格式:防止类型转换错误(如用户输入非数字时转’int‘会崩溃)。
使用’try-except‘捕获异常

示例

  • while True:
  • try:
  • num = int(input("请输入整数:"))
  • break
  • except ValueError:
  • print("输入无效,请重新输入!")

练习 7.1 汽车租赁

编写一个程序,询问用户要租什么样的汽车,并打印一条消息,如下所示。
Let me see if I can find you a Subaru
  • car = input("What kind of car would you like? ")
  • print(f"Let me see if I can find you a {car.title()}.")
运行结果:
  • What kind of car would you like? audi
  • Let me see if I can find you a Audi.

练习 7.2 餐馆订位

编写一个程序,询问用户有多少人用餐。如果超过8个人,就打印一条消息,指出没有空桌;否则指出有空桌。
  • party_size = input("How many people are in your dinner party tonight? ")
  • party_size = int(party_size)
  • if party_size > 8:
  • print("I'm sorry, you'll have to wait for a table.")
  • else:
  • print("Your table is ready.")

运行结果:

  • How many people are in your dinner party tonight? 7
  • Your table is ready.
  • How many people are in your dinner party tonight? 12
  • I'm sorry, you'll have to wait for a table.

练习 7.3 10 的整数倍

让用户输入一个数,并指出这个数是否是 10 的整数倍。
  • number = input("input a number:")
  • number = int(number)
  • if number % 10 == 0:
  • print(f"{number} is a multiple of 10.")
  • else:
  • print(f"{number} is not a multiple of 10.")

运行结果:

  • input a number:20
  • 20 is a multiple of 10.
  • input a number:12
  • 12 is not a multiple of 10.
7.2    while循环

在 Python 中,‘while’ 循环用于重复执行代码块,直到条件不再满足。

基本语法

  • while 条件:
  • # 循环体代码
  • else:
  • # 循环正常结束后执行(非 break 退出时触发)

示例

  • count = 0
  • while count < 5:
  • print(f"当前计数: {count}")
  • count += 1
  • else:
  • print("循环正常结束")

运行结果

  • 当前计数: 0
  • 当前计数: 1
  • 当前计数: 2
  • 当前计数: 3
  • 当前计数: 4
  • 循环正常结束

 核心特点
条件驱动:只要条件为 ’True‘,循环持续执行。
灵活性:适用于不确定循环次数的场景(如用户输入验证、实时监控)。
手动控制:需在循环体内更新条件变量,避免无限循环。

 常见应用场景
(1) 用户输入验证

  • while True:
  • user_input = input("请输入 'yes' 退出:")
  • if user_input.lower() == "yes":
  • break
  • print("输入无效,请重试!")

(2) 处理动态数据

  • data = [1, 2, 3, 4, 5]
  • while data:
  • item = data.pop()
  • print(f"处理元素: {item}")

‘break’和‘continue’

  • num = 0
  • while num < 10:
  • num += 1
  • if num == 3:
  • continue # 跳过本次循环剩余代码
  • if num == 7:
  • break # 退出循环
  • print(num)
  • # 输出: 1 2 4 5 6

避免无限循环

  • # 条件变量未更新
  • count = 0
  • while count < 5:
  • print("卡在循环中!") # count 始终为 0

正确写法

  • count = 0
  • while count < 5:
  • print("正常执行")
  • count += 1 # 必须更新条件变量

 性能优化技巧:使用标志变量,简化复杂退出条件

  • running = True
  • while running:
  • if error_occurred:
  • running = False

练习 7.4 比萨配料

编写一个循环,提示用户输入一系列比萨配料,并在用户输入'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,指出要在比萨中添加这种配料。
  • prompt = "\nWhat topping would you like on your pizza?"
  • prompt += "\nEnter 'quit' when you are finished: "
  • while True:
  • topping = input(prompt)
  • if topping != 'quit':
  • print(f" I'll add {topping} to your pizza.")
  • else:
  • break

运行结果:

  • What topping would you like on your pizza?
  • Enter 'quit' when you are finished: 2
  • I'll add 2 to your pizza.
  • What topping would you like on your pizza?
  • Enter 'quit' when you are finished: QUIT
  • I'll add QUIT to your pizza.
  • What topping would you like on your pizza?
  • Enter 'quit' when you are finished: quit
练习 7.5 电影票
有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3(含)~12岁的观众收费10美元;年满12岁的观众收费15美元。请编写一个循环,在其中询问用户的年龄,并指出
其票价。
  • prompt = "\nHow old are you?"
  • prompt += "\nEnter 'quit' when you are finished. "
  • while True:
  • age = input(prompt)
  • if age == 'quit':
  • break
  • age = int(age)
  • if age < 3:
  • print(" You get in free!")
  • elif age < 12:
  • print(" Your ticket is $10.")
  • else:
  • print(" Your ticket is $15.")

运行结果:

  • How old are you?
  • Enter 'quit' when you are finished. 12
  • Your ticket is $15.
  • How old are you?
  • Enter 'quit' when you are finished. 4
  • Your ticket is $10.
  • How old are you?
  • Enter 'quit' when you are finished. 0
  • You get in free!
  • How old are you?
  • Enter 'quit' when you are finished. quit
7.3    使用while循环处理列表和字典

在 Python 中,`while` 循环可以灵活处理列表和字典,尤其适用于需要动态修改容器内容或条件复杂的场景。

1. 处理列表
(1) 遍历列表

  • fruits = ["apple", "banana", "cherry"]
  • index = 0
  • while index < len(fruits):
  • print(fruits[index])
  • index += 1
  • # 输出: apple banana cherry

(2) 动态修改列表

  • # 删除所有偶数
  • numbers = [1, 2, 3, 4, 5, 6]
  • i = 0
  • while i < len(numbers):
  • if numbers[i] % 2 == 0:
  • del numbers[i] # 删除元素后,后续元素前移,索引不需递增
  • else:
  • i += 1 # 未删除时递增索引
  • print(numbers) # 输出: [1, 3, 5]

(3) 条件筛选

  • # 从后向前遍历(避免索引错位)
  • data = [10, 20, 30, 40, 50]
  • i = len(data) - 1
  • while i >= 0:
  • if data[i] > 25:
  • data[i] = data[i] * 2
  • i -= 1
  • print(data) # 输出: [10, 20, 60, 80, 100]

2. 处理字典
(1) 遍历字典键

  • person = {"name": "Alice", "age": 30, "city": "New York"}
  • keys = list(person.keys()) # 转换为列表避免遍历时修改错误
  • index = 0
  • while index < len(keys):
  • key = keys[index]
  • print(f"{key}: {person[key]}")
  • index += 1
  • # 输出: name: Alice \n age:30 \n city:New York

(2) 动态删除键值对

  • # 删除值为空的键
  • user_data = {"name": "Bob", "email": "", "age": 25}
  • keys = list(user_data.keys()) # 先固定键列表
  • index = 0
  • while index < len(keys):
  • key = keys[index]
  • if not user_data[key]: # 值为空则删除
  • del user_data[key]
  • index += 1
  • print(user_data) # 输出: {'name': 'Bob', 'age': 25}

(3) 条件更新字典

  • # 将所有数值类型的值翻倍
  • data = {"a": 10, "b": "hello", "c": 3.14, "d": [1, 2]}
  • keys = list(data.keys())
  • index = 0
  • while index < len(keys):
  • key = keys[index]
  • if isinstance(data[key], (int, float)):
  • data[key] *= 2
  • index += 1
  • print(data) # 输出: {'a':20, 'b':'hello', 'c':6.28, 'd':[1,2]}

练习 7.8 熟食店

创建一个名为sandwich_orders的列表,其中包含各种三明治的名字,再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如“I made your tuna sandwich.”,并将其移到列表finished_sandwiches中。当所有三明治都制作好后,打印一条消息,将这些三明治列出来。
  • sandwich_orders = ['a','b','c']
  • finished_sandwiches = []
  • while sandwich_orders:
  • sandwich = sandwich_orders.pop()
  • finished_sandwiches.append(sandwich)
  • print(f'I made your {sandwich} sandwich')
  • print("\n")
  • for sandwich in finished_sandwiches:
  • print(f"I made a {sandwich} sandwich.")

运行结果

  • I made your c sandwich
  • I made your b sandwich
  • I made your a sandwich
  • I made a c sandwich.
  • I made a b sandwich.
  • I made a a sandwich.
练习 7.9 五香烟熏牛肉卖完了
使用为练习7.8创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:先打印一条消息,指出熟食店的五香烟熏牛肉(pastrami)卖完了;再使用一个while循环将列表sandwich_orders 中的'pastrami'都删除。确认最终的列表finished_sandwiches中未包含'pastrami'。
  • sandwich_orders = ['a','b','c','pastrami','pastrami','pastrami']
  • finished_sandwiches = []
  • print("I'm sorry, we're all out of pastrami today.")
  • while 'pastrami' in sandwich_orders:
  • sandwich_orders.remove('pastrami')
  • while sandwich_orders:
  • sandwich = sandwich_orders.pop()
  • finished_sandwiches.append(sandwich)
  • print(f'I made your {sandwich} sandwich')
  • print("\n")
  • for sandwich in finished_sandwiches:
  • print(f"I made a {sandwich} sandwich.")
练习 7.10 梦想中的度假胜地
编写一个程序,调查用户梦想中的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
  • name_prompt = "\nWhat's your name?"
  • place_prompt = "If you could visit one place in the world, where would it be? "
  • continue_prompt = "Would you like to let someone else respond? (yes/no) "
  • response = {}
  • while True:
  • name = input(name_prompt)
  • place = input(place_prompt)
  • response[name] = place
  • repeat = input(continue_prompt)
  • if repeat == 'no':
  • break
  • print('\n')
  • for name,place in response.items():
  • print(f"{name.title()} would like to visit {place.title()}.")

运行结果

  • What's your name?zzy
  • If you could visit one place in the world, where would it be? hongkong
  • Would you like to let someone else respond? (yes/no) yes
  • What's your name?zzyy
  • If you could visit one place in the world, where would it be? shenyang
  • Would you like to let someone else respond? (yes/no) no
  • Zzy would like to visit Hongkong.
  • Zzyy would like to visit Shenyang.

 

查看本帖全部内容,请登录或者注册
此帖出自编程基础论坛
点赞 关注
 

回复
举报
您需要登录后才可以回帖 登录 | 注册

随便看看
查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/10 下一条
报名最后一周!2025 英飞凌消费、计算与通讯创新大会-北京站
会议时间:3月18日(周二)09:30签到
参会奖励:电动螺丝刀套装、户外登山包、京东卡

查看 »

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

 
机器人开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表