How to pass arguments to function, differently different times? - python

I need to pass two different arguments to the code (cartype and bonus) and set a for loop, so that each time it loops a different kind of car would be displayed & a different bonus amount.
I have looked for several solutions on here, on google & in my textbook without any success. I know it would be easier to do them all seprately but this is what is required.
Any help would be fantasic :) Please find part of my code below.
def main():
#This program uses a while loop, to give the user the option to go again.
while True:
#This displays the heading & instructions.
print ('AUSSIE BEST CAR INCOME AND BONUS CALCULATOR')
print ('*********************************')
print('**Please input data in the following format: 10000 **')
print('**Please be aware that inputs of zero(0) are invalid**')
#The program asks the user to input the total price of the cars, one by one.
kluger_price = float(input('Please enter the selling price of the Toyota Kluger: $'))
patrol_price = float(input('Please enter the selling price of the Nissan Patrol: $'))
territory_price = float(input('Please enter the selling price of the Ford Territory: $'))
#The program asks the user to input the total amount of cars sold, one by one.
kluger_sold = int(input('Please enter the number of Toyota Klugers sold in 2014:'))
patrol_sold = int(input('Please enter the number of Nissan Patrols sold in 2014:'))
territory_sold = int(input('Please enter the number of Ford Territorys sold in 2014:'))
#The program calculates the totals of each of the cars, one by one.
kluger_total = kluger_price*kluger_sold
patrol_total = patrol_price*patrol_sold
territory_total = territory_price*territory_sold
total = kluger_total + patrol_total + territory_total
#The program calculates the total bonus
if total <= 500000:
bonus = 0.001*total
elif total <= 1000000:
bonus = 500 + (total - 500000)*0.002
elif total <= 5000000:
bonus = 1500 + (total -1000000)*0.003
elif total <= 10000000:
bonus = 13500 + (total - 5000000)*0.004
else:
bonus = 33500 + (total - 10000000)*0.005
#The program calculates the bonus contributed by each car
global kluger_bonus
kluger_bonus = kluger_total/total*bonus
global patrol_bonus
patrol_bonus = patrol_total/total*bonus
global territory_bonus
territory_bonus = territory_total/total*bonus
print ('*********************************')
#The program displays the total income made and bonus
print ('The amount made from the Toyota Klugers is $', format(kluger_total,',.2f'))
print ('The amount made from the Nissan Patrols is $', format(patrol_total,',.2f'))
print ('The amount made from the Ford Territorys is $', format(territory_total,',.2f'))
print ('The total amount amount made from all three cars is $', format(total,',.2f'))
print ('The total bonus for 2014 is $', format(bonus,',.2f'))
print ('The bonus contributed through the sale of the Toyota Klugers is $', format(kluger_bonus,',.2f'))
print ('The bonus contributed through the sale of the Nisssan Patrols is $', format(patrol_bonus,',.2f'))
print ('The bonus contributed through the sale of the Ford Territorys is $', format(territory_bonus,',.2f'))
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in enumerate(3)]
def CalculateAdditionalBonus(cartype,bonus):
rate = input('Please input the value the assessed for the additional bonus of the', cartype')
additional_bonus = rate*bonus
print('The additional bonus for the', cartype' is $', format(additional_bonus,',.2f')
def CalculateTotalBonus():
#This ends the while loop, giving the user the option to go again.
try_again = int(input('This is the end of the calculations.Press 1 to try again, 0 to exit.'))
if try_again == 0:
break
if try_again == 1:
print('===============================================================')
main()

I'm not sure if I understood your question correctly, but I guess you want to pass cartype and bonus into your CalculateAdditionalBonus function. If that's the case, just zip the two lists to combine them into a list of tuples, then iteratively feed into your function.
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in zip(cartype, bonus)]

The answer is to use an if-elif-else statement.

Related

Why does my code keep printing the first data in the array?

i = 0
one_adult = [20.00,30.00]
one_child = [12.00,18.00]
one_senior = [16.00,24.00]
family_ticket = [60.00,90.00]
groups_of_six = [15.00,22.50]
lion_feeding = 2.50
penguin_feeding = 2.00
evening_barbecue = 5.00
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
Attractions_1day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding]
Attractions_2day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding,"evening_barbecue",evening_barbecue]
option = input("are you buying tickets for one day? (yes or no)")
if option == "yes" :
print()
print("These are ticket types available for one day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for one day tickets and their prices $")
print()
print(Attractions_1day)
elif option == "no" :
i = i + 1
print()
print("These are ticket types available for two day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for two day tickets and their prices $")
print()
print(Attractions_2day)
Why does it keep printing the data when i = 0 and not the data when i = 1?
It is supposed to print one_adult, 30 not one_adult 20 etc
The program is supposed to display the options available for people to buy tickets (1 day / 2 day)
Move the line:
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
to if and elif clause
if option == "yes" :
//Here
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
print()
print("These are ticket types available for one day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for one day tickets and their prices $")
print()
print(Attractions_1day)
elif option == "no" :
i = i + 1
//And here.
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
print()
print("These are ticket types available for two day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for two day tickets and their prices $")
print()
print(Attractions_2day)
Check your code properly, You have specified i=0 and and in every place in the Ticket_type array you have put one_adult[i] which is just the first element of the array i.e "20".
You haven't increased the value of i after every iteration. like you have to put loops to increase the value so that other elements of the array is printed.
To solve your problem do this
["one_adult",one_adult[0],"one_child",one_child[1],"one_senior",one_senior[2],"family_ticket",family_ticket[3],"groups_of_six",groups_of_six[4]]
Reply if this was helpful or you want better explanation.

