Python基础(五) 用户输入和while循环


本人是个新手,写下博客用于自我复习、自我总结。
如有错误之处,请各位大佬指出。
参考教材:Python编程从入门到实践


1. input()

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
例如:

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

也就是说,每当使用input()函数时,都应该指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息。这个提示也可以是变量,例如:

prompt="If you tell us who you are, we can personalize the messages you see."
prompt+="\nWhat is your first name: "
name=input(prompt)
print("\nHello, "+name+"!")

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

如果输入的是个数值,用input()函数后,这个数值就会先变成字符,而不是把它当作数值看待。这时候可以用int(),例如:

age=input("How old are you?")
age=int(age)
if age >= 18:
	print("You are old")
else:
	print("You are young")

求模运算符

求模运算符不会指出一个数是另一个数的多少倍,而只是指出余数是多少。

如果一个数可被另一个数整除,求模运算符就返回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.")

2.while循环

while循环会不断运行,直到指定的条件不满足,例如:

current_number=1
while current_number <=5:
	print(current_number)
	current_number+=1
	
prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\n Enter 'quit' to end the program."
message=""
while message!='quit':
	message=input(prompt)
	if message !='quit':
		print(message)

这里的message一定要先创建一个空字符串,让Python首次执行while时,有可供检查的东西,否则会报错。

使用标志

在未来,可能会有很多条件都满足才会继续运行的程序。在一条while语句中检查所有条件,将复杂又困难。这时可定义一个变量,用于判断整个程序是否处于活动状态,充当了程序的交通信号灯。这个变量称为标志。

例如:

prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\n Enter 'quit' to end the program."
active=True
while active:
	message=input(prompt)
	if message =='quit':
		active=False
	else:
		print(message)

使用break退出循环

在任何Python循环中都可以使用break语句。

使用continue回到循环开头

避免无限循环! (使用Ctrl+C关闭窗口)

3.使用while循环来处理列表和字典

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

在列表之间移动元素

例如:

#一个待验证用户列表和一个用于存储已验证用户的空列表
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
#验证每个用户,并将经过验证的列表都移动已验证用户列表中
while unconfirmed_users:
	current_user=unconfirmed_users.pop()
	print("Verifying user: "+current_user)
	confirmed_users.append(current_user)
#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
	print(confirmed_user.title())

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

之前的方法remove()删除特定值时,是因为要删除的值在列表中只出现了一次。

如果要删除列表中所有包含特定值的元素,可用while循环

例如:

pets=['cat','cat','dog','goldfish','rebbit','dog','cat']
print(pets)
while 'cat' in pets:
	pets.remove('cat')
print(pets)

使用用户输入来填充字典

例如:

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+".")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只爭朝夕不負韶華

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值