第 7 章 用户输入和while循环

7.1 函数input()的工作原理

message = input("Tell me something, and I will repeat it back to you: ")

print(message)

7.1.1 编写清晰的程序

name = input("Please enter your name: ")

print("Hello, " + name + "!")

prompt = "If you tell us who you are, we can personalize the message you see."

prompt += "\nWhat is your first name? "

name = input(prompt)

print("\nHello, " + name + "!")

7.1.2 使用int()来获取数值输入

age = input("How old are you? ")

print("I'm " + str(age) + ".") # 可转化为字符串再打印输出,间接的赋值数字必须转化为字符串再输出打印,否则打印会出错

print("I'm " + age + ".") # 输入的数字age为字符串可直接打印

age = input("How old are you? ") # 此处age为字符串,需用int()转换为数字才能跟数字比较大小

age >= 18

age = input("How old are you? ")

age = int(age)

if age >= 18:

print("Yes!")

判断一个人是否满足坐过山车的身高要求

height = input("How tall are you, in inches? ")

height = int(height)

if height >= 36:

print("\nYou 're tall enough to ride!")

else:

print("\nYou'll be able to ride when you're a little older.")

7.1.3 求模运算符

a = 4 % 3

print(a)

b = 5 % 3

print(b)

c = 6 % 3

print(c)

如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。

你可利用这一点来判断一个数是奇数还是偶数。

number = input("Enter a number, and I'll tell you if it's even or odd: ")

number = int(number)

if number % 2 == 0:

print("\nThe number " + str(number) + " is even.")

else:

print("\nThe number " + str(number) + " is odd.")

如果你使用的是Python 2.7,应使用函数raw_input() 来提示用户输入。这个函数与Python 3中的input() 一样,也将输入解读为字符串。

7-1 汽车租赁

car = input("What kind of car would you like? ")

print("Let me see if I can find you a " + car.title() + ".")

7-2 餐馆订位

number = input("How many people are in your dinner party tonight? ")

number = int(number)

if number > 8:

print("I'm sorry, you'll have to wait for a table.")

else:

print("Your table is ready.")

7-3 10的整数倍

number = input("Please enter a number: ")

number = int(number)

if number % 10 == 0:

print(str(number) + " is a multiple of 10.")

else:

print(str(number) + " is not a multiple of 10.")

7.2.1 使用while循环

current_number = 1

while current_number <= 5:

print(current_number)

current_number += 1 # current_number = current_number + 1

7.2.2 让用户选择何时退出

prompt = "\nTell me something, and I will repeat it back to you:"

prompt += "\nEnter 'quit' to end the program."

message = ""

while message != 'quit':

message = input(prompt)

print(message)

prompt = "\nTell me something, and I will repeat it back to you:"

prompt += "\nEnter 'quit' to end the program."

message = ""

while message != 'quit':

message = input(prompt)

if message != 'quit':

print(message)

7.2.3 使用标志

prompt = "\nTell me something, and I will repeat it back to you:"

prompt += "\nEnter 'quit' to end the program. "

active = True

while active:

message = input(prompt)

if message == 'quit':

active = False

else:

print(message)

7.2.4 使用break 退出循环

注意 在任何Python循环中都可使用break 语句。例如,可使 用break 语句来退出遍历列表或字典的for 循环。

prompt = "\nPlease enter the name of a city you have visited:"

prompt += "\n(Enter 'quit' when you are finished.) "

while True:

city = input(prompt)

if city == 'quit':

break

else:

print("\nI'd love to go to " + city.title() + ".")

7.2.5 在循环中使用continue

current_number = 0

while current_number < 10:

current_number += 1

if current_number % 2 == 0:

continue

print(current_number)

7.2.6 避免无限循环

x = 1

while x <= 5:

print(x)

x += 1 # 没这句程序会无限循环下去

7-4 披萨配料

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(" I will add " + topping + " to your pizza.")

else:

break

7-5 电影票

prompt = "\nHow old are you? We will tell you the prize."

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 dollars.")

else:

print(" Your ticket is 15 dollars.")

7-6 三个出口

prompt = "\nWhat topping would you like on your pizza?"

prompt += "\nEnter 'quit' when you are finished: "

active = True

while active:

topping = input(prompt)

if topping != 'quit':

print(" I will add " + topping + " to your pizza.")

