Python编程学习笔记,第7记:用户输入和while循环
在本节中,将学习:如何在程序中使用 input()来让用户提供信息、如何处理文本和数字的输入、如何使用while循环让程序按要求不断的运行、多种控制while循环的方式:设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素、如何从列表中删除所有包含特定值的元素、如何使用while循环和字典。
目录
# 1.函数input()的工作原理.
- # 函数input()接受一个参数:即向用户显示提示或说明,让用户知道该如何做.等待用户输入,并在用户按回车键后继续运行.
- # 每当使用函数input()时,都应当指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息.
# 通过获取用户输入并学会控制程序的运行时间,可编写出交互式程序.
# 1.函数input()的工作原理.
message = input("Tell me something, and I will repeat it back to you: ") # (提示用户输入信息,输入:hello)
print(message)
输出结果为:
Tell me something, and I will repeat it back to you: hello
hello
# 创建多行字符串的一种方式
- # 创建多行字符串的一种方式
- # 如果提示信息超过一行,可将提示信息存储在一个变量中,再将该变量传递给函数input().
- # 运算符+=在存储在prompt中的字符串末尾附加一个字符串.
# 创建多行字符串的一种方式
# 函数input()接受一个参数:即向用户显示提示或说明,让用户知道该如何做.等待用户输入,并在用户按回车键后继续运行.
# 每当使用函数input()时,都应当指定清晰而易于明白的提示,准确地指出你希望永华提供什么样的信息.
# 如果提示信息超过一行,可将提示信息存储在一个变量中,再将该变量传递给函数input().
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat's your name? "
name = input(prompt)
print("\nHello, " + name + "!")
# 运算符+=在存储在prompt中的字符串末尾附加一个字符串.
输出结果为:
If you tell us who you are, we can personalize the messages you see.
What's your name? Emy
Hello, Emy!
# 2.使用int()来获取数值输入
- # 由于使用函数input()时,Python将用户的输入解读为字符串.
- # 因此,当我们需要的的是数值时,需要用函数int()将数字的字符串表示转换为数值表示.
- # 将数值用于计算或比较前,务必将其转换为数值表示.
# 2.使用int()来获取数值输入
# 由于使用函数input()时,Python将用户的输入解读为字符串.
# 因此,当我们需要的的是数值时,需要用函数int()将数字的字符串表示转换为数值表示.
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("You are tall enough to ride!")
else:
print("You wiil be able to ride when you're a little older!!!")
输出结果为:
How tall are you, in inches? 32
You wiil be able to ride when you're a little older!!!
如果写成以下形式,输入数字后,肯定会报错,想想为什么??
height = input("How tall are you, in inches? ")
# height = int(height)
if height >= 36:
print("You are tall enough to ride!")
else:
print("You wiil be able to ride when you're a little older!!!")
# 3.求模运算
- # 求模运算符 % ,它将两个数相除并返回余数.
- # 如果一个数能被另外一个数整除,余数就是0,求模运算符将返回零.因此,可利用这一点判断一个数是奇数还是偶数.
# 3.求模运算
# 求模运算符 % ,它将两个数相除并返回余数.
# 如果一个数能被另外一个数整除,余数就是0,求模运算符将返回零.因此,可利用这一点判断一个数是奇数还是偶数.
# even_or_odd 偶数能被2整除,奇数不能.
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.")
输出结果为:
Enter a number, and I'll tell you if it's even or odd: 24
The number 24 is even.
# 4.while循环
- # for循环用于针对集合中的每个元素的一个代码块,而while循环不断的运行,直到指定条件不满足为止.
- # Python中最简单的循环机制是while.
# 4.while循环
# for循环用于针对集合中的每个元素的一个代码块,而while循环不断的运行,直到指定条件不满足为止.
# Python中最简单的循环机制是while.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# 该while循环中,current_number的初始值为1,从而从1开始,每次执行完循环体后,current_number的值都加1,
# 只要其值小于或等于5,循环就会一直执行下去.直到current_number大于5不满足条件,while循环停止,整个程序结束.
输出结果为:
1
2
3
4
5
# 4.1让用户选择何时退出while循环
# 4.1让用户选择何时退出while循环
prompt = "\nTell me something, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
输出结果为:
Tell me something, and I'll repeat it back to you:
Enter 'quit' to end the program. Hello everyone
Hello everyone
Tell me something, and I'll repeat it back to you:
Enter 'quit' to end the program. Hello again!!
Hello again!!
Tell me something, and I'll repeat it back to you:
Enter 'quit' to end the program. quit
quit
- # 在上面这个程序中,只要用户输入的不是单词'quit',循环就会再次显示提示消息并等待用户输入.直到用户输入了'quit',循环就终止,整个程序结束.
# 4.2使用标志让循环退出
- # 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态.
- # 这个变量被称为标志,充当了程序的交通信号灯.
# 4.2使用标志让循环退出
# 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态.
# 这个变量被称为标志,充当了程序的交通信号灯.
prompt = "\nTell me something, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "
active = True # 名为active的标志
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
输出结果为:
Tell me something, and I'll repeat it back to you:
Enter 'quit' to end the program. Hello AAA
Hello AAA
Tell me something, and I'll repeat it back to you:
Enter 'quit' to end the program. quit
# 4.3使用break退出循环
- # 要立即退出while循环,不再运行循环中余下的代码,也不管测试条件的结果如何,可以使用break语句.
- # break语句用于控制程序循环,可使用它来控制哪些代码行将执行,哪些代码行不执行.
# 4.3使用break退出循环
# 要立即退出while循环,不再运行循环中余下的代码,也不管测试条件的结果如何,可以使用break语句.
# break语句用于控制程序循环,可使用它来控制哪些代码行将执行,哪些代码行不执行.
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("I'd love to go to " + city.title() + "! ")
输出结果为:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) Hk
I'd love to go to Hk!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
# 4.4 再循环中使用continue
- # 要返回到循环的开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句.
# 4.4 再循环中使用continue
# 要返回到循环的开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句.
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
输出结果为:
1
3
5
7
9
# 4.6 避免无限循环
- # 每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去.
- # 要避免编写无限循环,务必对每个while循环进行条件测试,确保它按预期的那样执行.
# 5.使用while循环来处理列表和字典
- # for循环是一种遍历列表的有效方式,但在for循环中不应修改列表中的值,否则将导致Python难以跟踪其中的元素.
- # 要在遍历列表的同时对其进行修改,可使用while循环.
# 5.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())
输出结果为:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed.
Candace
Brian
Alice
# 5.2删除列表中包含特定值的所有元素
- # 使用while循环和函数remove()来删除列表中等于特定值的所有元素.
# 5.2删除列表中包含特定值的所有元素
# 使用while循环和函数remove()来删除列表中等于特定值的所有元素.
pets = ['dog', 'cat', 'goldfish', 'dog', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
输出结果为:
['dog', 'cat', 'goldfish', 'dog', 'cat', 'rabbit', 'cat']
['dog', 'goldfish', 'dog', 'rabbit']
# 6.使用用户输入来填充字典
- # 可使用while循环提示用户输入任意数量的信息.
# 6.使用用户输入来填充字典
# 可使用while循环提示用户输入任意数量的信息.
responses = {}
# 设置一个标志,指出调查是否继续.
polling_active = True
while polling_active:
# 提示输入被调查者的名字和答案.
name = input("\nWhat's 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 Results-------")
for name, response in responses.items():
print(name.title() + " would you like to climb " + response.title() + ".")
输出结果为:
What's your name? Amy
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/no) yes
What's your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/no) no
------Poll Results-------
Amy would you like to climb Denali.
Lynn would you like to climb Devil'S Thumb.
-
有志者事竟成。