我不确定如何使用isinstance
,但这是我尝试的内容:
age = int(input("Enter your Age: "))
if isinstance(age,int):
continue
else:
print ("Not an integer")
我在这里做错了什么?这也会使我的程序终止吗?或者让我重新进入我的年龄?
如果输入不是整数,我希望它继续让我重新输入。
答案 0 :(得分:4)
如果用户输入的不是整数,那么这不会起作用,因为对int()
的调用会触发ValueError
。如果int()
成功,则无需再查看isinstance()
。此外,continue
仅在for
或while
循环中有意义。相反,这样做:
while True: # keep looping until we break out of the loop
try:
age = int(input("Enter your age: "))
break # exit the loop if the previous line succeeded
except ValueError:
print("Please enter an integer!")
# If program execution makes it here, we know that "age" contains an integer
答案 1 :(得分:0)
isinstance(object, class-or-type-or-tuple) -> bool
age = int(input("Enter your Age: "))
In [6]: isinstance(age, int)
Out[6]: True
尝试递归功能。与try except
def solve():
try:
age = int(input('enter age: '))
solve()
except ValueError:
print('invalid value')
solve()
答案 2 :(得分:0)
只是为了好玩:)另一个可能的答案,没有处理异常(可能效率低下):
age=raw_input('Enter your age: ')
while len ([ii for ii in age if not ii in [str(jj) for jj in range(9)]]) > 0:
print 'It\'s not an integer\n'
age=raw_input('Enter your age: ')
age=int(age)
答案 3 :(得分:-2)
while True:
try:
age = int(input("Enter your Age: "))
print (("Your age is: "),age)
break
except ValueError:
print ("It's not an integer.")
continue
这是您的解决方案