I am making a macronutrient calculator. This this calculator if the user makes an error calculator simply restarts and goes back to the main(). However, I believe my use of main() in my code causes the display of 2 runs of the code
Here is the link to my code: http://pastebin.com/FMqf2aRS
*******Welcome to the MACRONUTRIENT CALCULATOR********
Enter your calorie deficit: 30
Percentage of Protein: 30
Percent of Carbohydrates: 40
Percentage of Fats: 40
Total percentages surpassed 100! Please reenter percentages.
*******Welcome to the MACRONUTRIENT CALCULATOR********
Enter your calorie deficit: 2200
Percentage of Protein: 30
Percent of Carbohydrates: 30
Percentage of Fats: 40
You must eat 660.0 calories of protein which is equivalent to 165.0 grams of protein.
You must eat 880.0 calories of fat which is equivalent to 97.7777777778 grams of fat.
You must eat 660.0 calories of carbohydrates which is equivalent to 73.3333333333 grams of carbohydrates.
You must eat 9.0 calories of protein which is equivalent to 2.25 grams of protein.
You must eat 12.0 calories of fat which is equivalent to 1.33333333333 grams of fat.
You must eat 12.0 calories of carbohydrates which is equivalent to 1.33333333333 grams of carbohydrates.
Is there a different way of approaching this to prevent this from happening?
Calling main() the way you are doing it is the wrong way to solve this. You're pushing more and more main() calls onto the stack - eventually the program will crash if you enter invalid entries too many times in a row. You should use a while loop as shown below
def main():
while True:
print "*******Welcome to the MACRONUTRIENT CALCULATOR********"
calorie_deficit = float(input("Enter your calorie deficit: "))
Percent_protein = float(input("Percentage of Protein: "))
Percent_carb = float(input("Percent of Carbohydrates: "))
Percent_fat = float(input("Percentage of Fats: "))
Macro_dict = {'Protein': Percent_protein, 'Carbohydrate': Percent_carb, 'Fats': Percent_fat}
Macro_sum = Percent_protein + Percent_carb + Percent_fat
if not Total_Macro_Check(Macro_sum):
continue
Macro_percentage_to_calorie(calorie_deficit, Percent_protein, Percent_carb, Percent_fat)
def Total_Macro_Check(total_val):
if total_val > 100:
print "Total percentages surpassed 100! Please reenter percentages."
return False
if total_val < 100:
print "Total precentages is less than 100! Please reenter precentages."
return False
return True
The code is doing exactly what you tell it to do:
def Total_Macro_Check(total_val):
if total_val > 100:
print "Total percentages surpassed 100! Please reenter percentages."
main()
if total_val < 100:
print "Total precentages is less than 100! Please reenter precentages."
main()
You call main again.
Related
The Speedy Shipping Company will ship packages based on how much they weigh and how far they are being sent. They will only ship light packages up to 10 pounds. You have been tasked with writing a program that will help Speedy Shipping determine how much to charge per delivery.
The charges are based on each segment of 500 miles shipped. Shipping charges are not pro-rated; i.e., 600 miles is the same charge as 900 miles; i.e., 600 miles is counted as 2 segments of 500 miles.
Your program should prompt the user for inputs (weight and miles), accept inputs from the keyboard, calculate the shipping charge, and produce accurate output.
Test:Prompts / Inputs:
Please enter package weight in pounds: 1.5
Please enter number of miles to ship: 200 (This is one 500-mile segment.)
Expected result:
To ship a 1.5 pound package 200 miles, your shipping charge is $1.50.
Helpful Hints:
You can use integer (floored) division. For example: 1200 // 500 = 2
So I have typed the code to the best of my knowledge however my print statement just prints (1.5). I need help in understanding why my print statement won't print the results.
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("1.5"))
num_miles_ship = int(input("200"))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package > 2 and weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package > 6 and weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
shipping_charge = weight_of_package//num_miles_ship * shipping_rate
print(("To ship a " +str(weight_of_package) + "pound package" + str(num_miles_ship)
+ "your shipping charge is" + str(shipping_charge,".2f")))
There are several problems with your code.
The input method does probably do something else than you think. I does not convert anything, but it ask the user (you) for input and return this input. a=input("enter value for a:") will just open a prompt that will let you type something on your keyboard and when you press enter this will be copied into variable a here. So you may want to do weight_of_package=int(input("enter weight of package: ")) etc.
In your if/elif sequence: careful! python uses indentation to understand your scoping! This is critical in python and wrong in your code. You have to intend code in the if/elif blocks.
You can save some typing in the elif statements, since all the weight_of_package > XXX statements have no effect because of the preceding if statements (this would be just the else)
Before you second-last line shipping_charge = ... you need to protect against shipping_rate equal to zero. This will happen for a weight_of_package > 10 and will just fail in the calculation. Thus you need to add if shipping_rate>0: ...
Division operator in python is / not //
Best leave away the ,"2.f" in str(shipping_charge,".2f") since this does not do what you believe. If you do want to use formatted output use the standard python format syntax "{:.2f}".format(shipping_charge)`. Please consult https://docs.python.org/3/library/string.html#formatspec which is very interesting and relevant.
Here is the full example:
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("please enter weight of package: "))
num_miles_ship = int(input("please enter miles to ship: "))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
if shipping_rate > 0:
shipping_charge = weight_of_package / num_miles_ship * shipping_rate
print("To ship a {} pound package {} miles "
"your shipping charge is {:.2f} ".format(
weight_of_package, num_miles_ship, shipping_charge))
Your print statement is probably not being executed at all right now
I am guessing that 1.5 which you are probably seeing is the result of this line probably
weight_of_package = int(input("1.5"))
The input() function in python takes an argument that tells the user about the input being required. So, if you change it to
weight_of_package = float(input("Enter the weight of package"))
and then run the program. You'll be prompted to Enter the weight of package following which you need to give the program input for the weight of the package ( and you'll enter 1.5 )
Also, you need to use float instead of int in that line as 1.5 is a decimal value
Making this change, it'll be easier for you to debug the print statements that are at the bottom of the code as 1.5 won't confuse you.
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))
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'
relatively new to programming in python, thank you for all the fast help that was provided on my last question I had on another python project. Anyways, Ive written a new program for a project in python that produces a bill for a catering venue. This is my code below, everything runs fine, and I get the intended results required for the project, The two problems I am experience are, 1. I need the cost of the desert to not print---> 3.0 but ---> $3.00, essentially, how can I print dollar signs, and round e.x 3.0 --> 3.00, or 45.0--> 45.00..and with dollar signs before prices. Sorry if something like this has been asked..
import math
# constants
Cost_Per_Desert = 3.00
Tax_Rate = .075
Gratuity_Tips = .15
Adult_Meal_Cost = 12.75
Child_Meal_Cost = .60*12.75
Room_Fee = 450.00
Less_Deposit = 250.00
def main():
# Input Section
Name = input("\n\n Customer:\t\t\t ")
Number_Of_Adults = int(input(" Number of Adults:\t\t "))
Number_Of_Children = int(input(" Number of Children:\t\t "))
Number_Of_Deserts = int(input(" Number of Deserts:\t\t "))
print("\n\nCost Of Meal Per Adult:\t\t" , Adult_Meal_Cost)
print("Cost of Meal Per Child:\t\t" , round(Child_Meal_Cost,2))
print("Cost Per Desert:\t\t" , round(Cost_Per_Desert,2))
# Processing/Calculations
Total_Adult_Meal_Cost = Adult_Meal_Cost* Number_Of_Adults
Total_Child_Meal_Cost = Child_Meal_Cost* Number_Of_Children
Total_Desert_Cost = Cost_Per_Desert* Number_Of_Deserts
Total_Food_Cost = Total_Adult_Meal_Cost + Total_Child_Meal_Cost + Total_Desert_Cost
Total_Taxes = Total_Food_Cost * Tax_Rate
Tips = Total_Food_Cost * Gratuity_Tips
Total_Bill = Total_Food_Cost + Total_Taxes + Tips + Room_Fee
# Output Section
print("\n\n Total Cost for Adult Meals: \t", Total_Adult_Meal_Cost)
print(" Total Cost for Childs Meals: \t", Total_Child_Meal_Cost)
print(" Total Cost for Desert: \t", Total_Desert_Cost)
print(" Total Food Cost: \t\t", Total_Food_Cost)
print("\n\n Plus 7.5% Taxes: \t\t", round(Total_Taxes,2))
print(" Plus 15.0% Tips: \t\t", round(Tips,2))
print(" Plus Room Fee: \t\t", Room_Fee)
print("\n\n Total Bill: \t\t\t", round(Total_Bill,2))
print(" Less Deposit: \t\t\t", Less_Deposit)
print("\n\nBalance Due: \t\t\t", round(Total_Bill - Less_Deposit,2))
print("\n\n\n\n\t\t Thank You For Using Passaic County Catering Services. ")
main()
input("\n\n\n\n\nPress Enter to Continue")
Let's say cost of desert is $3.00
cost = 3
print("${0:.2f}".format(cost))
Output:
$3.00
When you need to add a $ sign you just simply put a $ sign in your string.
If you would like to fix the decimal number places you just need basic string formatting, like:
print('pi is %.2f' % 3.14159)
and the output would be pi is 3.14
You might wanna like to read: https://docs.python.org/2.7/library/string.html#formatspec
I'm writing a simple python program that helps users keep track of the number of calories that they consume and displaying whether the user is over or within their calorie goal for the day.
Here's my code so far.
caloriesGoal = float(input('Enter the calorie goal for number of calories for today: '))
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
totalConsumed = 0
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
numberOfCaloriesConsumed = float(input('How many calories did you consumed?'))
totalConsumed += numberOfCaloriesConsumed
count = count + 1
print('Your total calories consumed is: ' , totalConsumed)
if(caloriesGoal > totalConsumed):
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Try this out, the output is much clearer for what you are expected to enter.
while True:
caloriesGoal = float(input('Enter the calorie goal the day: '))
if 1500 <= caloriesGoal <= 3000:
break
else:
print("Error: Goal must be between 1500 and 3000 calories!")
totalConsumed = 0
items = 0
while True:
caloriesConsumed = float(input('Item {}: How many calories was it? (-1 to stop)'.format(items+1)))
if caloriesConsumed < 0:
print("Input stopped")
break
totalConsumed += caloriesConsumed
items += 1
if totalConsumed > caloriesGoal:
print("Goal reached/exceeded!")
break
print('You consumed {} calories in {} items.'.format(totalConsumed, items))
if caloriesGoal > totalConsumed:
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Welcome to Python! It was my second language, but I love it like it was my first. There are few things going on in your code that's a little strange.
Something interesting is that you're doing a check on numberOfCaloriesConsumed. If you're entering a Krispy Kreme donut, you're going to enter 190 calories. Let's review your while:
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
If we take a look at this line ...
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
... and we enter 190 for our Krispy Kreme donut, then we won't enter the loop. What you may want to change the while to is an infinite loop with a break mechanism:
while 1:
numberOfCaloriesConsumed = input('How many calories did you consumed?')
if (numberOfCaloriesConsumed == "q") or (totalConsumed > 3000): # keep numberOfCaloriesConsumed as a string, to compare for the break
if (totalConsumed < 1500):
print("You need to eat more!\n")
else:
break
else:
if (totalConsumed + int(numberOfCaloriesConsumed)) > 3000:
print("You eat too much! You're done now!\n")
break
totalConsumed = totalConsumed + int(numberOfCaloriesConsumed) #make the string an int, if we're adding it
This way, the code loop is exited when your user manually exits the loop (or if they've entered too many calories). Now, your user should be able to input caloric data and have it added up for them.
Also, I would remove the counter because the counter isn't necessary for this loop. We've got a few reasons why we don't need the counter:
The counter isn't directly affecting the loop (e.g. no while counter < 5)
We have the computer asking for user input, so the program stops and gives control to the human thus no infinite loop
We have break statements to remove us from the (new) loop