Function & Loop Python - python

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

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

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)

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.

Related

How to calculate sum of numbers in a list?

I am trying to write a program in which the user enters the age of 8 guests. Each guest's age is priced differently. How can I add each cost together to come up with the total cost for each guest? This is what I have written.
def main():
guest1= int(input("Enter the age of guest 1(in years): "))
guest2 = int(input("Enter the age of guest 2(in years): "))
guest3 = int(input("Enter the age of guest 3(in years): "))
guest4 = int(input("Enter the age of guest 4(in years): "))
guest5 = int(input("Enter the age of guest 5(in years): "))
guest6 = int(input("Enter the age of guest 6(in years): "))
guest7 = int(input("Enter the age of guest 7(in years): "))
guest8 = int(input("Enter the age of guest 8(in years): "))
ages = [guest1, guest2, guest3, guest4, guest5, guest6, guest7, guest8]
getCost(ages)
def getCost(ages):
for age in ages:
if age <=2:
cost = 0
print(cost)
elif age <= 3>12:
cost = 14
print(cost)
elif age >= 65:
cost = 18
print(cost)
else:
cost = 23
print(cost)
main()
You can put all the ages into a list up front by calling input() in a loop instead of copying and pasting it eight times:
ages = [int(input(f"Enter the age of guest {i}(in years): ")) for i in range(1, 9)]
I'd suggest having your getCost function just return the cost for a single age (hint: make this simpler by arranging the age brackets in ascending order, and eliminating them one at a time according to their upper bound):
def getCost(age):
if age < 3:
return 0
elif age < 12:
return 14
elif age < 65:
return 23
else:
return 18
This makes the job of getCost much easier -- then after you've gotten ages you can compute the total cost just by calling getCost(age) for each age and taking the sum of the result:
print(sum(getCost(age) for age in ages))
Splitting the logic into parts like this makes it easy to do other things with the costs; for example, you could show how the total was computed by joining the costs before you sum them:
print(
" + ".join(str(getCost(age)) for age in ages),
"=",
sum(getCost(age) for age in ages)
)
Enter the age of guest 1(in years): 2
Enter the age of guest 2(in years): 9
Enter the age of guest 3(in years): 13
Enter the age of guest 4(in years): 27
Enter the age of guest 5(in years): 44
Enter the age of guest 6(in years): 52
Enter the age of guest 7(in years): 66
Enter the age of guest 8(in years): 81
0 + 14 + 23 + 23 + 23 + 23 + 18 + 18 = 142
You can start by defining a totalCost variable, as a running total that you can keep incrementing after you calculate the cost for each customer. For instance:
def getCost(ages):
totalCost = 0
for age in ages:
if age <=2:
cost = 0
elif age >= 3 and age < 12:
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
totalCost += cost
return totalCost
Do note that I've assumed age <= 3>12 refers to ages between 3 and 11, inclusive.
It seems that you use function getCost to calculate each cost. A little bit modification of adding a variable to sum up all values will help you get what you want.
def sumCost(ages):
total = 0
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
total = total + cost
return total
Or you can construct a list of cost then use sum.
def sumCost(ages):
costs = []
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
costs.append(cost)
total = sum(costs)
return total

How can I resolve no print output of float value commission with arrays?

