首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

编程字典-使用Python实现一个循环输入

使用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 all caps): ")

if not data.isupper():

print("Sorry, your response was not loud enough.")

continue

else:

#we're happy with the value given.

#we're ready to exit the loop.

break

while True:

data = input("Pick an answer from A to D:")

if data.lower() not in ('a', 'b', 'c', 'd'):

print("Not an appropriate choice.")

else:

break

结合异常处理和自定义验证

上述两种技术都可以组合成一个循环。

while True:

try:

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

except ValueError:

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

continue

if age

print("Sorry, your response must not be negative.")

continue

else:

#age was successfully parsed, and we're happy with its value.

#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.")

将其全部封装在一个函数中

如果您需要向用户询问许多不同的值,将此代码放在函数中可能很有用,因此您不必每次都重新键入它。

def get_non_negative_int(prompt):

while True:

try:

value = int(input(prompt))

except ValueError:

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

continue

if value

print("Sorry, your response must not be negative.")

continue

else:

break

return value

age = get_non_negative_int("Please enter your age: ")

kids = get_non_negative_int("Please enter the number of children you have: ")

salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

把它放在一起

您可以扩展这个想法,以创建一个非常通用的输入函数:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):

if min_ is not None and max_ is not None and max_

raise ValueError("min_ must be less than or equal to max_.")

while True:

ui = input(prompt)

if type_ is not None:

try:

ui = type_(ui)

except ValueError:

print("Input type must be .".format(type_.__name__))

continue

if max_ is not None and ui > max_:

print("Input must be less than or equal to .".format(max_))

elif min_ is not None and ui

print("Input must be greater than or equal to .".format(min_))

elif range_ is not None and ui not in range_:

if isinstance(range_, range):

template = "Input must be between and ."

print(template.format(range_))

else:

template = "Input must be ."

if len(range_) == 1:

print(template.format(*range_))

else:

print(template.format(" or ".join((", ".join(map(str,

range_[:-1])),

str(range_[-1])))))

else:

return ui

使用如下:

age = sanitised_input("Enter your age: ", int, 1, 101)

answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))yu

原文:编程字典Python专题

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181109A0GVVW00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券