我需要python来检查变量是否使用input()命令为整数



我需要python检查变量是否是整数,然后采取相应的行动。

下面是相关代码:

def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?nn"
"Please note: Only forklifts that have greater than 8,000 lbs. of lift capacity will qualify for this incentive.n"
"**Forklifts do  NOT need to be located at a port or airport to be eligible.**")
forklift_count = input("Enter in # of forklifts:")
if type(forklift_count) is int:
fl_count = forklift_count
else: 
print("Invalid number. Please try again.")    
data_grab()                       

目前,当用户实际输入一个整数时,它会自动跳转到ELSE,而不是执行IF下的代码。

任何想法吗?

尝试str.isdigit()方法:

forklift_count = input("Enter in # of forklifts:")
if forklift_count.isdigit():
# Use int(forklift_count) to convert type to integer as pointed out by @MattDMo
fl_count = forklift_count  
else: 
print("Invalid number. Please try again.")  

来自文档:

str.isdigit()

如果字符串中至少有一个字符且所有字符都是数字则返回True,否则返回False。

这里是一个初学者/可能不完整的答案,但是您可以用int()包装input()。

forklift_count = int(input("Enter in # of forklifts:"))

input()返回一个字符串,所以即使你输入一个int,它也会被视为字符串,除非你对它进行了转换。

相关内容

  • 没有找到相关文章

最新更新