【问题标题】:Python - define function using decision statement and return variablePython - 使用决策语句定义函数并返回变量
【发布时间】:2017-03-13 06:05:05
【问题描述】:

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

【问题讨论】:

  • 您的问题是什么?您的缩进已关闭,因此请修复它以反映您实际运行的代码。您需要阐明问题陈述,例如“当我运行某某时,我得到某某错误,这是完整的回溯……”假设您的缩进是正确的,我会立即注意到您不是捕获函数返回的值。所以cost 永远是0
  • 还有一点,你用的是哪个python。在 2.7 中没有 input(),在 python3 中是。最终将所有输入转换为大写。现在,如果您输入“YES”,那么您就有折扣,如​​果您输入“yes”,那么您就没有折扣。
  • 请说明您的问题。如果没有运行,请提供错误堆栈。

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


【解决方案1】:

代码应在 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, "$")

【讨论】:

    【解决方案2】:
    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 2017-09-23
      • 2018-03-19
      相关资源
      最近更新 更多