我是 Python 的新手,周末一直在做一些练习。我现在被困在一个特定的问题上,这需要我制作一个电影票预订程序。
我一直在研究如何为特定年龄段提供百分比值,我在我的代码中留下了一些评论,说明我需要包括哪些方法。
14.95的标准票价需要有10%的折扣和15%的折扣。
我需要使用一个名为“buyTicket()”的函数,我已将其包含在计算步骤百分比的参数中。
截至目前,该程序能够识别年龄,但我不确定如何将百分比添加到特定年龄,然后在选择每张票后将票价加起来。
下面是我当前的代码。非常感谢任何有关包含和使用内容的建议!
谢谢。
def cinema():
age = int(input("Please enter your age: "))
if age < 18:
print("Sorry. You are not over 18 years old. You cannot watch this movie.")
if age >= 18:
print("You are allowed to see the film. Standard ticket price is £14.95 ")
#twentydiscount = 10% (over 20)
#oapdiscount = 15% (over 65)
def buyTicket(percentageDiscount):
if age <= 20:
print("You are under 20 years old. You are eligible for a 10% discount. Your ticket price will be", percentageDiscount)
elif age >= 65:
print("You are 65 years or over. You are eligible for a 15% discount. Your ticket price will be", percentageDiscount)
else:
print("You are", age, "years old. Your ticket price will be £14.95")
# totalticketprice = (adding up prices of tickets after tickets have been selected each time)
while (True):
cinema()
anotherticket = input("Do you want to find out more information about another ticket? (Yes/No): ")
if anotherticket == 'No':
exit()
buyTicket(percentageDiscount)
请您参考如下方法:
尽量不要过多混淆逻辑和界面(为用户打印)。始终首先关注您的逻辑:
- 将原始价格存储并保存在变量中
- 根据买家的年龄将折扣存储在变量中
- 收集您需要的所有信息
- 最后计算
- 必要时通知用户
这是您的脚本示例(带有缩短的句子..):
#!/usr/bin/python3
def cinema():
age = int(input('Enter age: '))
if age < 18:
print(' Too young for this movie.')
return
discount = get_discount(age)
print_discount_message(discount)
price = 14.95
discd = calculate_discount_price(price, discount)
print(f' Your price: {discd} (original price: {price})')
def get_discount(age):
if age <= 20:
discount = 0.1
elif age >= 65:
discount = 0.15
else:
discount = 0.0
return discount
def print_discount_message(discount):
if discount == 0.0:
print(' Not qualified for discount.')
else:
print(' Qualified for discount: {}%'.format(int(discount * 100)))
def calculate_discount_price(original_price, discount):
return round(original_price - original_price * discount, 2)
if __name__ == '__main__':
while True:
cinema()
more = input('Buy more? (Yes/No): ')
if more != 'Yes':
break
示例输出:
$ python3 cinema.py
Enter age: 17
Too young for this movie.
Buy more? (Yes/No): Yes
Enter age: 19
Qualified for <= 20 discount (10%).
Your price: 13.45 (original price: 14.95)
Buy more? (Yes/No): Yes
Enter age: 21
No discount.
Your price: 14.95 (original price: 14.95)
Buy more? (Yes/No): Yes
Enter age: 66
Qualified for >= 65 discount (15%).
Your price: 12.71 (original price: 14.95)
Buy more? (Yes/No): Nah
