5.Python之input和while

本文深入探讨了Python中while循环和input函数的应用,包括如何利用它们创建交互式程序,处理用户输入,以及如何通过break和continue控制循环流程。此外,还介绍了如何使用while循环进行数据收集和列表操作。
  • 概述
    接收用户输入是程序的一个重要功能,而while循环可以让程序不断运行,直到判断条件不满足为止。
    通过获取用户输入并学会控制程序的运行时间,可编写除交互式程序。

  • input()

##--------input()  get string
message=input("Tell me something,and I will repeat it back to you: ")
print(message)
##--------input() get value
question="How old are you? "
age = input(question)
print(age)

在这里插入图片描述
可以将提示存储到变量中,再讲该变量传递给input()函数。

  • while()
    for循环用于处理集合中的每个元素,而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 += "\nEnter 'quit' to end the program.\n"
message = ""
while message != 'quit':#until to Not-meet
	message =input(prompt)
	print(message)

在这里插入图片描述
美中不足的是把quit也打印出来了,可以通过一个if判断修复这个问题。

prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
message = ""
while message != 'quit':#until to Not-meet
	message =input(prompt)
	if message !="quit":
		print(message)
  • break VS continue
    break:立刻退出循环,不再运行循环中余下的代码,不管条件判断结果如何都退出整个循环。
    任何python循环都可以使用break语句。
    continue:返回到循环开头,并根据条件判断结果决定是否运行。
##==break
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
while True:
	city=input(prompt)
	if(city=='quit'):
		break
	else:
		print("I'd love to go to "+city.title()+" !")

##==continue
current_number=0
while current_number<10:
	current_number+=1;
	if current_number%2==0:
		continue
	else:
		print(current_number)

在这里插入图片描述
while语句需要有停止运行的条件(如果需要停止的话),务必对每个 while循环进行测试。
如果程序陷入无限循环,按Ctrl+C可以停止,关机也好使。

  • 使用while()
##==use while to get infomation
responses={}#dict
polling_active=True
while polling_active:
	name=input("What's your name?\n")
	response=input("Which mountain would you like to climb someday?\n")
	responses[name]=response
	
	repeat=input("Would you like to let another person respond?(yes/no)\n")
	if repeat=='no':
		polling_active=False

在这里插入图片描述
使用while进行调查,获取信息。

pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

while 'cat' in pets:
	pets.remove('cat')
print(pets)

删除包含特定值的列表元素。while一直等到pets中没有cat才退出。

就酱!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值