输入将整数作为字符串对象

时间:2018-12-29 09:45:38

标签: python python-3.x

我试图强行从用户那里获取输入并在Fibonacci元素程序中执行它,在输入附近出现问题时,我想确保当我将输入作为int(input( ))我的while循环不会执行,我希望它一直执行到用户提供输入为止。

在下面的程序中,当我输入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()

1 个答案:

答案 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