[英]Testing if user input is an int or a str, then failing if input is a str. I keep getting strs I enter as undefined
我正在尝试测试我的用户输入是字符串还是整数。
feet = input ("Enter your feet.")
inches = input ("Enter your inches.")
if type(eval(feet)) and type(eval(inches)) == int:
print ("both are numbers!")
else:
print ("That's not a Number!")
这是我的代码,如果我输入数字作为英尺和英寸的值,它将起作用。 但是,如果foot = a,则会收到错误消息,指出a未定义。
我究竟做错了什么?
您做错的是使用eval
。 那绝不是做任何事情的好方法。
相反,尝试转换为int并捕获异常:
try:
feet = int(feet)
inches = int(inches)
except ValueError:
print("not numbers!")
else:
print("numbers!")
不要使用eval
来测试用户输入是否为整数。 因为解释器试图找到一个叫做a
的变量,但没有定义一个变量,所以会出现错误。 相反,您可以检查字符串是否仅包含数字。
def is_integer(s):
for c in s:
if not c.isdigit():
return False
return True
feet = input ("Enter your feet.")
inches = input ("Enter your inches.")
if is_integer(feet) and is_integer(inches):
print ("both are numbers!")
else:
print ("That's not a Number!")
假设负数无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.