I am currently working on improving my commission program by implementing arrays into my program. However, I cannot properly display my commission results anymore. If I revert some array changes, I can display my commission fine. Where did I do wrong? I would appreciate any feedback on my code posted below. I'm a beginner and have included code that I have learned up to this point.
MAX = 10
def main():
comp_name = [""] * MAX
sales_amount = [0.0] * MAX
total_sales_amount = 0.0
commission = 0.0
bonus = 0.0
more_sales = 'Y'
select_item = 0
welcome_message()
while more_sales == 'Y':
comp_name[select_item] = get_comp_name()
sales_amount[select_item] = get_sales_amount()
total_sales_amount = total_sales_amount + (sales_amount[select_item] + sales_amount[select_item])
more_sales = more_sales_input()
select_item = select_item + 1
commission += get_commission_calc(sales_amount[select_item])
print_receipt(comp_name, sales_amount, commission, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def print_receipt(comp_name, sales_amount, total_commission, select_item):
sub_total = 0
count = 0
print("\nCompany Name Sales Your Commission")
print("------------ ----- ---------------")
while count < select_item:
print("{0:<15}".format(comp_name[count]), "\t\t$ ", format(sales_amount[count], ".2f"), "\t$ ", format(sales_amount[count], ".2f"))
sub_total = sub_total + (sales_amount[count])
count = count + 1
print("-----------------------------------------------")
print("Collect: $", format(total_commission, ".2f"))
def get_comp_name():
comp = ""
comp = input("\nEnter Company name: ")
return comp
def more_sales_input():
more = ""
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
while more != "Y" and more!= "N":
print("Invalid entry, either y or n.")
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
return more
def get_sales_amount():
sales = 0.0
while True:
try:
sales = float(input("Please enter sales $ "))
if sales < 0:
print("Invalid, must be a positive numeric!")
else:
return sales
except:
print("Invalid, must be a positive numeric!")
def get_commission_calc(sales):
commission = 0.0
if sales >= 20000:
commission = sales * .10
elif sales >= 10000:
commission = sales * .07
else:
commission = sales * .05
return commission
def get_bonus(commission):
if commission >= 1000:
return + 500
else:
return 0
def print_totals(bonus, total_commission):
if bonus > 0:
print("\nYou earned a $500 bonus added to your pay!")
else:
print("\nYou did not yet meet requirements for a bonus!")
print("\nYour commission is", '${:,.2f}'.format(total_commission))
main()

trying to write a food ordering sys for homework in python

im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger

Returning a new value for my string variable

I am trying to update my string variable then return it to be printed.
race = 'human'
age = int(x)
def aging(age, maturity):
if x < 13:
maturity = 'Child'
elif x>13 and x<18:
maturity = 'Teenager'
elif x>18 and x<65:
maturity = 'Adult'
elif x>65 and x<99:
maturity = 'Senior'
else:
maturity = 'Dead'
aging(age, maturity)
x=int(input('Please enter age: '))
print ("Age is",age)
print ("You are a "+maturity)
The end product, however, is always
Please enter age: 9
Age is 9
You are a none
How can I get the maturity string to update?
Let's address your program as a whole -- the major issue I see is that your data is embedded in your code. Let's separate out the data to simplify the code:
MATURITIES = {
'a Child': (0, 12),
'a Teenager': (13, 17),
'an Adult': (18, 64),
'a Senior': (65, 99),
}
def aging(age):
for maturity, (lower, upper) in MATURITIES.items():
if lower <= age <= upper:
return maturity
return 'Dead'
age = int(input('Please enter age: '))
print("Your age is", age)
print("You are", aging(age))
You need to refactor your code - remove x, change where you define variables/take input, and return something (maturity):
def aging(age):
if age < 13:
maturity = 'Child'
elif age > 13 and age < 18:
maturity = 'Teenager'
elif age > 18 and age < 65:
maturity = 'Adult'
elif age > 65 and age < 99:
maturity = 'Senior'
else:
maturity = 'Dead'
return maturity
age = int(input('Please enter age: '))
maturity = aging(age)
print ("Age is" + age)
print("You are a " + maturity)
Output:
Please enter age: 9
Age is 9
You are a Child
Use return
def aging(age, maturity):
if x < 13:
maturity = 'Child'
elif x>13 and x<18:
maturity = 'Teenager'
elif x>18 and x<65:
maturity = 'Adult'
elif x>65 and x<99:
maturity = 'Senior'
else:
maturity = 'Dead'
return age, maturity
race = 'human'
age = int(input('Please enter age: '))
age, maturity = aging(age, maturity)
print ("Age is",age)
print ("You are a "+maturity)
I recommend your function to return maturity.
You can global the variable, but it is considered a bad practice.
I did a few corrections on your code, it should work fine like this:
def aging(age):
if age < 13:
maturity = 'Child'
elif age >= 13 and age <18:
maturity = 'Teenager'
elif age >= 18 and age <65:
maturity = 'Adult'
elif age >= 65 and age < 99:
maturity = 'Senior'
else:
maturity = 'Dead'
return maturity
age = int(input('Please enter age: '))
print ("Age is", age)
print ("You are a", aging(age))

Rogue Number Not Working Python

I have a piece of python code that is supposed to end if a variable is equal to the string 'x', but it doesnt, I dont understand why. Can someone explain please
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = 0
while house_type != "x":
house_type = input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(input("How many rooms does the house have? "))
age = int(input("How old is the house? "))
price = int(input("What is the houses price? "))
if price > biggest_price :
biggest_house_type = house_type
biggest_rooms = number_of_rooms
biggest_age = age
biggest_price = price
if price < smallest_price :
smallest_house_type = house_type
smallest_rooms = number_of_rooms
smallest_age = age
smallest_house_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_house_type, biggest_rooms, biggest_age, biggest_price)
print(smallest_house_price, smallest_rooms, smallest_age, smallest_price)
print(total_price / counter)
Can someone explain why the program doesn't end when X is pressed, and instead just gives house_type the value of 'x'
There were a number of issues. I tried to make a minimal working example.
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = ''
while house_type != "x":
house_type = raw_input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(raw_input("How many rooms does the house have? "))
age = int(raw_input("How old is the house? "))
price = int(raw_input("What is the houses price? "))
if price > biggest_price :
biggest_price = price
if price < smallest_price :
smallest_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_price)
print(smallest_price)
print(total_price / counter)
Output:
What is the house type? 3
How many rooms does the house have? 5
How old is the house? 30
What is the houses price? 100000
100000
100000
100000
What is the house type? 4
How many rooms does the house have? 2
How old is the house? 10
What is the houses price? 200000
200000
100000
150000
What is the house type? x
NOTE:
If you are on Python 2.x use raw_input(). If you are on Python 3.x use input()

Categories