My while loop is keeps looping. What am I doing wrong?

In this the total amount is the amount the user need to pay. If user pay lesser than the total amount the system needs to subtract the payment and show their balance and keep on looping until the payment is completed. But, when I run my codes its keep on looping while showing the balance.
print ("Your total amount is:", total_amount)
print ("")
payment = int(input("Please insert your payment: "))
count = 0
while payment != total_amount:
count = total_amount - payment
print ("Your balance:", count)
payment = int(input("Please insert your payment: "))
if payment == total_amount:
print ("Successful")
does the program outputs "Successful" if the user inputs the total amount on the first input?
if the user doesnt input the total amount on the first input, what could happen is that the variable named payment will never be equal to the total payment, but the count will eventually reach the total amount yes, but the while loop does not has variable count working is logic statement, it uses payment as the variable for its logic. if someones buys a something from a store, and the total is 5 dollars,, and the buyer has 1 dollar bills, the buyer will first put one dollar on the counter, then the other 1, and so on... but the buyer will not put 1 dollar on the counter, and then 5 dollars on the counter, because that would be 6 dollars
You are not updating either payment or total_amount correctly in the loop. I believe this should work.
payment = int(input("Please insert your payment: "))
while payment <= total_amount:
diff = total_amount - payment
print("Your balance:", diff)
payment += int(input("Please insert your payment: "))
if payment == total_amount:
print("Successful")
 Based on your code, only if I pay the correct amount in one go, should I successfully pay. Of course this is wrong. I have modified and added some details to your code like this:
print("Your total amount is: $%.2f \n" % (total_amount))
count = 0
while count < total_amount:
payment = int(input("Please insert your payment: $"))
count += payment
print ("Your balance: $%.2f" % (total_amount - count))
print("Successful")
if count > total:
print("Your change is $%.2f" % (count - total))

How do I continuously re-run a program in Python?

