簡體   English   中英

Python:為什么我得到ValueError:解壓縮的值太多了

[英]Python: Why am I getting ValueError: too many values to unpack

我不知道為什么我會收到這個錯誤。 我已經閱讀並嘗試了不同的東西,但它無法正常工作。

def product():

    y, x= raw_input('Please enter two numbers: ')
    times = float(x) * int(y)
    print 'product is', times
product()

我究竟做錯了什么? 非常感謝

raw_input返回單個字符串。 要在你正在做的時解壓參數,它需要返回2個東西。

你可以這樣做:

y, x = raw_input('Please enter two numbers (separated by whitespace): ').split(None,1)

請注意,這仍然有點脆弱,因為用戶可以輸入類似“2 1 3”的字符串。 解壓縮工作沒有異常,但在嘗試將“1 3”轉換為整數時會出現阻塞。 執行這些操作最強大的方法是通過try/except塊。 這是我將如何做到這一點。

while True: #try to get 2 numbers forever.
   try:
      y, x = raw_input("2 numbers please (integer, float): ").split()
      y = int(y)
      x = float(x)
      break  #got 2 numbers, we can stop trying and do something useful with them.
   except ValueError:
      print "Oops, that wasn't an integer followed by a float.  Try again"

@ mgilson的回答是正確的; 除非有人輸入三個數字,否則你會得到相同的ValueError異常。

所以,這個替代版本捕獲了:

numbers = raw_input('Please enter only two numbers separated by a space: ').split()
if len(numbers) > 2:
   print 'Sorry, you must enter only two numbers!'
else:
   x,y = numbers

暫無
暫無

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

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