如何在 Python 中排除特定类型的输入变量?
Posted
技术标签:
【中文标题】如何在 Python 中排除特定类型的输入变量?【英文标题】:How to exclude specific type of an input variable in Python? 【发布时间】:2020-12-18 04:10:38 【问题描述】:我创建了一行斐波那契数列。在开始时需要输入数字来指定斐波那契数列的大小,实际上是行的大小。数字必须是>=2的整数。
结果是打印出所有斐波那契数,直到行的最后一个数,以及它们各自的索引!之后需要取出一行的切片,结果是打印出切片内的所有数字及其各自的索引。
我成功地排除了所有不在指定范围内的值,但是我没有成功排除数字和其他不需要的类型的输入,例如想排除输入变量的浮点类型和字符串类型一个输入变量。
我指定不希望的输入变量类型是浮点数和字符串!但是它报告我一个错误!如何克服这个问题,或者换句话说,如何指定排除浮动变量和字符串变量的要求以不向我报告错误?
代码:
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)
【问题讨论】:
【参考方案1】:已解决 :-) 只需在您的代码中添加 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)
投票和检查:-)
【讨论】:
非常有用!谢谢!【参考方案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)!')
【讨论】:
我不确定这是否足够,因为n
将始终返回一个字符串。正确的做法是有后备,例如总是首先尝试强制转换为浮点数 - 如果没有错误,然后尝试转换为 int。然后,如果强制浮点数和强制 int 不相等,则会引发错误,或者会显示一条关于浮点到 int 强制的消息。如果强制 int 和强制 float 相等,则输入的值可能实际上是一个整数,并且执行按预期工作。请注意,比较的顺序也需要机会。
我解决的部分问题是排除浮点类型的数据!然而仍在苦苦挣扎如何排除字符串类型的数据!【参考方案3】:
使用try/except/else
测试输入。如果字符串值不是严格的整数,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
>>>
【讨论】:
【参考方案4】:如果您需要检查类型,isinstance
通常更好,例如。 g.:
if isinstance(var, int) or isinstance(var, str):
pass # do something here
【讨论】:
以上是关于如何在 Python 中排除特定类型的输入变量?的主要内容,如果未能解决你的问题,请参考以下文章