你應該使用==
而不是is
,因爲is
不會做你認爲它在這種情況下所做的。更多關於那here。
使用.lower()
允許用戶也輸入Dollars
並仍然成功。
看來您希望能夠處理用戶輸入無效信息的時間。您應該使用try
except
塊,以確保用戶爲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指出了兩項改進。
這是行得通的,但如果我輸入歐元或美元或英鎊,它會直接轉到別的地方...爲什麼?我用小寫的「美元」......或歐元或任何選擇......完全打字......? – Victor
'print(repr(select_currency))'輸出是什麼? –