Personal Code Project Only Works Sometimes - python

I wrote this code because I'm just starting out and wanted to practice a little bit. This code only works 1 out of every 10 times I try to run it. I wrote it in Jupyter Notebook.
When it doesn't work I get the NameError: name 'oatcalories' is not defined. Sometimes it says 'eggcalories' is not defined as well.
How do I make sure it works 100% of the time?
Here it is:
while True:
one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")
if one == "done":
print ("Done")
break
if one.lower() == "eggs":
quantegg = input("How many eggs? ")
eggcalories = (int(quantegg) * 78)
elif one.lower() == "oatmeal":
quantoat = input("How many servings of oatmeal? ")
oatcalories = (int(quantoat) * 120)
elif one.lower() == "avacado":
quantav = input("How many avacados: ")
avcalories = (int(quantav) * 120)
elif one.lower() == "toast":
quantoast = input("How many pieces of toast?: ")
toastcalories = (int(quantoast) * 70)
butter = input("Did you add butter?")
if butter.lower()[0] == "y":
quantbut = input("How many servings of butter?: ")
butcalories = (int(quantbut) * 102)
elif butter.lower()[0] == "n":
butcalories = (int(quantbut) * 0)
else:
pass
break_total = eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)
This newbie appreciates your help!

You aren't defining any of the variables used in the break_total line at the very bottom. If your code was like this, it should work fine:
eggcalories = 0
oatcalories = 0
avcalories = 0
toastcalories = 0
butcalories = 0
while True:
one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")
if one == "done":
print ("Done")
break
if one.lower() == "eggs":
quantegg = input("How many eggs? ")
eggcalories = (int(quantegg) * 78)
elif one.lower() == "oatmeal":
quantoat = input("How many servings of oatmeal? ")
oatcalories = (int(quantoat) * 120)
elif one.lower() == "avacado":
quantav = input("How many avacados: ")
avcalories = (int(quantav) * 120)
elif one.lower() == "toast":
quantoast = input("How many pieces of toast?: ")
toastcalories = (int(quantoast) * 70)
butter = input("Did you add butter?")
if butter.lower()[0] == "y":
quantbut = input("How many servings of butter?: ")
butcalories = (int(quantbut) * 102)
elif butter.lower()[0] == "n":
butcalories = (int(quantbut) * 0)
else:
pass
break_total = eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)
The cause for error was because you were trying to add things that you hadn't set yet, so when you tried to add them the interpreter didn't know what you were referencing.

Related

I am making a calculator the issue is on line 42 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

