查看输入是否是已定义函数中的整数



所以我用Python制作这个配方转换器程序,它可以将你的配方乘以或除以某个数字。我现在做了这几行代码,检查一种成分所需的量是否是整数:

while True:
try:
amount = int(input(f"Enter in the amount for {ingredient}: "))
except ValueError:
print("This is not a number")
continue
else:
break

虽然这确实可以检查它是否是数字,但我在整个程序中重复这部分代码几次,以检查特定输入是否是数字。有没有办法制作一个定义的函数来检查它是否是整数?例如(如果可能是这样(:

amount = int(input(f"Enter in the amount for {ingredient}: "))
check_int(amount)

单独分解检查不会有多大好处(因为您想再次提示,直到他们提供有效的int(,所以将检查和循环分解为一个函数:

def prompt_for_int(prompt_str=None, error_str='This is not an integer'):
while True:
try:
return int(input(prompt_str))
except ValueError:
print(error_str, flush=True)

然后在使用点,你只会看到:

amount = prompt_for_int(f"Enter in the amount for {ingredient}: ")
def check_int(value):
try:
int(value)
return True
except ValueError:
return False

print(check_int(2))
print(check_int("2"))

试图将输入值强制转换为整数的函数。如果它可以强制转换,则表示它是一个整数,否则它就不是整数。如果您也想处理浮动,则需要对此进行更多更改。

最新更新