我需要 python 来使用 input() 命令检查变量是否为整数
I need python to to check if variable is an integer using the input() command
我需要 python 检查变量是否为整数,然后采取相应行动。
这里是相关代码:
def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?\n\n"
"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下的代码。
有什么想法吗?
这里有一个 beginner/possibly 不完整的答案,但是你可以用 int() 包装 input()。
forklift_count = int(input("Enter in # of forklifts:"))
input() returns 一个字符串,所以即使你输入一个 int 除非你转换它,它也会被视为字符串。
这是因为无论输入什么,输入的都是returns字符串。如果您输入数字,它 returns “123” 作为字符串而不是 123 作为 int。你可以试一试,除非你尝试将字符串转换为 int 以查看它是否是 int,或者你可以使用 if-else 并检查字符串中是否有任何非数字字符。
这是一个 try/except 示例:
in = input("Enter a number :")
try:
in = int(in) #cast string to int
print("Yay it is an int")
except ValueError:
#not a number logic here
print("that is not an int")
试试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()
Return True if all characters in the string are digits and there is at least one character, False otherwise.
我需要 python 检查变量是否为整数,然后采取相应行动。
这里是相关代码:
def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?\n\n"
"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下的代码。
有什么想法吗?
这里有一个 beginner/possibly 不完整的答案,但是你可以用 int() 包装 input()。
forklift_count = int(input("Enter in # of forklifts:"))
input() returns 一个字符串,所以即使你输入一个 int 除非你转换它,它也会被视为字符串。
这是因为无论输入什么,输入的都是returns字符串。如果您输入数字,它 returns “123” 作为字符串而不是 123 作为 int。你可以试一试,除非你尝试将字符串转换为 int 以查看它是否是 int,或者你可以使用 if-else 并检查字符串中是否有任何非数字字符。
这是一个 try/except 示例:
in = input("Enter a number :")
try:
in = int(in) #cast string to int
print("Yay it is an int")
except ValueError:
#not a number logic here
print("that is not an int")
试试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()
Return True if all characters in the string are digits and there is at least one character, False otherwise.