Python基础【while与input】

大多数人在利益面前是没有人性可言的,这也正是那些在利益面前选 择情义的人被我们尊重的原因之一。

一、input输入

input 用于接收用户输入,括号内的文字会显示给用户作为输入提示。比如,需要用户输入姓名、输入年龄、比萨的配料等。

 message=input("Please enter the toppings for your pizza: ")
print("Ok, we will add "+message+" for you .")

 【注意】

1、如果输入的是数字,python默认把数字当成字符串,这时需要用  变量=int(变量)  来把字符转成我们想要的数字。否则会报错。

#将数值输入用于计算和比较时,务必将其转换为数值表示。

age=input("Please enter your age : ")
age=int(age)

if age<18:
    print("You can't see this ,just to finish your homework my kid.")

2、注意看我上面两个例子的input括号内的冒号后面是有一个空格的,这样会使用户输入时更清晰。

3、每当你使用函数input()时,都应指定清晰而易于明白的提示,准确指出你希望用户提供什么样的信息。

二、while循环

1、while 循环的功能:当满足某个条件就反复做某事。当不满足就跳出循环不做。

使用举例:

让用户选择何时退出:

prompt ="\n Tell me something and I will repeat it back to you : "
prompt+="\nEnter 'quit' if you want to end the program. "

message=""
while message !='quit':
    message=input(message)
    print(message)

【注】python首次执行whie语句时,需要将message 的值与“ quit ” 进行比较,但此时用户还没有输入,如果没有可以比较的内容python将无法继续执行,所以给message指定了一个空字符串作为初始值。虽然为空,但只要不是quit python 就会执行下去。

2、使用break退出循环,使用continue跳出当前循环。

3、使用标志。

实际应用中,可能有多种因素导致退出循环。比如,游戏中人物没血了会结束,城堡被攻破会结束,敌人投降会结束。

面对多种条件都可以退出循环的情况,我们使用一个标志。比如,初始标志active=True,只要任何一个条件不满足就令其为False,让while 循环判断这一个标志就能保证任何一个因素不满足就结束循环。

4、使用while处理列表

比如,把符合要的新注册用户转移到已审核完成的用户列表中。。

#首先,创建两个列表用来存储未验证通过和已验证通过的用户名单。
unconfirmed_users=['xiaoMing','Hong','Jack','Vincent']
confirmed_users=['hong']

#用while循环验证用户,直到示验证用户列表为空
unconfirmed_users=[x.lower() for x in unconfirmed_users]
while unconfirmed_users:
	for user in unconfirmed_users:
		if user in confirmed_users:
			print('Sorry '+user+' has been used.')
			unconfirmed_users.remove(user)
			continue
		else :
			print(user+' has been confirmed.')
			confirmed_users.append(user)
			unconfirmed_users.remove(user)
print(confirmed_users)

5、删除包含特定值的列表元素。如下例:

pets=['peg','peacock','peg','eagle','dolphin','peg',]
print(pets)

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

6、使用用户输入来填充字典:

responses={}
active=True
while active:
	name=input("\nWhat is your name: ")
	response=input("which mountain would you like to climb someday: ")
	
	responses[name]=response
	repeat=input("anythone else: ")
	if repeat=='no':
		active=False
print("\n======Result======")
for name,response in responses.items():
	print(name.title()+" would like to climb "+response.title())

【注意】在遍历键值对的时候别忘记列表后面的 .items()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

纸城

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

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

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

打赏作者

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

抵扣说明:

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

余额充值