I created a program that calculates how much money is saved after a "percentage off" is applied. The user is able to input the price of the product as well as the percentage off. After the program does the calculation, how do I continuously loop the program so that the user can keep using it without me having to click "run" each time in the console.
def percent_off_price():
price = amount * percent
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
Put the whole code segment in a while loop which runs always but it is the worst thing you would want:
while True:
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
You can also put a check to run it for controlled amount. Hence it would only run if the amount entered is a positive value:
flag= True
while flag:
amount = float(input('Enter the price of your product: '))
if amount <0:
flag=False
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
Lastly if you want to run it for a fixed no. of times (Let's say 10) you can go for a for loop:
for i in range(10):
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
You can do:
while True:
percent_off_price()

Recurring line disappearance, issue with while loop

*I'm new to python, so be gentle...
Overall issue: I have had an issue in multiple codes I've written lately where lines get skipped and it is obviously an error on my part. I know I must be messing up ordering of something, but I'm just not seeing it. My most recent issue can be found here: Is there any reason Python would skip a line?
Now, I want to write an application to pre-sell a limited number of tickets. Here are the conditions:
"Each buyer can buy as many as 4 tickets. There are a total of 15 tickets that are available to pre-sell. The program should prompt the user for the amount of tickets they want to purchase and then display the number of remaining tickets. Repeat until all tickets have been sold, and then display the total number of buyers."
A similar problem is occurring.
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
buy = input("How many tickets would you like to purchase? ")
else:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
print()
print("The total number of buyers was:", buyers)
It appears that the print line in the 'else' structure is not being read and I don't quite understand why...
Can anyone lend me any insight into what my overall misunderstanding is..?
I figured it out. I had a couple of things incorrect with this problem:
I did not have enough conditional statements (elif) to cover the requirements
I did not need to have the buy variable gather input again in the if statement because the while loop would already cause the program to prompt for input again.
I did not need to have the buy variable outside the while loop at all, I just had to initialize it before using it in the 'if' statement.
The solution is as follows:
tickets = 15
buyers = 0
print("There are currently", tickets, "tickets available.")
while tickets > 0 :
buy = int(input("How many tickets would you like to purchase? "))
if buy <= 4 and tickets - buy >= 0:
tickets = tickets - buy
buyers = buyers + 1
print("There are", tickets, "tickets remaining.")
elif buy > 4:
print("You cannot buy that many (4 max).")
elif tickets - buy < 0:
print("You can only buy what remains. Please see previous 'remaining' message.")
print()
print("There was a total of", buyers, "buyers.")
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
#buy = input("How many tickets would you like to purchase? ")
else:
if ticket_num - buy>=0:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
else:
print("There are currently", ticket_num, "remaining. You can buy up to", ticket_num, "tickets")
print()
print("The total number of buyers was:", buyers)
Here is the solution. Problem was you were getting input two times. Firstly below the while. Secondly below at the if statement.

How to use the return function but avoid repetition of a function?

Trying to write this salary calculator script, but the output keeps on calculating taxes twice. It does what it is supposed to do, but I am misusing the concept of return statement, I reckon. I am kinda new to Python and just starting with the DSA. I tried searching for this problem a lot but apart from info for return statement, I couldnt solve this recurring statement problem. I would like your suggestions on the rest of the program as well.
Thanks!
Here is my code:
import math
# Personal Details
name = input("Enter your first name: ")
position= input("Enter your job position: ")
def regPay():
#Computes regular hours weekly pay
hwage= float(input("Enter hourly wage rate: "))
tothours=int(input("Enter total regular hours you worked this week: "))
regular_pay= float(hwage * tothours)
print ("Your regular pay for this week is: ", regular_pay)
return hwage, regular_pay
def overTime(hwage, regular_pay):
#Computes overtime pay and adds the regular to give a total
totot_hours= int(input("Enter total overtime hours this week: "))
ot_rate = float(1.5 * (hwage))
otpay= totot_hours * ot_rate
print("The total overtime pay this week is: " ,otpay )
sum = otpay + regular_pay
print("So total pay due this week is: ", sum)
super_pay = float((9.5/100)*sum)
print ("Your super contribution this week is:",super_pay)
return super_pay
def taxpay():
#Computes the taxes for different income thresholds, for resident Aussies.
x = float(input("Enter the amount of your yearly income: "))
while True:
total = 0
if x < 18200:
print("Congrats! You dont have to pay any tax! :)")
break
elif 18201 < x < 37000:
total = ((x-18200)*0.19)
print ("You have to pay AUD" ,total , "in taxes this year")
return x
break
elif 37001 < x < 80000:
total = 3572 + ((x-37000)*0.32)
print("You have to pay AUD",(((x-37000)*0.32) +3572),"in taxes this year")
return x
break
elif 80001 < x < 180000:
total = 17547+((x-80000)*0.37)
print ("You have to pay AUD" ,total ,"in taxes this year")
return x
break
elif 180001 < x:
total = 54547+((x-180000)*0.45)
print ("You have to pay AUD" , total ,"in taxes this year")
return x
break
else:
print ("Invalid input. Enter again please.")
break
def super(x):
#Computes super over a gross income at a rate of 9.5%
super_rate = float(9.5/100)
super_gross = float((super_rate)*(x))
print ("Your super contribution this year is: ",super_gross)
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
#Call main
main()
The output I get in powershell:
PS C:\Users\tejas\Desktop\DSA> python salary_calc.py
Enter your first name: tj
Enter your job position: it
Enter hourly wage rate: 23
Enter total regular hours you worked this week: 20
Your regular pay for this week is: 460.0
Enter total overtime hours this week: 20
The total overtime pay this week is: 690.0
So total pay due this week is: 1150.0
Your super contribution this week is: 109.25
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Your super contribution this year is: 1900.0
From your output, I see it asks twice for the yearly income:
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Looks like your problem is here:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
You call taxpay(), then set y to another call of taxpay(). Did you mean just to call this once? If so, try this instead:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
y = taxpay()
super(y)
Simply put, both of the following call / execute the taxpay function, so this will repeat exactly the same output, unless you modify global variables, which doesn't look like you are.
Only the second line will return the value into the y variable.
taxpay()
y = taxpay()
Along with that point, here you call the function, but never capture its returned output
overTime(hw, r_p)
And, as an aside, you don't want to break the input loop on invalid input.
print ("Invalid input. Enter again please.")
break # should be 'continue'

Categories