else:

active = False

7.3.1 在列表之间移动元素

首先,创建一个待验证用户列表和⼀个⽤于存储已验证⽤户的空列表

unconfirmed_users = ['alice', 'brian', 'candace']

confirmed_users = []

验证每个用户,直到没有未验证用户为止

将每个经过验证的列表都移到已验证用户列表中

while unconfirmed_users:

current_user = unconfirmed_users.pop()

print("Verifying user: " + current_user.title())

confirmed_users.append(current_user)

显示已验证的用户

print("\nThe following users have been confirmed:")

for confirmed_user in confirmed_users:

print(confirmed_user.title())

7.3.2 删除包含特定值的所有列表元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

print(pets)

while 'cat' in pets:

pets.remove('cat')

print(pets)

7.3.3 使用用户输入来填充字典

responses = {}

设置一个标志,指出调查是否继续

polling_active = True

while polling_active:

# 提示输入被调查者的名字和回答

name = input("\nWhat is your name? ")

response = input("Which mountain would you like to climb someday? ")

# 将答卷存储在字典中

responses[name] = response

# 看看是否还有人要参与调查

repeat = input("Would you like to let another person response? (yes/no) ")

if repeat == 'no':

polling_active = False

# 调查结束,显示结果

print("\n--- Poll Results ---")

for name, response in responses.items():

print(name.title() + " would like to climb " + response.title() + ".")

7-8 熟食店

sandwich_orders = ['tuna', 'veggie', 'grilled cheese', 'turkey', 'roast beef']

finished_sandwiches = []

for sandwich in sandwich_orders:

print("\nI made your " + sandwich + " sandwich.")

finished_sandwiches.append(sandwich)

print("Here are the finished sandwiches:")

for sandwich in finished_sandwiches:

print(sandwich)

sandwich_orders = ['tuna', 'veggie', 'grilled cheese', 'turkey', 'roast beef']

finished_sandwiches = []

while sandwich_orders:

current_sandwich = sandwich_orders.pop()

print("I'm working on your " + current_sandwich + " sandwich.")

finished_sandwiches.append(current_sandwich)

print("\n")

for sandwich in finished_sandwiches:

print("I made a " + sandwich + " sandwich.")

7-9 五香烟熏牛肉(pastrami)卖完了

sandwich_orders = ['pastrami', 'tuna', 'pastrami', 'veggie', 'grilled cheese', 'pastrami', 'turkey', 'roast beef']

finished_sandwiches = []

print("I'm sorry, we're all out of pastrami today.")

while sandwich_orders:

current_sandwich = sandwich_orders.pop()

if current_sandwich != 'pastrami':

finished_sandwiches.append(current_sandwich)

print("I'm working on your " + current_sandwich + " sandwich.")

print("\n")

for sandwich in finished_sandwiches:

print("I made a " + sandwich + " sandwich.")

sandwich_orders = ['pastrami', 'tuna', 'pastrami', 'veggie', 'grilled cheese', 'pastrami', 'turkey', 'roast beef']

finished_sandwiches = []

print("I'm sorry, we're all out of pastrami today.")

while 'pastrami' in sandwich_orders:

sandwich_orders.remove('pastrami')

print("\n")

while sandwich_orders:

current_sandwich = sandwich_orders.pop()

print("I'm working on your " + current_sandwich + " sandwich.")

finished_sandwiches.append(current_sandwich)

print("\n")

for sandwich in finished_sandwiches:

print("I made a " + sandwich + " sandwich.")

7-10 梦想的度假胜地

responses = {}

name_prompt = "\nWhat's your name? "

place_prompt = "If you want to visit one place in the world, what would it be? "

continue_prompt = "\nWould you like to let someone else respond? (yes/no) "

while True:

name = input(name_prompt)

place = input(place_prompt)

responses[name] = place

repeat = input(continue_prompt)

if repeat != 'yes':

break

print("\n--- Results ---")

for name, place in responses.items():

print(name.title() + " would like to visit " + place.title() + ".")

