How do I continuously re-run a program in Python? - 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()

Related

How to create a tipping function in python

trying to fix this code for tipping.
Let's add a tipping function. I've created the bare-bones of the function, which will take in the cost of the meal, and ask for a percentage to tip on the meal. You do the rest!
def tip(cost):
percentage = input("What percent would you like to tip? ")
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
the first part does not seem to work
after that, I run
cost, items = order(menu)
print("Your order is", items)
cost = round(cost + tax("vt", cost, tax_rate), 2)
cost = round(cost + tip(cost), 2)
print("Your total cost is", cost)
You have to convert the input to float in order to perform mathmatical operation . Otherwise it will multiply the string with number and return a repeated string.
def tip(cost):
percentage = float(input("What percent would you like to tip? "))
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip

Python : Amount input with While

Beginner here. I'm trying to build a loop where the chekout displays a total amount that has to be over 0$. For example, if I start with 450$ the code works. But if I start with say -12 it will ask me again (which is what I want), but then if I enter 450 as the third essay; the first condition keeps runing. Why is that? Thanks in advance.
amount = input("What's the total amount of the bill ? :")
value = float(amount)
while (value < 0):
print("Please enter an amount higher than 0$ !")
amount = input("What's the total amount of the bill ? :")
else:
print("Total amount of the bill:{0}".format(value))
You forgot to update the variable "value" so your while loop condition remains true even after inputting 450 (value is still -12). You can convert the input to a float in the same line too, which removes the need for the "amount" variable
value = float(input("What's the total amount of the bill ? :"))
while (value < 0):
print("Please enter an amount higher than 0$ !")
value = float(input("What's the total amount of the bill ? :"))
else:
print("Total amount of the bill:{0}".format(value))

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

Subtract a tuple from an int

I keep getting a error that tuple cant be subtracted from a integer. I am trying to add all inputs to a list, then add all contents together and subtract it from the total monthly cash flow.
def budget_50_total():
list=[]
monthly = int(input("How much is your monthly cash flow "))
essential = budget_50(monthly)
print(essential)
# Do calculation for 50%
print("Please enter your essential expenses! ")
house = int(input("How much is your housing for month: "))
utilities = int(input("How much is your utilities this month 'gas, power, etc': "))
grocery = int(input("How much is your groceries for month "))
health = int(input("How much is your health insurance for the month "))
car = int(input("How much is your car payment"))
for i in range(1):
data = house, utilities,grocery,health,car
list.append(data)
print(list)
total = sum(list)
print(total)
total2 = essential - total
print(total2)
This line creates a tuple:
data = house, utilities,grocery,health,car
Then you add the tuple to the list in the next line. You won't be able to sum a list of tuple. You could however do
data = house, utilities,grocery,health,car
print(data)
total = sum(data)
However, your error "tuple cant be subtracted from a integer" is likely caused by your calculation for total2 as that is your only subtraction in the code shown. It's impossible to say what the issue is here without knowing what essential is.
You can use a for loop to add the sum of each tuple in list to the total:
total = 0
for x in list:
total += sum(x)

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