函数和循环蟒蛇



有没有一种方法可以使用函数和循环来简化这里的代码?我想简化它,但不确定如何简化。

age1 = int(input("Enter age:"))
if age1 < 12:
price1 = 10
else:
if age1 < 59:
price1 = 20
else:
price1 = 15

age2 = int(input("Enter age:"))
if age2 < 12:
price2 = 10
else:
if age2 < 59:
price2 = 20
else:
price2 = 15

age3 = int(input("Enter age:"))
if age3 < 12:
price3 = 10
else:
if age3 < 59:
price3 = 20
else:
price3 = 15
total = price1 + price2 + price3
print("The total price for the tickets is $" + str(total))

我会做这个

people = int(input('Enter number of people: '))
min_age=12
max_age=59
def price(min_age, max_age):
age = int(input("Enter age:"))

if age < min_age:
price = 10
else:
if age < max_age:
price = 20
else:
price = 15
return price
prices = []
for j in range(people):
prices.append(price(min_age, max_age))
total_price = sum(prices)
print("The total price for the tickets is $" + str(total_price))

我建议创建一个函数,给定年龄并返回价格。您也可以创建一个函数来获取年龄。然后,它将很容易在循环或理解中使用,以将价格相加:

def getAge():      return int(input("Enter age:"))
def getPrice(age): return 10 if age <12 else 20 if age < 59 else 15
total = sum(getPrice(getAge()) for _ in range(3))
print(f"The total price for the tickets is ${total}")

Enter age:65
Enter age:25
Enter age:9
The total price for the tickets is $45

这将把计算与用户交互分开,并且很容易在输入中添加验证(例如允许的年龄范围或检查值是否为数字(

在此上下文中尝试使用while语句;

while true:
# Code goes here

while true:意味着当程序运行时,重复执行此代码,直到它停止。

最新更新