Python 3.x 如何验证输入是否不是字母或字符串?
我正在用IDLE编写一个基本程序,其中有一个菜单选项,选项从1到4。 如果用户输入的是数字以外的任何内容,则会给出一个ValueError:invalid literal for int(),以10为基数:“a”Python 3.x 如何验证输入是否不是字母或字符串?,python-3.x,input,menu,Python 3.x,Input,Menu,我正在用IDLE编写一个基本程序,其中有一个菜单选项,选项从1到4。 如果用户输入的是数字以外的任何内容,则会给出一个ValueError:invalid literal for int(),以10为基数:“a” 我如何检查输入是否不是字母,如果是,则打印我自己的错误消息?我不清楚您是否希望测试某个内容是整数还是字母,但我对前一种可能性做出了回应 user_response = input("Enter an integer: ") try: int(user_
我如何检查输入是否不是字母,如果是,则打印我自己的错误消息?我不清楚您是否希望测试某个内容是整数还是字母,但我对前一种可能性做出了回应
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
我对python相当陌生,因此可能有更好的方法来实现这一点,但这就是我在过去测试输入值是否为整数的方法
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
这将检查数字是1、2、3还是4,如果不是,将要求用户再次输入数字,直到符合标准。isalpha()
-这是一种字符串方法,用于检查输入的字符串是字母还是单词(仅字母,没有空格或数字)
此程序具有无限循环,即在输入整数之前,此程序不会停止。我已经为此使用了break and continue关键字。使用您的方法,如果它是int值,我可以让它打印出来。任何其他信息都会给我一个回溯错误。您想如何处理有关它是否为整数的信息?如果您发布了正在处理的代码,可能会有所帮助。
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break