Python - 使用决策语句和返回变量定义函数

时间:2017-03-13 06:05:05

标签: python function if-statement methods user-defined-functions

我是Python的新手,我正在编写一个程序,该程序涉及定义我自己的函数,该函数确定客户是否在其票证上获得折扣。首先我问他们是否预先注册,然后调用我的函数,该函数具有if-then-else决策声明,它要么应用10%的折扣,要么不应用。我不确定我的计划有什么问题,有什么建议吗? 编辑:我的输出现在返回0 $,我希望如果没有预先登记就输出20美元,或者如果预先登记则计算20美元10%的折扣。

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, "$")

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

代码应使用PY2中的raw_input和PY3中的input。 此外,函数返回的成本必须以成本存储,否则它将保持不变。功能之外的成本与功能内部的成本不同。

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, "$")