[英]How can I have an int variable with 0 as the first number in Python?
[英]How can I verify that a variable is a number in Python?
我正在编写有关工程主题的代码,该代码要求用户输入几个值,程序随后将使用这些值。
目前,我有以下代码:
while True:
strainx =input("Please enter a value for strain in the x-direction: ")
num_format = re.compile("^[1-9][0-9]*\.?[0-9]*")
isnumber = re.match(num_format,strainx)
if isnumber:
break
简而言之,我试图要求用户输入应变数字的值。 如果用户输入的不是数字,则该问题将重复出现,直到他们输入数字为止。 但是,通过使用这种方法,代码不接受小数,并且在某些情况下,用户必须输入小数。 有没有办法解决?
如果用户输入了无法转换的内容,请尝试将其转换为浮点数并捕获ValueError:
while True:
strainx = input("Please enter a value for strain in the x-direction: ")
try:
number = float(strainx)
break # if valid entry we break the loop
except ValueError:
# or else we get here, print message and ask again
print("Invalid entry")
print(number)
转换为浮点覆盖"1"
和"1.123"
等。
如果您不希望接受零,则可以在强制转换后检查数字是否为零,我认为负数也无效,因此我们可以检查数字是否不等于0。
while True:
strainx = input("Please enter a value for strain in the x-direction: ")
try:
number = float(strainx)
if number <= 0:
print("Number must be greater than zero")
continue # input was either negative or 0
break # if valid entry we break the loop
except ValueError:
# or else we get here, print message and ask again
print("Invalid entry")
print(number)
如果您使用的是Python 2,而不是使用正则表达式,则可以使用Python的内置类型检查机制。
让我们在trainx不是数字时循环,然后检查最新输入是否是数字。
is_number = False
while not is_number:
strainx =input("Please enter a value for strain in the x-direction: ")
is_number = isinstance(strainx, float) or isinstance(strainx, int)
如果您坚持使用正则表达式,则此模式似乎有效:
"^(\-)?[\d]*(\.[\d]*)?$"
匹配可选的负号,匹配任意数量的数字,可选的十进制与任意数量的数字。
提示:您可以将isnumber = bool(re.match(num_format,strainx)
或后一部分直接用于if语句中。
如果您要查找整数检查,请尝试以下操作-
isinstance( variable_name, int )
如果返回True,则该变量为数字,否则为其他变量。
但是,如果要检查字符值是否为数字。 例如-上面的脚本中的a =“ 2”将返回False。 所以试试这个-
try:
number = float(variable_name)
print "variable is number"
except ValueError:
print "Not a number"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.