How to add a counter function? - python

So i need to count how many times BMI is calculated and for it to print at the end of this loop. Any ideas?
print("Hello and welcome to the BMI calculator!!")
user = input("Would you like to go again, Y/N: ")
while user == "y":
height = int(input("Please put in your height in Meters: "))
weight = int(input("Please put in your weight in Kilogram: "))
BMI = weight/ (height*height)
if BMI < 18:
print("Your BMI is:", BMI, "Eat some more Big Macs, you are too skinny!")
elif BMI > 25:
print("Your BMI is:", BMI, "Stop eating all those Big Macs, you are far too fat!")
elif BMI >18 < 25:
print("Your BMI is:", BMI, "You are a normal and healthy weight, congratulations!!!")
user = input("Would you like to go again, Y/N: ")
input("\nPress the enter key to exit")

Fairly simple. Just make a variable outside the loop, and increment it every time the loop begins.
print("Hello and welcome to the BMI calculator!!")
count = 0;
user = input("Would you like to go again, Y/N: ")
while user == "y":
count += 1 #Increase count by one
height = int(input("Please put in your height in Meters: "))
weight = int(input("Please put in your weight in Kilogram: "))
BMI = weight/ (height*height)
if BMI < 18:
print("Your BMI is:", BMI, "Eat some more Big Macs, you are too skinny!")
elif BMI > 25:
print("Your BMI is:", BMI, "Stop eating all those Big Macs, you are far too fat!")
elif BMI >18 < 25:
print("Your BMI is:", BMI, "You are a normal and healthy weight, congratulations!!!")
user = input("Would you like to go again, Y/N: ")
print("You checked your BMI", count, "times.")
input("\nPress the enter key to exit")

Related

Variables aren't passing from one function to another why?

I'm a Python beginner and trying to build upon my code below. I have the base working and want to collect the data from the calculator and store it in a dictionary. I created the last function to do this, but I can't pass the variables from bmi_metrics(). Why?
#Intro to BMI Calculator
print("Welcome to my BMI calculator!")
print("Give me your height and weight, I'll calculate your Body Mass Index")
# Gather BMI metrics from user and create two loops that only accept number inputs for height/weight
def bmi_metrics():
get_name = (input("\nWhat's your name? "))
while True:
try:
get_height = float(input(f"\nHi {get_name.title()}, please enter your height in inches: "))
break
except ValueError:
print("Oops, that doesn't look like a number, try again.")
while True:
try:
get_weight = float(input("Please enter your weight in pounds: "))
break
except ValueError:
print("Oops, that doesn't look like a number, try again.")
#Calculate BMI from height and weight input
BMI = (get_weight * 703) / (get_height ** 2)
#Display user BMI and weight category back to them
print(f"{get_name.title()}, your BMI is {BMI:.2f}")
if BMI <= 18.5:
print(f"A person with a BMI of {BMI:.2f} is underwieght ")
elif BMI <= 24.9:
print(f"A person with a BMI of {BMI:.2f} is normal weight ")
elif BMI <= 29.9:
print(f"A person with a BMI of {BMI:.2f} is overweight ")
else:
print(f"A person with a BMI of {BMI:.2f} is obese")
return get_name, get_height, get_weight, BMI
#Prompt user to run calculator again
def prompt_again():
while True:
run_again = input("\nWould you like to do another calculation (y/n)? ")
if run_again == 'y':
bmi_metrics()
elif run_again == 'Y':
bmi_metrics()
elif run_again == 'N':
break
elif run_again == 'n':
break
else:
print("Please enter 'y' or 'n' ")
print("Thanks for playing!")
#Collect Name/BMI data and place it in an empty dictionary
def calc_data():
calc_results = {"Name": " ", "BMI": " "}
get_name = name
bmi_metrics()
prompt_again()
Hello :) You are missing the storage of the returned values from the call at the end of the script:
get_name, get_height, get_weight, BMI = bmi_metrics()
Otherwise, the result is not stored. You have to keep in mind that all variables in python defined inside a method are local to the method unless you store them in an object, return them as result of the method or define them as global variables. If you want to use the resulting values in another function you need to pass them as arguments.

How do you add user counter to BMI calculator?

I've made this BMI calculator and I want the user count at the bottom to count every time the user has used the BMI calculator by entering "y". I can't seem to get the code to work. Any help?
user_continue = "y"
counter = 0
while user_continue == "y":
weight = float(input("What is your weight? (KG) "))
height = float(input("What is your height? (Metres) "))
#formula to convert weight and height to users bmi
bmi = weight/(height*height)
print("Your BMI is", bmi)
#indicators to state if user is either underwieght, overweight or normal
if bmi < 18:
print("It indicates you underweight.")
elif bmi >= 18 and bmi < 25:
print("It indicates you are within normal bounds.")
elif bmi >= 25:
print("It indicates you are overweight.")
user_continue = input("Add Another BMI? y/n: ")
# add counter
if user_continue != "y":
counter+=1
print(counter)
print("\t\tThank You for using BMI calculator by Joe Saju!")
print("\n\t\t\t\tPress ENTER to Exit.")
break
You want to increase the counter in any iteration of the loop so you need increase the counter variable inside the loop but not in the ending if statement.
Tip: increase counter variable at the begining of the loop(like in the code below)
In your case the counter increase only if the user want exit. so it will counter only one time.
user_continue = "y"
counter = 0
while user_continue == "y":
# increase the counter at the begining
counter+=1
weight = float(input("What is your weight? (KG) "))
height = float(input("What is your height? (Metres) "))
#formula to convert weight and height to users bmi
bmi = weight/(height*height)
print("Your BMI is", bmi)
#indicators to state if user is either underwieght, overweight or normal
if bmi < 18:
print("It indicates you underweight.")
elif bmi >= 18 and bmi < 25:
print("It indicates you are within normal bounds.")
elif bmi >= 25:
print("It indicates you are overweight.")
user_continue = input("Add Another BMI? y/n: ")
if user_continue != "y":
# counter+=1 line removed and moved to the begining
print(counter)
print("\t\tThank You for using BMI calculator by Joe Saju!")
print("\n\t\t\t\tPress ENTER to Exit.")
break

