1 函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便以后使用。
例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:
1
2
3#parrot.py message = input("Tell me something, and I will repeat it back to you: ") print(message)
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
1.1 编写清晰的程序
1
2
3#greeter.py name = input("Please enter your name: ") print("Hello, " + name + "! ")
输出:
Please enter your name: Eric
Hello, Eric!
有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input()语句也非常清晰。
1
2
3
4
5#greeter.py prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "n What is your first name? " name = input(prompt) print("nHello, " + name + "! ")
输出:
If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!
1.2 使用int()来获取数值输入
函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示,如下所示:
1
2
3
4age = input("How old are you? ") age = int(age) print(age >= 18)
若输入大于等于18的值则输出
True。
如何在实际程序中使用函数int()呢?请看下面的程序,它判断一个人是否满足坐过山车的身高要求:
1
2
3
4
5
6
7#rollercoaster.py 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.")
如果输入的数字大于或等于36,我们就告诉用户他满足身高条件:
How tall are you, in inches? 71
You're tall enough to ride!
将数值输入用于计算和比较前,务必将其转换为数值表示。
1.3 求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数。
如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。你可利用这一点来判断一个数是奇数还是偶数:
1
2
3
4
5
6
7#even_or_odd.py 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: 42
The number 42 is even.
2 while循环简介
2.1 使用while循环
你可以使用while循环来数数,例如,下面的while循环从1数到5:
1
2
3
4
5#counting.py current_number = 1 while current_number <= 5: print(current_number) current_number += 1
输出:
1
2
3
4
5
2.2 让用户选择何时退出
1
2
3
4
5
6
7#parrot.py 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)
不管用户输入是什么,都将存储到变量message中并打印出来;接下来,Python重新检查while语句中的条件。只要用户输入的不是单词’quit', Python就会再次显示提示消息并等待用户输入。等到用户终于输入’quit'后,Python停止执行while循环,而整个程序也到此结束:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Helloeveryone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
这个程序很好,唯一美中不足的是,它将单词’quit’也作为一条消息打印了出来。为修复这种问题,只需使用一个简单的if测试:
1
2
3
4
5
6
7
8#parrot.py 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)
现在,程序在显示消息前将做简单的检查,仅在消息不是退出值时才打印它:
Tell me something, and I will repeat it back to you
Enter 'quit' to end the program. Helloeveryone!Hello everyone!
Tell me something, and I will repeat it back to you
Enter 'quit' to end the program. Helloagain.Hello again.
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
2.3 使用标志
下面来在前一节的程序parrot.py中添加一个标志。我们把这个标志命名为active(可给它指定任何名称),它将用于判断程序是否应继续运行:
1
2
3
4
5
6
7
8
9
10#parrot.py 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)
2.4 使用break退出循环
1
2
3
4
5
6
7
8
9#parrot.py prompt = "nTell me something, and I will repeat it back to you:" prompt += "nEnter 'quit' to end the program. " 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.) NewYork
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) SanFrancisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
注意在任何Python循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。
2.5 在循环中使用continue
1
2
3
4
5
6
7#counting.py current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number)
输出:
1
3
5
7
9
3 使用while循环来处理列表和字典
要记录大量的用户和信息,需要在while循环中使用列表和字典。
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
3.1 在列表之间移动元素
假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#confirmed_users.py # 首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 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
3.2 删除包含特定值的所有列表元素
假设你有一个宠物列表,其中包含多个值为’cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值’cat',如下所示:
1
2
3
4
5
6#pets.py pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
输出:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
3.3 使用用户输入来填充字典
可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#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 Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
输出:
最后
以上就是怕孤独麦片最近收集整理的关于Python编程从入门到实践(六)-用户输入和while循环的全部内容,更多相关Python编程从入门到实践(六)-用户输入和while循环内容请搜索靠谱客的其他文章。
发表评论 取消回复