2014-03-02 36 views
-1

您好我正在學習python,我正在嘗試做一個小型程序,將錢轉換爲美元,歐元或英鎊。有人能幫助我,告訴我爲什麼不工作? 謝謝!Python程序不工作,輸入==字符串不工作

def calculate(): 
    currency_input = input("Insert value:") 
    dollar = 34 
    euro = 36 
    pound = 52 
    select_currency = input("Insert currency(dollar,euro or pound):") 
    if select_currency is "dollar": 
     currency_input * dollar 
    elif select_currency is "euro": 
     currency_input * euro 
    elif select_currency is "pound": 
     currency_input * pound 
    else: 
     print ("Please select a currency(dollar,euro,pound)!") 
    calculate() 
calculate() 

回答

0

你應該使用==而不是is,因爲is不會做你認爲它在這種情況下所做的。更多關於那here

使用.lower()允許用戶也輸入Dollars並仍然成功。

看來您希望能夠處理用戶輸入無效信息的時間。您應該使用tryexcept塊,以確保用戶爲currency_input

使用while True循環,以繼續要求正確輸入用戶只輸入數字。如果他們輸入正確的輸入,我們會停止詢問break聲明。

詞典可以很容易地存儲貨幣名稱及其關聯的值。

此外,數學對於所有貨幣都是相同的,唯一改變的是貨幣的價值(美元,歐元,...),所以我們可以查找用戶選擇的內容並且乘以那個時間currency_input

def calculate(): 
    # we only want the user to input numbers 
    while True: 
     try: 
      currency_input = float(input('Insert value: ')) # input always returns a str, we need to type cast 
      break # if input is valid we break out of the loop and move on 
     except TypeError: # handle the error when the input is not a number 
      print('Please enter a number.') 

    # use a dictionary because it is easier to read 
    currency_dict = { 
     'dollar': 34, 
     'euro': 36, 
     'pound': 52} 

    # get the type of currency and do the math 
    while True: 
     select_currency = input('Insert currency(dollar,euro or pound): ').lower() 
     if select_currency not in currency_dict: # if the users enter something that is not in the dict 
      print('Invalid currency') # oops, try again 
     else: 
      money = currency_input * currency_dict[select_currency] # we do the math 
      return money # return allows us to further manipulate that variable if we so desire 

print(calculate()) 

感謝Martijn Pieters指出了兩項改進。

0

您正在測試身份而不是平等。使用==代替:

if select_currency == "dollar": 

is測試如果名稱select_currency是指同一對象;兩個對象可以是不同的,但仍然具有相同的值,您可以使用==進行測試。

你需要修復您的所有字符串測試,還實際存儲你的計算結果:

if select_currency == "dollar": 
    result = currency_input * dollar 
elif select_currency == "euro": 
    result = currency_input * euro 
elif select_currency == "pound": 
    result = currency_input * pound 

更易仍然是使用這裏的字典:

currencies = { 
    'dollar': 34, 
    'euro': 36, 
    'pound': 52, 
} 
if select_currency in currencies: 
    result = currency_input * currencies[select_currency] 
else: 
    print ("Please select a currency(dollar,euro,pound)!") 
+0

這是行得通的,但如果我輸入歐元或美元或英鎊,它會直接轉到別的地方...爲什麼?我用小寫的「美元」......或歐元或任何選擇......完全打字......? – Victor

+0

'print(repr(select_currency))'輸出是什麼? –