python第七章_Python第七章相关推荐

  1. python第七章_python 第七章 模块

    模块 一个py文件就是一个模块 模块一共三种:1.python标准库 2.第三方模块 3.应用程序自定义模块 import:1.执行对应文件 2.引入变量名 if__name__="__ma ...

  2. python实现列表去重_python实现七种列表去重方法

    #encoding=utf-8import timetime_start=time.time()print u"列表去重的七种方法"print u"第一种测试方法&quo ...

  3. python控制语句第一章_python基础第一章

    Python基础 第一个python程序 变量 程序交互 基本数据类型 格式化输出 基本运算符 流程控制if...else... 流程控制-循环 第一个python程序 文件执行 1.用notepad ...

  4. python教材答案第六章_python第六章{输入和输出}

    输出 用print加上字符串,就可以向屏幕上输出指定的文字.比如输出'hello, world',用代码实现如下: >>>print 'hello, world' print语句也可 ...

  5. python第七关_Python 基础(七)

    封面图片来源:沙沙野 内容概览字典的相关概念 字典的增 字典的删 字典的改 字典的查 字典的其他操作 字典的四种创建方式 字典的相关概念前面提到了列表,列表的缺点体现在:列表如果存储大量的数据,查找速 ...

  6. python列表 行列选择_Python第七课——如何选取excel表格的行数据和列数据

    # Section0 print("-"*30 + "Begin Section 0 开场" + "-"*30) print("l ...

  7. python第七章文件和数据格式化选择题_《计算机二级Python语言程序设计考试》第7章:文件和数据格式化...

    注明:本系列课程专为全国计算机等级考试二级 Python 语言程序设计考试服务 目录 考纲考点 文件的使用: 文件打开.关闭和读写 数据组织的维度:一维数据和二维数据 一维数据的处理:表示.存储和处理 ...

  8. Python基础_第3章_Python中的循环结构

    Python基础_第3章_Python中的循环结构 文章目录 Python基础_第3章_Python中的循环结构 Python中的循环结构 一.回顾分支练习题 1.判断是否为一个合法三角形 2.求世界 ...

  9. Python基础_第2章_Python运算符与if结构

    Python基础_第2章_Python运算符与if结构 文章目录 Python基础_第2章_Python运算符与if结构 Day02之`Python运算符与if结构` 一.昨日回顾 1.回顾昨天的课程 ...

最新文章

  1. 顶刊发文奖励100万!不唯论文后,这所中科院研究院的激励机制引发争议
  2. 【强化学习】数据科学,从计算到推理
  3. 英伟达显卡不同架构_英伟达新款笔记本显卡全阵容曝光:共计六款
  4. wordpress 静态化 linux,WordPress如何静态化
  5. MySQL 高级 loop循环
  6. sas sql中有类似mysql的 g_SAS中的SQL
  7. 优化算法笔记|粒子群算法理解及Python实现
  8. 如何解决系统补丁(KB971092)重复安装问题
  9. mysql 正则截取字符串_mysql字符串查找截取与正则表达式的联合应用 | 学步园
  10. n-1 java_【Java】 剑指offer(53-2) 0到n-1中缺失的数字
  11. Win10系统怎么看隐藏文件夹
  12. FJUT Home_W的gcd(乱搞)题解
  13. 安装linux-mysql-yum方式
  14. Simulink永磁同步电机控制仿真系列八:使用自抗扰控制(adrc)实现速度闭环以及扰动估计
  15. vue 阻止输入框冒泡
  16. js 检测浏览器开发者控制台是否被打开
  17. xp系统打印机服务器报错,互联网要点:Win7系统连接XP共享打印机报错0X000004如何解决...
  18. 英语影视台词---无敌破坏王2大脑互联网
  19. win10分屏快捷键无法使用_Win10分屏操作,再也不用来回切换视图了!
  20. ROUGE评价算法学习

热门文章

  1. Python报错: RuntimeError: The current Numpy installation (‘D:\\Develop\\anaconda\\lib\\site-packages\\
  2. 360浏览器清凉新版让手机解暑
  3. 新加坡推出人工智能计划AI.SG 迎战人工智能和数据科学关键难题
  4. java常见面试题及答案 1-10(基础篇)
  5. C代码工具--自动生成enum值和名字映射代码
  6. linux下svn常用命令集锦
  7. 大访问量网站缓存的一点思考,个人看法,勿拍砖
  8. 计算机导航医学应用,【2016年】计算机导航在全膝关节置换中的应用技术及进展【临床医学论文】.doc...
  9. SCCM2012系列之六,SCCM2012部署前的WDS准备
  10. php开发_图片验证码