簡體   English   中英

Python 2.7從用戶那里獲取兩個獨立變量的輸入

[英]Python 2.7 taking input from user for two separate variables

getMin, getMax = int(input("Enter a range (min,max): "));

以上是我試圖實現的代碼,但它給出了一個錯誤說...

int() argument must be a string or a number, not 'tuple'

基本上,我嘗試在輸入語句后輸入.split(,) ,但我得到了同樣的錯誤。 當用戶輸入1,10作為輸入時,我想要getMin = 1getMax = 10

因為你使用的是Python 2,所以你應該使用raw_input而不是input 嘗試這樣的事情:

from ast import literal_eval

prompt = "Enter a range (min,max): "
getMin = getMax = None

while {type(getMin), type(getMax)} != {int}:
    try:
        getMin, getMax = literal_eval(raw_input(prompt))
    except (ValueError, TypeError, SyntaxError):
        pass  # ask again...

恕我直言,更清潔的方法假設您希望輸入以逗號分隔

>>> prompt = "Enter a range (min,max): "
>>> while True:
...     try:
...             getMin, getMax = map(int, raw_input(prompt).split(','))
...             break
...     except (ValueError, TypeError):
...             pass
... 
Enter a range (min,max): skfj slfjd
Enter a range (min,max): 232,23123,213
Enter a range (min,max): 12, 432
>>> getMin
12
>>> getMax
432

input函數(請參閱此處的doc )將嘗試評估提供的輸入。 例如,如果您使用名稱AMcCauley13提供它,它將查找名為so的變量。 使用像1,10這樣的值來提供它將在元組(1,10)進行求值,這將破壞期望字符串的int()函數。

嘗試更簡單

getMin = int(raw_input("min range: "))
getMax = int(raw_input("max range: "))

或者將splitmap結合起來,就像巴爾基所建議的那樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM