While循环在Python中标识整数
我正试图编写一个程序来计算密度,并试图创建一个while循环,防止用户为体积输入任何内容或非数字 但当我运行程序时,它总是循环“你必须输入一个值”。我在for循环中尝试了相同的代码,输入2个数字后,它确实可以工作While循环在Python中标识整数,python,for-loop,while-loop,numbers,Python,For Loop,While Loop,Numbers,我正试图编写一个程序来计算密度,并试图创建一个while循环,防止用户为体积输入任何内容或非数字 但当我运行程序时,它总是循环“你必须输入一个值”。我在for循环中尝试了相同的代码,输入2个数字后,它确实可以工作 def GetVolume(): print("How many cublic cm of water does the item displace") Volume = input() while Volume == ("") or type(Volume)
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while Volume == ("") or type(Volume) != int:
print("You have to type a value")
Volume = input()
return float(Volume)
您必须修改while,因为正在验证的是str或与int不同。默认情况下,输入将始终是str,除非您在案例中使用int()或float()修改类型 您可以使用“try”来检查以下内容:
while True:
x = input("How many cubic cm of water does the item displace")
try:
x = float(x)
break
except ValueError:
pass
print('out of loop')
此解决方案是在假设您使用的是
python3
的情况下编写的。代码中的问题是,您假设如果键入一个数字,input
方法将返回一个type int
。这是不正确的。您将始终从输入中获得一个字符串
此外,如果您尝试在输入周围强制转换int
,以强制输入int,则如果您输入字符串,代码将升高,其中包括:
ValueError: invalid literal for int() with base 10:
因此,我建议您如何使实现更容易,使用try/except
,而不是尝试将值转换为浮点值。如果不起作用,则提示用户继续输入值,直到用户输入为止。然后,您只需断开循环并返回您的数字,并将其类型转换为浮点数
此外,由于使用了try/except,您不再需要在while循环中放入条件检查。您只需将循环设置为,而设置为True
,然后在满足代码中的条件后中断循环
遵守以下代码,并使用我上面提到的代码重新编写:
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume
input
返回一个字符串。您必须将其转换为int
,正如@saulspatz所建议的,在中使用int(Volume)
或float(Volume)
,尝试/除此之外,如果输入数据是float,您的代码将永远不会返回某些内容。类似于'4.5'.isdigit()==False
。您可以尝试Volume.replace('.','').replace('.','').isdigit()
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume