整数和字符串的Python输入验证 [英] Python input validation for both integer and string
本文介绍了整数和字符串的Python输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是编程新手,在进行输入验证时遇到问题.
我的程序需要输入1到10之间的数字或字母y
,但是看来我无法为此执行错误处理程序.
I'm new in programming and I have an issue when doing the input validation.
My program requires to input number from 1 to 10 or the letter y
but it seems that I cannot do an error handler for this.
def checkingInput():
while True:
try:
a = input()
if 10 >= a >= 1 or a == 'y':
return value
else:
print('Invalid input!')
except NameError:
print('Name error!Please try again!')
except SyntaxError:
print('Syntax Error!Please try again!')
推荐答案
jamylak建议将if条件更改为:
as jamylak suggested change the if condition to :
if a == 'y' or 1 <= int(a) <= 10:
程序:
def checkingInput():
while True:
try:
a = input('enter')
if a == 'y' or 1 <= int(a) <= 10:
return a
else:
print('Invalid input!')
except ValueError:
print('Value error! Please try again!')
这篇关于整数和字符串的Python输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文