cant figure out line 42 keep getting error TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' could some one advise me on how to fix it as i have been stuck on it for hrs how the code work is you run it and then you pick what type of calculation you want to do in this case area of a circle is broken and for some reason it wont work how its supposed to work is that def check checks if the string are numbers or letters and if they are numbers it will continue and if it is letters it will restart and say that you need to choose numbers not letters
import time
import math
def check(num1, num2):
number1 = str(num1).isnumeric()
if number1 == False:
print('Bruh math not l\'anglais')
time.sleep(0.5)
restart()
number2 = str(num2).isnumeric()
if number2 == False:
print('Bruh math not l\'anglais')
time.sleep(2.5)
while True:
restart()
def percentage_decrease():
original_amount = str(input("Please give me the original amount: "))
percentage_decrease = str(input("Give me percentage to decrease: "))
check(original_amount, percentage_decrease)
multiplier = 1 - int(percentage_decrease) / 100
answer = int(original_amount) * multiplier
print("The answer is",answer)
def percentage_increase():
original_amount = str(input("Please give me the original amount: "))
percentage_increase = str(input("Give me percentage to increase: "))
check(original_amount, percentage_increase)
multiplier = 1 + int(percentage_increase) / 100
answer = int(original_amount) * multiplier
print("The an is",answer)
def power_of_x():
num = str(input("What number would you like to find out the power off: "))
power = str(input("what power do you to do: "))
check(num, power)
answer = int(num**power)
print("The answer is",answer)
def area_circle():
user_choice = input("Would you like to use diameter or radius?")
if user_choice.lower() == "radius" or user_choice.lower() == "r":
num_area_circle_radius = str(input("Please give me the radius: "))
check(num_area_circle_radius, '0')
anwser_area_circle = math.pi * int(num_area_circle_radius**2)
rounded_anwser_area_circle = round(anwser_area_circle, 2)
print("The anwser is",rounded_anwser_area_circle,"rounded 2d.p")
elif user_choice.lower() == "diameter" or user_choice.lower() == "d":
num_area_circle_diameter = str(input("Please give me the diameter: "))
check(num_area_circle_diameter, '0')
convert_diameter_radius = num_area_circle_diameter / 2
anwser_area_circle = math.pi * int(convert_diameter_radius**2)
rounded_anwser_area_circle = round(anwser_area_circle, 2)
print("The anwser is",rounded_anwser_area_circle,"rounded 2d.p")
def addition():
num1_addition = input("First Number pls: ")
num2_addition = input("Second Number pls: ")
check(num1_addition, num2_addition)
answer_addition = int(num1_addition) + int(num2_addition)
print("The answer is",answer_addition)
def multiply():
num1_multiply = str(input("First Number pls: "))
num2_multiply = str(input("Second Number pls: "))
check(num1_multiply, num2_multiply)
answer_multiply = int(num1_multiply) * int(num2_multiply)
print("The answer is",answer_multiply)
def subtraction():
num1_subtraction = str(input("First Number pls: "))
num2_subtraction = str(input("Second Number pls: "))
check(num1_subtraction, num2_subtraction)
answer_subtraction = int(num1_subtraction) - int(num2_subtraction)
print("The answer is",answer_subtraction)
def division():
num1_division = str(input("First Number pls: "))
num2_division = str(input("Second Number pls: "))
check(num1_division, num2_division)
answer_division = int(num1_division) / int(num2_division)
print("The answer is",answer_division)
def start():
print("These are multiple things you can do \n1)Addition \n2)Subtraction \n3)Multiplication \n4)Division \n5)Area Of Circle \n6)Power Off x \n7)Percentage Increase \n8)Percentage Decrease")
time.sleep(0.5)
user_operator = input("What calculation would you like to: ")
if user_operator.lower() == "Addition" or user_operator == "1":
addition()
elif user_operator.lower() == "Subtraction" or user_operator == "2":
subtraction()
elif user_operator.lower() == "Division" or user_operator == "4":
division()
elif user_operator.lower() == "Multiplication" or user_operator == "3":
multiply()
elif user_operator.lower() == "Area of a circle" or user_operator == "5":
area_circle()
elif user_operator.lower() == "power of x" or user_operator == "6":
power_of_x()
elif user_operator.lower() == "percentage increase" or user_operator == "7":
percentage_increase()
elif user_operator.lower() == "percentage decrease" or user_operator == "8":
percentage_decrease()
else:
start()
start()
def restart():
user_restart = input("Do you want to do another calculation(y or n): ")
if user_restart == "Y".lower():
start()
elif user_restart == "N".lower():
print("Thank you for using my calculator.")
else:
start()
while user_restart == "Yes".lower():
restart()
if user_restart == "No".lower():
user_restart = "No"
while True:
restart()
num = str(input("What number would you like to find out the power off: "))
power = str(input("what power do you to do: "))
check(num, power)
answer = int(num**power)
You meant to convert "num" to int, and then take the power, you misaligned your brackets.

End a function when the user provides a certain keyword as input

