python 从想学到坚持
第七章 用户输入和while循环
7.1 函数input()的工作原理
# 函数input()让程序暂停运行,等待用户输入一些文本。
eg: message = input(“Tell me something,and I will repeat it back to you:”)
print(message)
函数input()接收一个参数。
7.1.1 编写清晰的程序
eg(1):
name = input(“Please enter your name:”)
print(“hello,”+name+”!”)
eg(2):
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 + “!”)
#其中运算符+=在储存在prompt 中的字符末尾附加一个字符串。
输出如下
If you tell us who you are,we can personalize the message you see.
What is your first name? Tao
hello, Tao!
7.1.2 使用 int()来获取输入
eg:
age = input(“how old are you?”)
how old are you?21
age=int(age)
age >=18
ture
# 函数input(),python把用户输入解读为字符串。
# 使用int(变量名)进行数据类型转换。
7.1.3 求模运算符
4%3=1
4对 3取余余1
# 还可以判断一个数是奇数还是偶数
number = input(“qingshuruyigeshupanduanjiouxing:”)
number = int(number)
if number % 2 == 0:
print(“\n the number”+str(number)+”is even”)
else:
print(“\n the number”+str(number)+”is odd”)
#注意其中的两次数据转换 int()和str()
7.2 while循环
7.2.1 循环的使用
# 循环输出一到五
current_number = 1
while current_number <= 5:
print(current_number)
current_number +=1
输出结果为
1
2
3
4
5
# 注意while循环后面后有(冒号):不能省略
7.2.2 选择退出循环
# 使用判断语句
prompt = “\nTell me something,and I will repeat it back to :”
prompt += “\nEnter ‘quit’ to end the program.”
message = “”
while message != ‘quit’: // if message != ‘quit’:
message=int(prompt)
print(message)
#我们可以使用 if message != ‘quit’: 隐藏输出的quit
7.2.3 使用标志
active = Ture
while active:
message = input(prompt):
if message == ‘quit’
active = False
else:
print(message)
# 以后游戏上可以游戏是否进行。
7.2.4 使用break退出循环。
if 语句下直接使用 break语句退出 和c类似
7.2.5 在循环中使用continue
if 语句下直接使用
eg:
current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 ==0:
continue
print(current_number)
#判断对2取余是否余数为0 ,是就继续循环,如果是不是输出数字。
7.2.6 避免无限循环。
# 注意代码的书写 和可以使用Ctrl+C 关闭输出窗口
7.3使用while循环来处理列表和字典
7.3.1 在列表之间移动元素
# 首先创建一个待验证用户的列表
# 和一个用于储存已验证用户的空列表
unconfirmed_users = [‘alice’,’brian’,’candace’]
confirmed_users=[]
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_user.pop()
print(“Verifiying user:”+ current.title())
confirmed_users.append(current_user)
print(“\nThe following users have been confirmed:”)
for confirmed_user in confirmed_users:
print(confirmed_user.title())
输出结果 为:
Verifying user:Candace
Verifying user:Brian
Verifying user:Alice
The following users have been confirmed:
Candace
Brian
Alice
#函数.pop()从unconfirmed_user删除末尾没有验证的用户。
7.3.2删除包含特定值的元素列表
pets=[‘dog’,’cat’,’dog’,’goldfish’,’cat’,’rabbit’,’cat’]
print(pets)
while ‘cat’ in pets:
pets.remove(‘cat’)
print(pets)
#删除了cat 函数.remove()
7.3.3 使用用户输入来填充字典
eg:
mountain_poll.py
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 respond?(yes/ no)”)
if repeat == 'no':
polling_active = False
#调查结束,显示结果
print("\n---Poll Result--")
for name, response in responses. items():
print(name + “ would like to climb “+ response +” .”)
# 提示用户输入名字和喜欢爬的山,是否继续接受调查 回复yes or no