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"
Related
Im having some issue with my code. Im not really sure what's wrong with it. Thank you
if mNewCal or fNewCal < 1200:
NameError: name 'mNewCal' is not defined
sorry if the format is a little weird, stack overflow made it weird.
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n " ))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input("How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
mBMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
fBMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = mBMR * 1.2
elif exercise == 2:
cal = mBMR * 1.375
elif exercise == 3:
cal = mBMR * 1.55
elif exercise == 4:
cal = mBMR * 1.8
else:
if exercise == 1:
cal = fBMR * 1.2
elif exercise == 2:
cal = fBMR * 1.375
elif exercise == 3:
cal = fBMR * 1.55
elif exercise == 4:
cal = fBMR * 1.8
if gender == 1:
mTotalCal = mBMR * 1.2
#print(mTotalCal)
else:
fTotalCal = fBMR * 1.2
# print(fTotalCal)
looseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if looseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
mNewCal = mTotalCal - 500
else:
fNewCal = fTotalCal - 500
if mNewCal or fNewCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print("In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
You only define fNewCal or mNewCal and have both in an or statement, if you haven't defined one of the variables and it's checked by the if statement it will raise a NameError like this. You should just use one variable, like newCal, and determine whether it's female or male using the existing gender variable like this:
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n "))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input(
"How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
mBMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
fBMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = mBMR * 1.2
elif exercise == 2:
cal = mBMR * 1.375
elif exercise == 3:
cal = mBMR * 1.55
elif exercise == 4:
cal = mBMR * 1.8
else:
if exercise == 1:
cal = fBMR * 1.2
elif exercise == 2:
cal = fBMR * 1.375
elif exercise == 3:
cal = fBMR * 1.55
elif exercise == 4:
cal = fBMR * 1.8
if gender == 1:
mTotalCal = mBMR * 1.2
# print(mTotalCal)
else:
fTotalCal = fBMR * 1.2
# print(fTotalCal)
looseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if looseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
newCal = mTotalCal - 500
else:
newCal = fTotalCal - 500
if newCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
In general, since you already have a gender variable, there's no reason to sex your other variables, either, though the remaining ones currently won't break the program because they are all contingent on gender. Here it is without the pointlessly sexed variables, it will work fine this way:
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n "))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input(
"How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
BMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
BMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = BMR * 1.2
elif exercise == 2:
cal = BMR * 1.375
elif exercise == 3:
cal = BMR * 1.55
elif exercise == 4:
cal = BMR * 1.8
else:
if exercise == 1:
cal = BMR * 1.2
elif exercise == 2:
cal = BMR * 1.375
elif exercise == 3:
cal = BMR * 1.55
elif exercise == 4:
cal = BMR * 1.8
if gender == 1:
TotalCal = BMR * 1.2
# print(mTotalCal)
else:
TotalCal = BMR * 1.2
# print(fTotalCal)
loseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if loseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
newCal = TotalCal - 500
else:
newCal = TotalCal - 500
if newCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
This program will ask the user for the number of half-dollars, quarters, dimes, nickels, and pennies s/he has and then compute the total value. The total value of the change is shown both as the total number of cents and then as the separate number of dollars and cents. I want to include a final total that displays after the user is finished; which will display the total of all amounts entered throughout the session(i.e. all loop iterations). So how can I code this?
#getCoin function
def getCoin(coinType):
c = -1
while c < 0:
try:
c = int(input("How many " + coinType + " do you have? "))
if c < 0:
print("Coin counts cannot be negative. Please re-enter.")
except ValueError:
print("llegal input. Must be non-negative integer. Re-enter.")
c = -1
return c
print("Welcome to the Change Calculator")
print()
choice = input ("Do you have any change (y/n)?")
while choice.lower() == "y":
h = getCoin("Half-Dollars")
q = getCoin("Quarters")
d = getCoin("Dimes")
n = getCoin("Nickel")
p = getCoin("Pennies")
print()
TotalVal = (h*50) + (q*25) + (d*10) + (n*5) + p
print("You have " + str(TotalVal) + " cents.")
dollars = TotalVal // 100 # // is for division but only returns whole num
cents = TotalVal % 100 # % is for modulos and returns remainder of whole number
print("Which is " + str(dollars) + " dollars and " + str(cents) + " cents.")
choice = input("Do you have more change (y/n)? ")
print("Thanks for using the change calculator.")
finalTotal = TotalVal
print("You had a total of" + finalTotal + " cents.")
print("Which is" + str(finalTotalDollars) + " dollars and" + str(finalTotalCents) + " cents.")
To make it so when a user wants to play again, you could use an external file to write to and read from using open, read and write, to store user info.
You could use notepad as .txt and write user name, money, and repeat, so login checks and calls the money at the line after the name.
I'm making a simple program (I am a beginner at python) where I fight a monster with random assigned values. I used 2 lists with 4 variables each depicting hp atk def and spd. They get assigned a random number of 10 to 15 and get multiplied by 2. I don't really know what I am doing wrong here.
import random
monsters = ["slime","goblin","troll","dryad","bard","clown"]
hp,atk,dfn,spd = 0,0,0,0
mhp,matk,mdfn,mspd = 0,0,0,0
stats = [hp,atk,dfn,spd]
mstats = [hp,atk,dfn,spd]
damage = 0
defend = 0
action = "none"
name = input()
print("Your name is " + name + ", time to battle!")
for x in stats:
stats[x] = random.randint(10,15) * 2
print("Your stats(hp/a/d/s): " + str(stats[x]))
for y in mstats:
mstats[y] = random.randint(10,15) * 2
print("Monster stats(hp/a/d/s): " + str(mstats[y]))
while stats[hp] > 0 or mstats[hp] > 0:
print("What will you do? 1 for attack, 2 for defend, others to give up")
action = input()
if action == "1":
damage = stats[atk] / 2 + random.randint(1,5)
mstats[hp] = mstats[hp] - damage
print("You slash the monster for " + str(damage) + " damage!" )
print("Monster HP: " + str(mstats[hp]))
damage = mstats[atk] / 2
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action == "2":
damage = mstats[atk] / 2 - random.randint(3,5)
if damage > 0:
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action != "1" and action != "2":
stats[hp] = 0
if stats[hp] < 0 or stats[hp] == 0:
print("You lose!")
if mstats[hp] < 0:
print("You win!")
Hopefully this code isn't a mess, I thank you all in advance if extra corrections can be given.
well i am trying to make a bmi & bmr calculator.
I have got the code down yet when i select bmi, it goes through the bmi process then immediately after it has finished it runs the mbr, then the program crashes?
HALP?
#menu
#Ask weather to print BMI or BMR
output = str(input('Calulate BMI or BMR or Exit: '))
print (output)
#BMI
if output == 'BMI' or 'bmi':
#Get height and weight values
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
#Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
#Fiqure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18:
text = 'Underweight'
if bmi <= 24: # we already know that bmi is >=18
text = 'Ideal'
if bmi <= 29:
text = 'Overweight'
if bmi <= 39:
text = 'Obese'
else:
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
#bmr
if output == 'bmr' or 'BMR':
gender = input('Are you male (M) or female (F) ')
if gender == 'M' or 'm':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
print (bmr)
if gender == 'F' or 'f':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print (bmr)
#exit
elif output == 'exit' or 'Exit' or 'EXIT':
exit()
Any help is welcome!
Cheers!
There are many bugs or inconsistencies within your code, here are a few main ones.
The or logical operator cannot be used like that, this is most prominent in the main if statements. Here is a tutorial to get you started on that.
The if and elif are very badly used, if is for a condition, elif is run if the subsequent if hasn't been satisfied, and if the code within the elif has, while the third one, else is more of a default statement, per se, if nothing was satisfied go to this one. Here is some documentation about it.
You are reusing the same code way too much, this should be fixed.
There are a few other tidbits that will show themselves in the code below, I've heavily commented the code so you can understand it thoroughly.
# Menu
# Ask whether to print BMI, BMR, or to exit
output = str(input('Calulate BMI or BMR or Exit: '))
print ('You entered: ' + output) # Try not to print 'random' info
# Exit, I put it up here to make sure the next step doesn't trigger
if output == 'exit' or output == 'Exit' or output == 'EXIT':
print('Exiting...') # Try to always notify the user about what is going on
exit()
# Check if the input is valid
if output != 'BMI' and output != 'bmi' and output != 'BMR' and output != 'bmr':
print('Please enter a valid choice.')
exit()
# Get user's height, weight and age values
# Never write code more than once, either place it in a function or
# take it elsewhere where it will be used once only
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
# BMI
if output == 'BMI' or output == 'bmi':
# Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
# Figure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18: # First step, is it less than 18?
text = 'Underweight'
elif bmi <= 24: # If it isn't is it less than or equal to 24?
text = 'Ideal'
elif bmi <= 29: # If not is it less than or equal to 29?
text = 'Overweight'
elif bmi <= 39: # If not is it less than or equal to 39?
text = 'Obese'
else: # If none of the above work, i.e. it is greater than 39, do this.
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
# BMR
elif output == 'bmr' or output == 'BMR':
gender = str(input('Are you male (M) or female (F): '))
age = int(input('Please enter your age in years: '))
bmr = 0 # Initialize the bmr
if gender == 'M' or gender == 'm':
# Figure out and print the BMR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
if gender == 'F' or gender == 'f':
# Figure out and print the BMR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print ('Your BMR is: ' + bmr)
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.