有没有办法使用函数和循环来简化这里的代码? 我想简化它,但不知道如何简化
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))
我会这么做
我建议创建一个函数,根据年龄和返回价格。您还可以创建一个函数来获取年龄。然后,它将很容易在循环或理解中使用,以计算价格:
这将把计算与用户交互分开,并且很容易向输入添加验证(例如允许的年龄范围或检查值是否为数字)
在这个上下文中,尝试使用
while
语句while true:
意味着当程序运行时,重复执行此代码直到停止相关问题 更多 >
编程相关推荐