如何在Python中排除特定类型的输入变量?

如何在Python中排除特定类型的输入变量?,python,string,fibonacci,valueerror,Python,String,Fibonacci,Valueerror,我创建了一行斐波那契数。在开始时,需要输入数字来指定斐波那契数列的大小,实际上是行的大小。该数字必须是大于等于2的整数 结果是打印出所有斐波那契数,直到行的最后一个数,其各自的索引在行内!之后,需要从行中取出一个切片,结果是打印出切片中的所有数字及其各自的索引 我成功地掌握了排除所有不在指定范围内的值的方法,但我没有成功排除数字和其他不需要的类型的输入,示例希望排除输入变量的浮点类型和输入变量的字符串类型 我指定不需要的输入变量类型是float和string!然而,它报告我一个错误!如何克服这个

我创建了一行斐波那契数。在开始时,需要输入数字来指定斐波那契数列的大小,实际上是行的大小。该数字必须是大于等于2的整数

结果是打印出所有斐波那契数,直到行的最后一个数,其各自的索引在行内!之后,需要从行中取出一个切片,结果是打印出切片中的所有数字及其各自的索引

我成功地掌握了排除所有不在指定范围内的值的方法,但我没有成功排除数字和其他不需要的类型的输入,示例希望排除输入变量的浮点类型和输入变量的字符串类型

我指定不需要的输入变量类型是float和string!然而,它报告我一个错误!如何克服这个问题,或者换言之,如何指定排除浮动变量和字符串变量的要求,以不向我报告错误

守则:

while True:
    n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))

    if n < 2:
        print('This is not valid number! Please enter valid number as specified above!')
        continue
    elif type(n)==float: # this line is not working!
        print('The number has to be an integer type, not float!')
        continue
    elif type(n)==str: # this line is not working!
        print(  'The number has to be an integer type, not string!')
        continue
    else:
        break

def __init__(self, first, last):
    self.first = first
    self.last = last

def __iter__(self):
    return self

def fibonacci_numbers(n):
    fibonacci_series =  [0,1]
    for i in range(2,n):
        next_element = fibonacci_series[i-1] + fibonacci_series[i-2]
        fibonacci_series.append(next_element)
    return fibonacci_series

while True:
    S = int(input('Enter starting number of your slice within Fibonacci row (N>=2):'))

    if S>n:
        print(f'Starting number can not be greater than {n}!')
        continue
    elif S<2:
        print('Starting number can not be less than 2!')
        continue
    elif type(S)==float: # this line is not working!
        print('The number can not be float type! It has to be an integer!')
        continue
    elif type(S)==str: # this line is not working!
        print('Starting number can not be string! It has to be positive integer number greater than or equal to 2!')
        continue
    else:
        break

while True:
    E = int(input(f'Enter ending number of your slice within Fibonacci row(E>=2) and (E>={S}):'))

    if E<S:
        print('Ending number can not be less than starting number!')
        continue
    elif E>n:
        print(f'Ending number can not be greater than {n}')
        continue
    elif E<2:
        print('Ending number can not be greater than 2!')
        continue
    elif type(E)==float: # this line is not working!
        print('Ending number can not be float type! It has to be an integer type!')
        continue
    elif type(E) ==str: # this line is not working!
        print(f'Ending number can not be string! It has to be positive integer number greater than or equal to {S}')
        continue
    else:
        break

print('Fibonacci numbers by index are following:')
for i, item in enumerate(fibonacci_numbers(n),start = 0):
    print(i, item)

fibonacci_numbers1 = list(fibonacci_numbers(n))
print('Fibonacci numbers that are within your slice with their respective indices are following:')
for i, item in enumerate(fibonacci_numbers1[S:E], start = S):
    print(i, item)
为True时:
n=int(输入('请输入斐波那契行的大小-正整数(n>=2)!'))
如果n<2:
print('这不是有效的数字!请输入上面指定的有效数字!')
持续
elif type(n)=float:#此行不工作!
print('数字必须是整数类型,而不是float!')
持续
elif type(n)=str:#此行不工作!
打印('数字必须是整数类型,而不是字符串!')
持续
其他:
打破
定义初始(自我、第一、最后):
self.first=第一
self.last=last
定义(自我):
回归自我
def斐波那契数(n):
斐波那契级数=[0,1]
对于范围(2,n)内的i:
下一个元素=斐波那契数列[i-1]+斐波那契数列[i-2]
fibonacci_级数。追加(下一个_元素)
返回斐波那契级数
尽管如此:
S=int(输入('输入斐波那契行(N>=2)中的切片起始编号):'))
如果S>n:
打印(f'起始编号不能大于{n}!')
持续
elif S在第一行

    n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))

您正在将输入转换为int,因此无论用户提供什么,它都将转换为int

如果希望代码正常工作,请将其替换为

n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')
在第一行

    n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))

您正在将输入转换为int,因此无论用户提供什么,它都将转换为int

如果希望代码正常工作,请将其替换为

n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')

使用
try/except/else
测试输入<如果字符串值不是严格意义上的整数,则code>int()
将引发
ValueError

>>> while True:
...   s = input('Enter an integer: ')
...   try:
...     n = int(s)
...   except ValueError:
...     print('invalid')
...   else:
...     break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>

使用
try/except/else
测试输入<如果字符串值不是严格意义上的整数,则code>int()将引发
ValueError

>>> while True:
...   s = input('Enter an integer: ')
...   try:
...     n = int(s)
...   except ValueError:
...     print('invalid')
...   else:
...     break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>

如果需要检查类型,
isinstance
通常更好,例如。g、 :

if isinstance(var, int) or isinstance(var, str):
    pass  # do something here

如果需要检查类型,
isinstance
通常更好,例如。g、 :

if isinstance(var, int) or isinstance(var, str):
    pass  # do something here
已解决:-)只需在ur代码中添加try except块,如下所示:

while True:
  try:
    num = int(input("Enter an integer number: "))
    break
  except ValueError:
      print("Invalid input. Please input integer only")  
      continue

print("num:", num)
upvote&check:-)

已解决:-)只需在ur代码中添加尝试除块,如下所示:

while True:
  try:
    num = int(input("Enter an integer number: "))
    break
  except ValueError:
      print("Invalid input. Please input integer only")  
      continue

print("num:", num)

upvote&check:-)

我不确定这是否足够,因为
n
将始终返回一个字符串。这里正确的做法是使用回退策略,例如,始终首先尝试强制转换为浮点-如果没有错误,则尝试转换为int。然后,如果强制转换的浮点和强制转换的int不相等,则可能会引发错误,或者可能会或显示有关强制转换为浮点的消息。如果强制int和强制float相等,那么输入的值实际上可能是一个整数,执行工作与预期一样。注意,比较的顺序也需要改变。我解决的问题的一部分是排除浮点型数据!然而,如何排除字符串类型的数据仍然很困难!我不确定这是否足够,因为
n
将始终返回字符串。这里正确的做法是使用回退策略,例如,始终首先尝试强制转换为浮点-如果没有错误,则尝试转换为int。然后,如果强制转换的浮点和强制转换的int不相等,则可能会引发错误,或者可能会或显示有关强制转换为浮点的消息。如果强制int和强制float相等,那么输入的值实际上可能是一个整数,执行工作与预期一样。注意,比较的顺序也需要改变。我解决的问题的一部分是排除浮点型数据!然而,如何排除字符串类型的数据仍然很困难!非常有用!谢谢非常有用!谢谢