函数与循环Python

2024-09-28 17:22:35 发布

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

有没有办法使用函数和循环来简化这里的代码? 我想简化它,但不知道如何简化

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))

Tags: 函数inputageifelseinttotalenter
3条回答

我会这么做

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:意味着当程序运行时,重复执行此代码直到停止

相关问题 更多 >