[英]How to input several float variables at once
例如:(我知道這是錯誤的,我只需要找出正確的方法即可。)
x, y, z = float(input('Enter what you would like x, y, and z to be.'))
因此,他們將鍵入1 2 3
並且將按相應順序分配每個變量。
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]
...此時您可以將結果分配給x
, y
和z
:
>>> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.