【问题标题】:Movie ticket cost calculator [duplicate]电影票成本计算器[重复]
【发布时间】:2021-01-17 06:36:34
【问题描述】:

我正在尝试完成一项学校作业,我必须询问用户他们是否正在观看 3D 电影以及他们的年龄,并根据他们的回答计算门票价格。出于某种原因,无论他们为“类型”写了什么,结果好像他们说是的。我做错了什么?

# Base Price: 13, Child Discount: 50%, Senior Discount: 25%, 3D Surcharge: 35%

base_price = 13
child_discount = .5
senior_discount = .75
surcharge3d = 1.35
type = (input("Is the movie you are seeing in 3D?\n"))
age = eval(input("How old are you?\n"))

# Determine the price of the movie ticket

if type == 'No' or 'no':
    if age <= 12:
        total = base_price * child_discount
    elif 12 < age < 65:
        total = base_price
    else:
        total = base_price * senior_discount
elif type == 'Yes' or 'yes':
    if age <= 12:
        total = base_price * surcharge3d * child_discount
    elif 12 < age < 65:
        total = base_price * surcharge3d
    else:
        total = base_price * surcharge3d * senior_discount

# Display total cost

print("The total cost of your ticket is", round(total, 2), "dollars.")

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用if else语句时,应在or周围使用两个条件,例如:

if type == 'No' or type == 'no'

详细解释: 当您比较单个字符串(例如 if ('no'))时,这将始终为 true,因为它是一个有效值,如果存在“none”值,则为 false。基本上任何有效值都算作真实值,因此首先执行 if 语句,然后执行 elif,因此它最终存储 elif 的总数。

两个建议:

  1. type 是一个内置函数,不要使用它。不过,这不是问题。
  2. 您可以在字符串上使用.lower() 函数,避免使用两次“是”和“是”。

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多