python编程如何在输入一次进行循环-编程字典-使用Python实现一个循环输入

本文介绍了如何在Python中使用while循环结合try-except和自定义验证规则来获取用户输入,并提供了一个通用的输入函数`sanitised_input`,支持指定输入类型、范围和值检查。
摘要由CSDN通过智能技术生成

使用Python实现一个循环输入

实现此目的的最简单方法是将input方法放在while循环中。当你输入错误时使用continue,break当你满意时使用break。

当您的输入可能会引发异常时

使用try和catch检测用户何时输入无法解析的数据。

while True:代码地址:codingdict.com/article/22038

try:

# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input

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

except ValueError:

print("Sorry, I didn't understand that.")

#better try again... Return to the start of the loop

continue

else:

#age was successfully parsed!

#we're ready to exit the loop.

break

if age >= 18:

print("You are able to vote in the United States!")

else:

print("You are not able to vote in the United States.")

实现自己的验证规则

如果要拒绝Python可以成功解析的值,可以添加自己的验证逻辑。

while True:

data = input("Please enter a loud message (must be a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值