How can I end a function when a user types a specific keyword (e.g. 'off') in an input without having to add the necessary code within each input? Basically I want the function to completely stop when a user types the word 'off' anywhere in any of the inputs below. I have created a function (see bottom of code) and have tried placing/calling it throughout my code but am not sure exactly where to put it or if I can even do this with a function? If not, how can I achieve this?
def order_coffee():
drink = input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(input("How many quarters?: ")) * .25)
dimes = (int(input("How many dimes?: ")) * .1)
nickels = (int(input("How many nickels?: ")) * .05)
pennies = (int(input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()
def off():
if input == "off":
return
Create your own input function an add the desired behaviour:
def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
exit()
return str
This will exit from the entire application when the user input is "off", to exit only from the function throw an exception instead, and catch it outside the function call. For instance:
def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
raise ValueError('Time to go')
and:
def order_coffee():
try:
# your code
except ValueError as err:
# handle it accordingly
return
A clearer approach is to create, throw, and handle a custom Exception. Have a look at this SO Thread to get an idea of how to implement those custom exceptions.
def order_coffee():
drink = input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
elif drink == 'off':
return None
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(input("How many quarters?: ")) * .25)
dimes = (int(input("How many dimes?: ")) * .1)
nickels = (int(input("How many nickels?: ")) * .05)
pennies = (int(input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()
You can create your own input function to check for this and when the event 'off' is entered then exit the program. That way if someone enters "off" at any point in the program it will end.
import sys
def get_input(text):
user_feedback = input(text)
if user_feedback == 'off':
sys.exit()
return user_feedback
def order_coffee():
print("Welcome to the coffee robot! (type 'off' to exit at any time)")
drink = get_input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(get_input("How many quarters?: ")) * .25)
dimes = (int(get_input("How many dimes?: ")) * .1)
nickels = (int(get_input("How many nickels?: ")) * .05)
pennies = (int(get_input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()

Loops in Python terminating Programm

I am new to coding and Python in general, and I can't figure this out.
I added loops so that the program does not terminate every time there is a typo, however I messed up something with the second loop presumably.
I think it might be connected to the whitespace, but I can't figure it out.
The Programm terminates after taking in the "calories_burned" variable.
def start():
print("""This is a Weight Calculator, please follow the instructions.""")
name = input("What is your name? ")
age = int(input("How old are you? "))
if 19 <= age <= 78:
height = float(input("How tall are you in cm? "))
current_weight = float(input("How much do you currently weigh? "))
goal_weight = float(input("How much do you want to weigh? "))
calories_consumed = int(input("How many calories did you consume today? "))
calories_burned = int(input("How many calories did you burn today? "))
def activity():
global rmr
activity_factor = input("Choose an activity factor: Sedentary, Lightly active, Moderately Active, Very Active ")
zif activity_factor == "sedentary":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.2))
if activity_factor == "lightly active":
rmr = int(round((10 * current_weight + 6.25 * height - 5 * age + 5) * 1.375))
if activity_factor == "moderately active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.550))
if activity_factor == "very active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.725))
else:
activity()
daily_deficit = int((rmr + calories_burned - calories_consumed))
print("Your daily deficit is: " + str(daily_deficit))
import numpy
mean_deficit = [daily_deficit]
calculation_mean_deficit = int(round(7500 / numpy.mean(mean_deficit)))
reach_goal = int(round((current_weight - goal_weight) * calculation_mean_deficit))
print(mean_deficit)
print(name + " it will take you " + str(calculation_mean_deficit) + " days to loose 1 kg.")
print(name + " it will take you " + str(reach_goal) + " days to reach your goal.")
choice = input("do you wish to continue Y/N?")
if choice == "n":
return
else:
start()
else:
print("Invalid age")
start()
start()
You don't call the activity() function anywhere in your code, so once the program collects the inputs it doesn't do anything else and exits.
Also it's "lose" not "loose"

looking for advice for coding project

So as of right now the code needs to re-ask the problem given if the answer given was too high or too low. Also, if the answer is correct, it should tell them and then loop back to the question ('How many problems do you want?')
def main():
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = (num_1*num_2)
count += 1
for guess in range(1):
if guess == answer:
print (' Thats Correct!')
for guess in range(1):
if guess > answer:
print (' Answer is to high')
for guess in range(1):
if guess < answer:
print ('Answer is to low')
main()
First of all can you please check your code. You have used "guess" variable in the for loop. When the program is executed the value of guess is say 40(4X10). When for statement is executed the guess values becomes 0 because of that you are getting the output as low. Make sure u change the variable you use in for loop to "num" and then check your output.
Why are you using 3 for loops you can do that in single for loop.
Please find the below code:-
from random import randint
def main():
ans = 'y'
while ans != 'n':
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
print(guess)
answer = (num_1*num_2)
print("=====>",answer)
count += 1
for num in range(1):
if guess == answer:
print (' Thats Correct!')
elif guess > answer:
print (' Answer is to high')
elif guess < answer:
print ('Answer is to low')
yes_no_input = str(input("Do you want to continue (y/n) ?"))
ans = accept_ans(yes_no_input)
if ans == 'n':
print("thanks for the test")
break;
def accept_ans(ans):
if not ans.isalpha():
print("Enter only y and n")
ans = str(input("Do you want to continue (y/n) ?"))
if ans == 'y' or ans == 'n':
return ans
if ans != 'y' or ans != 'n':
print("please enter y for YES and n for NO")
ans = str(input("Do you want to continue (y/n) ?"))
if ans != 'y' or ans != 'n':
accept_ans(ans)
if __name__ == '__main__':
main()
After
print("Thats correct")
you need to call the
main()
function again.

Defining Functions, TypeError

Probably obvious, but for some reason, this code:
import random
import time
def tables():
global tablesUsed
tablesUsed = [int(x) for x in input("Please choose which multiplication tables you wish\nto practice, then type them like this: 2 5 10.\n").split()]
return tablesUsed
def timer():
timer = input("Do you wish to play with the timer? (yes or no)\n")
if timer == "yes":
withTimer()
else:
withoutTimer()
def withTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def withoutTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
print("Congratulations, you got it correct!\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def playAgain():
playAgain = input("Do you wish to play again? (yes or no)\n")
if playAgain == "yes":
settings()
else:
print("Thank you for practising your multiplication tables with me. Your final score was " + score + " and your average time was " + averageTime)
def settings():
settings = input("Do you wish to edit settings? (yes or no)\n")
if settings == "yes":
tables()
timer()
tables()
timer()
returns an error saying:
TypeError: 'str' object is not callable, line 66, line 10, line 35
Please could someone help and tell me what I'm doing wrong?
I gather that it's probably to do with defining functions incorrectly, but I can't find anything on that solves my problem.
You defined playAgain both as a function and a local variable in the withTimer function:
def withTimer():
playAgain = "yes"
# ...
while playAgain == "yes":
# ....
playAgain() # this is now a string, not the function
Don't do that, use meaningful names that don't shadow your function names.

Categories