电影票成本计算器

2024-09-30 16:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图完成一项学校作业,我必须询问用户是否正在观看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.")

Tags: thechildinputagebaseiftypediscount
1条回答
网友
1楼 · 发布于 2024-09-30 16:26:45

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

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

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

两项建议:

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

相关问题 更多 >