[英]Input failing when user inputs a letter. I want to check to make sure they have put in a number
Hi I am trying to check if the user has put in a letter and then let them know it is a letter and they need to put in a number.嗨,我正在尝试检查用户是否输入了一封信,然后让他们知道这是一封信,他们需要输入一个数字。
it keeps giving me a error whenever this happens, I understand it may be because I am trying to convert a int to a string but I am at a lose to trying to figure this out.每当发生这种情况时,它都会给我一个错误,我知道这可能是因为我正在尝试将 int 转换为字符串,但我无法弄清楚这一点。
I thought the below code would check to see if its a number input and fail it or pass it depending on what they put.我认为下面的代码会检查它是否是一个数字输入并根据他们输入的内容失败或通过它。 however it doesn't seem to work.
但是它似乎不起作用。
is there anyway around this.有没有办法解决。
def weapons_(numguns,numknifes,numbombs,numswords):
print(numguns)
aaa = int(str(input("""Enter you're number accordinly to the list above:""")))
while True:
try:
number = int(aaa)
print("this is a num, thank you")
break
except ValueError:
print("this is not a number, please try again")
if aaa <= 50:
print (x)
elif aaa <= 100:
print (y)
elif 101 <= 150:
print (m + p)
elif 151 <= 200:
print (z)
weapons_("numguns","numknifes","numbombs","numswords")
Try this function:试试这个功能:
def isNum (var):
flag = True
while (flag):
try:
val = int(var)
flag = False
except ValueError:
var = input("No.. input is not a number! Please enter a number: ")
return int(var)
It keeps asking for a number until the input value is an int
.它一直要求一个数字,直到输入值是一个
int
。 It finally returns the value as output.它最终将值作为输出返回。
Here is a sample screenshot of the output: sample这是输出的示例屏幕截图: sample
Try this code.试试这个代码。 I put the variables x, y, m, p, z into quotes since they were not defined.
我将变量 x、y、m、p、z 放在引号中,因为它们没有被定义。 Since you've casted aaa into a number, You should not use aaa anymore to compare with (50, 100, etc.) but the variable number instead.
由于您已将 aaa 转换为数字,因此您不应再使用 aaa 与 (50, 100, etc.) 进行比较,而应使用变量 number 进行比较。 In addition, if the cast fails, the code will show the exception message and ask the use for a new number.
此外,如果转换失败,代码将显示异常消息并要求使用新号码。
while True:
try:
aaa = input("""Enter you're number accordinly to the list above:""")
number = int(aaa)
print("this is a num, thank you")
if number <= 50:
print ("x")
elif number <= 100:
print ("y")
elif 101 <= 150:
print ("m + p")
elif 151 <= 200:
print ("z")
break
except ValueError:
print("this is not a number, please try again")
Try using regex尝试使用正则表达式
import re
def checkInt(string):
ex = re.compile(r'[1-9][0-9]*')
return bool(ex.match(string))
You can use this function like this您可以像这样使用此功能
aaa = input("""Enter you're number accordinly to the list above:""")
if checkInt(aaa): aaa = int(aaa)
else:
print('Not a Integer')
exit()
# the code you posted on the question
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.