在下面的程序中,当我输入5作为字符串对象时输入
n=input("enter no of fibonnaci elements: ")
while not n:
n=input("enter no of fibonnac elements: ")
print(type(n))
if(n!=int()):
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
答案 0 :(得分:1)
您可以使用isinstance(n,int)
来检查它是否为整数。但是,如果您使用int(input("enter no of fibonnaci elements:"))
,则它将在其之前引发ValueError。
n=int(input("enter no of fibonnaci elements: ")) #convert to int here
while not n: #will not enter this loop - why is it even here?
n=input("enter no of fibonnac elements: ")
if(not isinstance(n,int)): #Note: won't Reach this line - Will throw an error before this
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
一种更好的方法
while True:
try:
n=int(input("enter no of fibonnaci elements: "))#convert to int here
break
except ValueError:
print("enter integer only")
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
输出
enter no of fibonnaci elements: str
enter integer only
enter no of fibonnaci elements: 6
series is: 0 1 1 2 3 5