Python编程:从入门到实践-用户输入和while循环
-
函数input()
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 name = input("Please enter your name: ") 4 print("Hello, " + name + "!")
-
使用int()来获取数值输入
1 2 3 4 | #!/usr/bin/env python #-*- encoding:utf-8 -*- age = input ( "How old are you? " ) print ( int (age)) |
1 2 | How old are you? 21 21 |
示例2:
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 height = input("How old are you? ") 4 height = int(height) 5 6 if height >= 36: 7 print("\nYou're tall enough to ride!") 8 else: 9 print("\nYou'll be able to ride when you're a little older.")
-
求模运算符
求模运算符(%),用来处理数值信息,它将两个数相除并返回余数
1 2 3 4 5 6 7 8 9 | >>> 4 % 3 1 >>> 5 % 3 2 >>> 6 % 3 0 >>> - 7 % 3 2 >>> |
判断奇偶数
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 number = input("Enter a number, and I'll tell you if it's even or odd: ") 4 number = int(number) 5 if number % 2 == 0: 6 print("\nThe number " + str(number) + " is even.") 7 else: 8 print("\nThe nuber " + str(number) + " is odd. ")
-
在Python2.7中获取输入
raw_input读取的内容以字符串的形式返回
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 msg = int(raw_input('How old are you? ')) 4 print('I was ' + str(msg) + ' years old!')

How old are you? 22
I was 22 years old!
-
while循环
For循环用于集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 #counting.py 4 current_number = 1 5 while current_number <= 5: 6 print(current_number) 7 current_number += 1
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 """ 4 使用while循环让程序再用户愿意时不断地运行,并定义一个退出值, 5 只用用户输入的不是这个值,程序就继续运行 6 """ 7 prompt = "\nTell me something, and I will repeat it back to you:" 8 prompt += "\nEnter 'quit' to end the program. " 9 message = "" 10 while message != 'quit': 11 message = input(prompt) 12 print(message)
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 """ 4 在上一个while基础上,修改。将单词'quit'消息不打印 5 """ 6 prompt = "\nTell me something, and I will repeat it back to you:" 7 prompt += "\nEnter 'quit' to end the program. " 8 message = "" 9 while message != 'quit': 10 message = input(prompt) 11 if message != 'quit': 12 print(message)
-
使用标志
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 """ 4 使用标志,在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态, 5 这个变量被成为标志,充当程序的交通信号灯。下列程序将标志命名为active 6 """ 7 prompt = "\nTell me something, and I will repeat it back to you:" 8 prompt += "\nEnter 'quit' to end the program. " 9 active = True 10 while active: 11 message = input(prompt) 12 if message == 'quit': 13 active = False 14 else: 15 print(message)
-
使用break、continue
在循环中使用break
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 prompt = "\nPlease enter the name of a city you have visited." 4 prompt +="\n(Enter 'quit' when you are finished: ) " 5 while True: 6 city = input(prompt) 7 if city == 'quit': 8 break 9 else: 10 print("I'd love to go to " + city.title() + "!")
在循环中使用continue
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 """从1数到10,只打印其中的偶数""" 4 current_number = 0 5 while current_number < 10: 6 current_number += 1 7 if current_number % 2 != 0: 8 continue 9 print(current_number)
-
避免无限循环

1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 x = 1 4 while x <= 5: 5 print(x) 6 x += 1
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 """当遗漏代码行x += 1,这个循环将一直运行""" 4 x = 1 5 while x <= 5: 6 print(x)
-
使用while循环来处理列表和字典
For循环是一个遍历列表的有效方式,但for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。在遍历列表的同事对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
示例:假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户之后,将他们移动到另一个已验证用户列表中?方法是:利用while循环,在验证用户的同时将其从未验证用户列表中提取出来。再将其加入到另一个已验证用户列表中。
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 #首先,创建一个待验证的用户列表和一个存储已验证用户的空列表 4 unconfirmed_users = ['alice', 'brain', 'candace'] 5 confirmed_users = [] 6 #验证每个用户,直到没有未验证用户位置,将每个经过验证的列表都移到已验证用户列表 7 while unconfirmed_users: 8 current_user = unconfirmed_users.pop() 9 print("Verifying user: " + current_user.title()) 10 confirmed_users.append(current_user) 11 #显示所有已验证的用户 12 print("\nThe following users have been confirmed: ") 13 for confirmed_user in confirmed_users: 14 print(confirmed_user.title())
1 2 3 4 5 6 7 8 9 | C:\PyProjects>C: / Python37 / python3.exe c: / PyProjects / demo.py Verifying user: Candace Verifying user: Brain Verifying user: Alice The following users have been confirmed: Candace Brain Alice |
删除包含特定值的所有列表元素
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 4 print(pets) 5 while 'cat' in pets: 6 pets.remove('cat') 7 print(pets)
1 2 3 | C:\PyProjects>C: / Python37 / python3.exe c: / PyProjects / demo.py [ 'dog' , 'cat' , 'dog' , 'goldfish' , 'cat' , 'rabbit' , 'cat' ] [ 'dog' , 'dog' , 'goldfish' , 'rabbit' ] |
使用用户输入来填充字典
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 responses = {} 4 #设置一个标志,指出调查是否继续 5 polling_active = True 6 while polling_active: 7 #提示输入被调查者的名字和回答 8 name = input("\nWhat is your name? ") 9 response = input("Which mountain would you like to climb someday? ") 10 #将答卷存储在字典中 11 responses[name] = response 12 #看看是否还有人要参与调查 13 repeat = input("Would you like to let another person respond? (yes/no)") 14 if repeat == 'no': 15 polling_active = False 16 #调查结束,显示结果 17 print("\n---Poll Results---") 18 for name, response in responses.items(): 19 print(name + " would like to climb " + response + ".")
1 2 3 4 5 6 7 8 9 10 11 12 13 | C:\PyProjects>C: / Python37 / python3.exe c: / PyProjects / demo.py What is your name? tianze Which mountain would you like to climb someday? panshan Would you like to let another person respond? (yes / no)yes What is your name? tiandi Which mountain would you like to climb someday? xiangshan Would you like to let another person respond? (yes / no)no - - - Poll Results - - - tianze would like to climb panshan. tiandi would like to climb xiangshan. |
分类:
Python学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南