如何一次输入几个浮点变量

时间:2017-02-26 21:41:53

标签: python python-3.x variables input

例如:(我知道这是错的,我只需要找出正确的方法。)

x, y, z = float(input('Enter what you would like x, y, and z to be.'))

因此他们会输入1 2 3,并且每个变量都会按相应的顺序分配。

1 个答案:

答案 0 :(得分:0)

input()返回单个字符串,因此您需要将其拆分:

>>> input('Enter what you would like x, y, and z to be: ').split()
Enter what you would like x, y, and z to be: 1.23 4.56 7.89
['1.23', '4.56', '7.89']

...然后将每个结果字符串转换为float

>>> [float(s) for s in input('Enter what you would like x, y, and z to be: ').split()]
Enter what you would like x, y, and z to be: 9.87 6.54 3.21
[9.87, 6.54, 3.21]

...此时您可以将结果分配给xyz

>>> x, y, z = [float(s) for s in input('Enter what you would like x, y, and z to be: ').split()]
Enter what you would like x, y, and z to be: 1.47 2.58 3.69
>>> x
1.47
>>> y
2.58
>>> z
3.69

当然,如果用户输入错误数量的花车,您就会遇到问题:

>>> x, y, z = [float(s) for s in input('Enter what you would like x, y, and z to be: ').split()]
Enter what you would like x, y, and z to be: 12.34 56.78
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)

......所以处理它可能是一个好主意:

>>> while True:
...     try:
...         x, y, z = [float(s) for s in input('Enter what you would like x, y, and z to be: ').split()]
...     except ValueError:
...         print('Please enter THREE values!')
...     else:
...         break
... 
Enter what you would like x, y, and z to be: 1 2 3 4 5
Please enter THREE values!
Enter what you would like x, y, and z to be: 6 7
Please enter THREE values!
Enter what you would like x, y, and z to be: 8 9 0
>>> x
8.0
>>> y
9.0
>>> z
0.0