2017-03-13 58 views
-1

我是Python的新手,我正在編寫一個程序,它涉及定義我自己的函數,以確定客戶是否在其票證上獲得折扣。首先,我問他們是否預註冊,然後打電話給我有一個if-then-else決策聲明的函數,它可以應用10%的折扣或不適用。我不確定我在做什麼我的程序有問題,有什麼建議嗎? 編輯:我的輸出現在返回0 $,我希望如果沒有預先註冊,它可以輸出20美元,或者如果預先註冊,則計算20美元的10%。Python - 使用決策語句和返回變量定義函數

def determineDiscount(register, cost): 
#Test if the user gets a discount here. Display a message to the screen either way. 
    if register == "YES": 
     cost = cost * 0.9 
     print("You are preregistered and qualify for a 10% discount.") 
    else: 
     print("Sorry, you did not preregister and do not qualify for a 10% discount.") 
    return cost 

#Declarations 
registered = '' 
cost = 0 
ticketCost = 20 

registered = input("Have you preregistered for the art show?") 
determineDiscount(registered, ticketCost) 

print("Your final ticket price is", cost, "$") 
+1

你的問題是?您的縮進已關閉,因此請修復它以反映您實際運行的代碼。你需要闡明一個問題陳述,比如「當我運行這樣那樣的事情時,我得到這樣那樣的錯誤,這裏是完整的追溯......」假設你的縮進是正確的,我馬上注意到你不是捕獲你的函數返回的值。所以'成本'將始終爲'0' –

+0

請指定您的問題。如果它沒有運行,請提供錯誤堆棧。 – Musen

+0

還有一件事,你使用了哪種python。在2.7中沒有輸入(),它在python3中。 最終將所有輸入轉換爲大寫。現在,如果你輸入「是」,那麼你有折扣,如​​果你輸入「是」,那麼你沒有它。 – darvark

回答

0

代碼應在PY3使用PY2 raw_inputinput。 此函數返回的成本必須以成本存儲,否則將保持不變。功能外的成本與功能內的成本不一樣。

def determineDiscount(register, cost): 
    if register.lower() == "yes": 
     cost *= 0.9 
     print("You are preregistered and qualify for a 10% discount.") 
    else: 
     print("Sorry, you did not preregister and do not qualify for a 10% discount.") 
    return cost 


ticketCost = 20 
registered = raw_input("Have you preregistered for the art show?") 
cost = determineDiscount(registered, ticketCost) 

print("Your final ticket price is", cost, "$") 
0
def determineDiscount(register, cost): 
#Test if the user gets a discount here. Display a message to the screen either way. 
    if register.lower() == "yes": #make user's input lower to avoid problems 
     cost -= cost * 0.10 #formula for the discount 
     print("You are preregistered and qualify for a 10% discount.") 
    else: 
     print("Sorry, you did not preregister and do not qualify for a 10% discount.") 
    return cost 
#Declarations 
ticketCost = 20 
#get user input 
registered = input("Have you preregistered for the art show?") 
#call function in your print() 
print("Your final ticket price is $", determineDiscount(registered, ticketCost)) 

輸出:

Have you preregistered for the art show?yes 
You are preregistered and qualify for a 10% discount. 
Your final ticket price is $18