-3

Is there a way to simplify the code here using function and loops? I would like to simplify it but not sure how to.

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))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
SortSort
  • 25
  • 6
  • 1
    Yes, there is. What did you find when you searched around for loops and functions? – quamrana Dec 14 '20 at 15:42
  • This shouldn't be closed. OP has some difficulty to create a function for all this stuff – IoaTzimas Dec 14 '20 at 15:46
  • @Muhammad Hidayat you can try this: `def pricing(): age = int(input("Enter age:")) return 10 if age<12 else 20 if age < 59 else 15 total=sum([pricing() for i in range(3)]) print("The total price for the tickets is $" + str(total))` – IoaTzimas Dec 14 '20 at 15:52
  • If we start to write short codes: `get_price = lambda age: (15, 20, 10)[(age<12)+(age<59)]` followed by `print(f'The total price for the tickets is ${sum(get_price(int(input("Enter age:"))) for _ in range(3))}')`. – Matthias Dec 14 '20 at 16:03

3 Answers3

0

I would do this

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))
DiegoT
  • 29
  • 6
0

I would suggest creating a function that, given the age and returns the price. You can also create a function to get the age. It will then be easy to use in a loop or a comprehension to add up the prices:

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

This will separate computations from user interactions and it will be easy to add validations to the input (such as a permissible age range or to check if the value is numeric)

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

try using the while statement, in this context;

while true:
   # Code goes here

while true: means that when the program is running, execute this code repeatedly until it stops.

James Barnett
  • 561
  • 5
  • 18