BMI Calculator not outputting Python

I'm building a BMI Calculator in Python and after choosing the metric or imperial system it won't post. The code is 100% functional other than that.
I added the option to choose if you want to use the imperial system or the metric system.
How could I improve the code?
def WeightCalMetric() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in meters? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Kg? "))
break
except:
print("Your weight has to be a number")
Bmi = UserWeight / (UserHeight ** 2)
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
def WeightCalImperial() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in inches? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Lbs? "))
break
except:
print("Your weight has to be a number")
Bmi = 703 * (UserWeight / (UserHeight ** 2))
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
print("Hi welcome to this BMI Calculator")
print("First choose if you want to use the metric system or the imperial system")
print('Write "Metric" for the metric system or write "Imperial" for the imperial system')
KgOrLbs = None
while KgOrLbs not in ("metric", "Metric", "imperial", "Imperial"):
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs == "metric, Metric":
WeightCalMetric()
elif KgOrLbs == "imperial" "Imperial":
WeightCalImperial()
I'm supposed to add more details, but I don't really have any more details, to be honest, so now I'm just writing all of this just so I can post this
You should change the while loop where you check the inputs. The code below lowercases the input and checks whether it is "metric" or "imperial", so there is no need to check for capitalized parameters
KgOrLbs = input("Metric or Imperial? ")
while KgOrLbs.lower() not in ["metric", "imperial"]:
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs.lower() == "metric":
WeightCalMetric()
elif KgOrLbs.lower() == "imperial":
WeightCalImperial()

Python craps game, while-loop issue

I'm looking to create a simple craps game and I am having issues.
When this code is inputted:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
rounds = input("Play again? (Y/N): ")
while rounds != "n" and rounds == "y":
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
break
main()
this happens when I input "n".
Enter your bet: 5
Dice roll 1: 6
Dice roll 2: 6
Your roll: 12
Play again? (Y/N): n
and this happens when I input "y".
Enter your bet: 5
Dice roll 1: 2
Dice roll 2: 3
Your roll: 5
Play again? (Y/N): y
You push.
You have $10 remaining.
In both instances, it needs to tell the user whether or not they push, win, or lose before it asks if they want to play again. How can I accomplish this?
If I put "rounds" within the while loop, it tells me that rounds is referenced before it's assigned.
I think there's a lot here to neaten up, but why not start with:
rounds = 'y'
while .....
....
....
else:
....
rounds = input("Play again (y/n)")
This way you automatically fall into the while loop after the first roll and give the user results before asking if they want to play again. The next problem you have to deal with is that within the while loop, there is no provision for placing new bets or rolling the dice again.
The first problem is that all of the code that tells the user whether they push, win, or lose is inside the loop, and if the user enters "n", that code never runs. The real problem is that most of your code really should be inside the loop, including asking the user how much they want to bet and rolling the dice.
I would start by initializing the rounds variable to a default value of "y" so that the loop runs at least once, then don't ask the user if they want to play again until the end of the loop. Then move all of your other code inside the loop. (Except for the "How much do you have to gamble?" part. That should probably stay outside the loop.)
This is untested, but the order of things should be something like:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
rounds = "y"
while rounds != "n" and rounds == "y":
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
rounds = input("Play again? (Y/N): ")
main()
You should probably also think about ending the game if the player runs out of money.

Adding floating numbers in python

Trying to add all the BMI results together and then display it, keep getting a error :
TypeError: 'float' object is not iterable
Also keep getting None printed when i run my program after a bmi is calculated>?
def bmirange():
if bmi >= 25.0:
print('Your BMI measurement shows that you are overweight')
elif bmi <18.0:
print('Your BMI measurement shows that you are underweight')
else:
print('Your BMI measurement shows that you are in the healty weight band')
weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
bmi = weight / (height * height)
print(bmi)
print(bmirange())
bmiredo = input('Do you want to do another BMI measurement?, y / n ')
while bmiredo == 'y':
weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
print(bmi)
print(bmirange())
bmiredo = input('Do you want to do anoher BMI measurement?, y / n ')
else:
print('ok, the total of your BMI results are')
print(sum(bmi))
input('press the enter key to exit')
The problem is here:
print(sum(bmi))
The bmi variable is a number, but if you want to use sum() you need a list of numbers. Here is how you can collect a list of numbers. The .append() method adds an element to the end of a list.
bmi_list = []
...
bmi = weight / height**2
bmi_list.append(bmi)
...
while ...:
....
bmi = weight / height**2
bmi_list.append(bmi)
...
...
print(sum(bmi_list))
Note
There is also an error with bmirange(): print() is called twice. You can either put the print() inside bmirange(), or you can print() the results of bmirange(), but doing both will result in None being printed out, which I assume is not what you want.
Solution 1
def bmirange():
if bmi >= 25.0:
print('Your BMI measurement shows that you are overweight')
elif bmi <18.0:
print('Your BMI measurement shows that you are underweight')
else:
print('Your BMI measurement shows that you are in the healty weight band')
...
bmirange() # will print itself
Solution 2
def bmirange():
if bmi >= 25.0:
return 'Your BMI measurement shows that you are overweight'
elif bmi <18.0:
return 'Your BMI measurement shows that you are underweight'
else:
return 'Your BMI measurement shows that you are in the healty weight band'
...
print(bmirange()) # will not print itself

Categories