【发布时间】:2015-05-05 16:55:32
【问题描述】:
我最初是这样写的:
n = input('How many players? ')
while type(n) != int or n <= 2:
n = input('ERROR! The number of players must be an integer bigger than 2! How many players? ')
然后,几行之后,这是:
V = input("What's the value? ")
while type(V) != int and type(V) != float:
V = input("ERROR! The value must be expressed in numbers!"+"\n"+"What's the value? ")
在第一次测试之后,我意识到我需要使用 raw_input 而不是 input。 但是我需要重写while循环。我不希望程序中断;我想检查输入并发送消息错误以防类型不是所要求的。
如果我使用 raw_input,我如何检查输入是整数还是浮点数,因为 type(n) 和 type(V) 都是字符串(使用 raw_input)?
附:对于 V,如果它是整数,我想将值存储为整数,如果它是浮点数,我想将值存储为浮点数
更新: 我已经解决了第一段代码的问题,如下所示:
n = None
while n <= 2 :
try:
n = int(raw_input('How many players? '))
except ValueError:
print 'ERROR! The number of players must be expressed by an integer!'
但是我仍然不知道如何解决第二段代码的问题。除非我信任用户,否则我不知道如何存储 V 的值,这样如果它是一个浮点数,它就是一个浮点数,如果它是一个整数,它就是一个整数。
更新 #2 - 问题已解决: 对于第二个部分,我想出了这些:
while *condition in my program*:
try:
V = float(raw_input("what's the value? "))
except ValueError:
print "ERROR! The value of the coalition must be expressed in numbers!"
if V - int(V) == 0:
V = int(V)
我对结果并不满意,但至少它有效。有cmets吗?有什么建议吗?
【问题讨论】:
-
您从
raw_input获得str。然后你需要把它转换成你需要的任何类型,python 不会自己做。 -
@Paco:这并不完全准确。你是对的,如果你使用python3。但是,OP 使用的是 python2.7,其中
input在存储到变量之前评估用户的输入。 Python2.7 有raw_input相当于python3 的input -
不完全是重复的,因为他的实际测试有话要说。通常你会在 python 中进行转换并使用 try/except 构造来查看它是否成功。
-
@inspectorG4dget 后来我意识到这是一个
python-2.7的问题,我的错。
标签: python python-2.7 input