我是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)
答案 0 :(得分:1)
尽量不要将逻辑和界面(用户的打印件)混淆得太多。始终先关注您的逻辑:
这是您的脚本示例(带有简短的句子..):
#!/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
答案 1 :(得分:0)
首先定义一个函数来计算数字的百分比。您可以内联地执行此操作,但是您将需要多次,因此为此使用函数会更好地进行编码:
def percentage(price, pct):
return (pct * price) /100
然后可以在需要的地方调用此函数,如下所示:
print("You are 65 years or over. You are eligible for a 15% discount. Your ticket price will be", percentage(price, percentageDiscount))
您还必须创建价格变量。
P.S .:您的问题闻起来像作业;)
答案 2 :(得分:0)
如果我没看错,我想这就是你想要的:
n = £14.95
x = n / 100
percent = n * x - 100
price = abs(age * percent / 100)
我认为这是正确的,因为您尝试执行的前三行是从数字中获取百分比的计算。