I have to create a BMI program. The weight should be entered as kilograms and the height as cm, then the program should convert the entered values to imperial equivalents and display them and after it should then calculate the BMI and display the result.
So far I have created a BMI calculator where the user can choose between Metric and Imperial. I have created a while true statement for the user to choose only between metric and imperial and when the user puts the height and the weight it will calculate and then display the result. BUT my problem is that I have to convert the metric values to imperial and I don't know how to do it. I miss the converter for metric to imperial and vice versa, any ideas how to improve it?
while True:
try:
if choice == 'Metric':
weight = float(input('weight in kg:'))
height = float(input('height in cm:'))
if choice == 'Imperial':
weight = float(input('weight in pounds:'))
height = float(input('height in inches:'))
except ValueError:
print('Invalid input')
else:
break
if choice == "Metric":
bmi = weight / (height * height)
return bmi
if choice == "Imperial":
bmi = (weight * 703) / (height * height)
return bmi
You first have to define the variable choice because so far you have created if statements that are just not being activated. So try this:
def conversion_to_metric(weight, height):
"""Convert values from Imperial to Metric"""
pound = 0.453592
kg_ans = float(weight * pound)
inch = 2.54
cm_ans = float(inch * height)
print("--------------------")
print(str(weight) + "lbs. " + "= " + str(kg_ans) + "kg.")
print(str(height) + "in. " + "= " + str(cm_ans) + "cm.")
def conversion_to_imperial(weight, height):
"""Convert values from Metric to Imperial"""
kg = 2.20462
lbs_ans = float(weight * kg)
cm = 0.393701
inch_ans = float(cm * height)
print("--------------------")
print(str(weight) + "kg. " + "= " + str(lbs_ans) + "lbs.")
print(str(height) + "cm. " + "= " + str(inch_ans) + "in.")
while True:
try:
print("A. Imperial -> Metric\n" + "B. Metric -> Imperial")
choice = input("Choose a conversion: ")
if choice == 'B':
weight = float(input('\tweight in kg:'))
height = float(input('\theight in cm:'))
conversion_to_imperial(weight, height)
if weight == 'q' or height == 'q':
break
elif choice == 'A':
weight = float(input('\tweight in pounds:'))
height = float(input('\theight in inches:'))
conversion_to_metric(weight, height)
if weight == 'q' or height == 'q':
break
elif choice == 'q':
break
except ValueError:
print('Please enter either A or B...')
Hope this helps. Remember to always give the user an option to quit, or else you will have an endless loop that eats up your memory. Fix a few of my variable around.
Related
I am trying to make a program that will calculate your popularity and based on that, use an algorithm to cycle through a friend list and open txt files based on that, then calculate their popularity, and if it is in a radius of 10 popularity points, they are put as compatible. However, my code is not working and my if statement keeps returning true no matter what. However, when printing the popularities, it says some are in my range, and some aren't. Why is my code failing?
def popularity(G, So, Sm, Sp):
g = float(G) * 0.3
so = float(So) * 0.4
sm = float(Sm) * 0.1
sp = float(Sp) * 0.2
return g + so + sm + sp
gfactor = input("What is your G-Factor? ")
social = input("What is your Social Quotient? ")
smartness = input("What is your smartness level? ")
sports = input("What is your sports skill? ")
poplr = popularity(gfactor, social, smartness, sports)
print(str(math.ceil(poplr * float(10))) + "%")
print("Finding friends... ")
for i in friends:
fs = open(i + ".txt")
json_str = fs.read(37)
data = json.loads(json_str)
friend_poplr = popularity(data["g"], data["So"], data["Sm"], data["Sp"]) * float(10)
if friend_poplr > float(poplr) - float(10):
if friend_poplr < float(poplr) + float(10):
print("# " + i + " is a compatible friend #")
else:
print("# " + i + " is not a compatible friend #")
else:
print("# " + i + " is not a compatible friend #")
Yes, I have imported math and json, and also have a list of friends, but I am censoring their names. PLEASE HELP!!!
I think the problem is the fact that you multiply friend_polr by 10 and you dont do the same for poplr. All you need to do is multiply poplr by 10 to make them both even. In my example below i made some other minor improvements to your code
def popularity(G, So, Sm, Sp):
g = float(G) * 0.3
so = float(So) * 0.4
sm = float(Sm) * 0.1
sp = float(Sp) * 0.2
return g + so + sm + sp
gfactor = input("What is your G-Factor? ")
social = input("What is your Social Quotient? ")
smartness = input("What is your smartness level? ")
sports = input("What is your sports skill? ")
poplr = popularity(gfactor, social, smartness, sports) * 10
print(str(math.ceil(poplr)) + "%")
print("Finding friends... ")
for i in friends:
fs = open(i + ".txt")
json_str = fs.read(37)
data = json.loads(json_str)
fs.close() # remember to close the file
friend_poplr = popularity(data["g"], data["So"], data["Sm"], data["Sp"]) * 10
if friend_poplr > poplr - 10:
if friend_poplr < poplr + 10:
print("# " + i + " is a compatible friend #")
continue
print("# " + i + " is not a compatible friend #")
I have a frame for the python code that calculates bmi.
i have done most of the part but I cannot seem to get around the sentinel loop. The goals are:
user enters a patient identification number (an int), patient name (a string), patient height in inches (a positive float), and patient weight in pounds (a positive float) until the user enters a negative number for the patient ID .
I have done the BMI calculation.
For each patient’s information entered, output a well-formatted result listing the patient’s ID, name, calculated BMI (output with 1 digit of precision) and associated category (Underweight, Obese, etc.). The use of f-strings to produce the formatted output is recommended.
After trying and some googling, here is what I have. I would like help with the sentinel loop.
class BodyMassIndex:
def __init__(self, pid, name, weight, height):
self.patient_id = pid
self.name = name
self.weight = weight
self.height = height
#property
def body_mass_index(self):
return round((self.weight * 703) / self.height ** 2, 1)
#property
def score(self):
if self.body_mass_index < 18.5:
return 'Underweight'
elif self.body_mass_index < 25:
return 'Healthy Weight'
elif self.body_mass_index < 30:
return 'Overweight'
else:
return 'Obese'
def print_score(self):
print('Patient id {}: {} has a bmi score of {}. Patient is {}.'.format(self.patient_id, self.name, self.body_mass_index, self.score))
def _get_user_info():
while True:
try:
pid = int(input("Please enter your 5-digit patient id: "))
p_name = input("Please enter patient first name and last name: ")
weight = float(input('Enter weight in pounds: '))
height = float(input('Enter height in inches: '))
if 0 < weight and 0 < height < 107:
return pid, p_name, weight, height
else:
raise ValueError('Invalid height or weight. Let us start over.')
except ValueError:
print('Invalid height or weight input')
continue
def calculate_bmi():
pid, name, weight, height = _get_user_info()
return BodyMassIndex(pid, name, weight, height)
if __name__ == '__main__':
bmi = calculate_bmi()
bmi.print_score()
I was told I would need to delete the print_score function and instead I should have a table of values entered and bmi result when user entered a wrong/negative patient id. It does not need to be 5-digit patient id.
I'm new to python, and I'm trying here to make some math, in Quanity, and balance. But that function in define, don't do anything to balance, and quanity. When I print them they are still the stock.
Ballance = 7000 # 7K DEMO
# SANDELYS
Indica_WEED_QUANITY = 600
AMAZON_QUANITY = 18
STEAM_GIFT50_QUANITY = 4
# Price
STEAM_GIFT50_PRICE_PER1 = 50 # Each
Indica_WEED_PRICE_PER1 = 8
Amazon_Prime_PRICE_PER1 = 25 # Each
def PickForShopItem():
ShopPick = int(input("~ PRODUCT ID = "))
if ShopPick == 1:
clear()
while True:
Pasirinxm = input("Would You like to continue buying ~ Indica WEED KUSH * ?\n* Y/N: ")
if "Y" in Pasirinxm or "y" in Pasirinxm:
clear()
BuyKiekis = int(input("~ How many you would to buy of " + Indica_WEED_NAME + "?\n "))
Indica_WEED_QUANITY - BuyKiekis # Atimam Ir paliekam sandari mazesni
Bendra_Suma = ( BuyKiekis * Indica_WEED_PRICE_PER1)
print(Bendra_Suma)
Ballance = 500
print(Ballance - Bendra_Suma)
print("Sandelio Kiekis po pirkimo " + str(Indica_WEED_QUANITY))
print(Ballance)
break
elif "N" in Pasirinxm or "n" in Pasirinxm:
print("xuine iseina")
break
elif " " in Pasirinxm or len(Pasirinxm) < 1:
print("PLease dont do shit")
continue
break
elif ShopPick == 2:
print("Darai")
elif ShopPick == 3:
print("hgelo")
Indica_WEED_NAME = "~ Indica WEED KUSH *
I think the problem you have is that:
Indica_WEED_QUANITY - BuyKiekis
does not update the variable "Indica_WEED_QUANITY" (and you have the same problem in the line print(ballance - BendraSuma))
In Python, that statement will just work out a value, but you aren't telling the program to save or store it anywhere. Do this:
Indica_WEED_QUANITY = Indica_WEED_QUANITY - BuyKiekis
Python also allows you to do this with a -= operator:
Indica_WEED_QUANITY -= BuyKiekis
will update Indica_WEED_QUANITY by subtracting the BuyKeikis amounts.
I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()
import sys
import os.path
class Juvenile(object):
def createJuv(self, pop, rate):
self.pop = pop
self.rate = rate
def displayJuvpop(self):
return self.pop
def displayjuvRate(self):
return self.rate
class Adult(object):
def createAd(self, pop, rate, brate):
self.pop = pop
self.rate = rate
self.brate = brate
def displayAdpop(self):
return self.pop
def displayAdRate(self):
return self.rate
def displayBirthrate(self):
return self.brate
class Senile(object):
def createSe(self, pop, rate):
self.pop = pop
self.rate = rate
def displaySepop(self):
return self.pop
def displaySerate(self):
return self.rate
a = Juvenile()
b = Adult()
c = Senile()
`enter code here`pop_model = raw_input("Enter the number of generations: ")
`enter code here`pop_model = int(pop_model)
newjuv = 0
newsen = 0
newadu = 0
def menu():
This = True
while This == True:
print("1) Enter Generation 0 values")
print("2) Display Generation 0 values")
print("3) Run the model")
print("4) Export data")
print("5) Quit")
decision = raw_input("")
if decision == "1":
Gen0values()
elif decision == "2":
display()
elif decision == "3":
run()
elif decision == "4":
export()
elif decision == "5":
sys.exit()
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
def Gen0values():
a.createJuv(float(raw_input("Enter the juvenile population: ")), float(raw_input("Enter the Juvenile survival rate: ")))
b.createAd(float(raw_input("Enter the Adult population: ")), float(raw_input("Enter the Adult survival rate: ")), float(raw_input("Enter the birth rate: ")))
c.createSe(float(raw_input("Enter the Senile population: ")), float(raw_input("Enter the Senile survival rate: ")))
menu()
The error is coming up here:
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
The error comes up with "Can't assign to function call, line 60". Due to stack overflow's code to text limit, I've removed parts of the program that are irrelevant, like exporting the data and displaying the values.
Ps: This isn't an indentation error, copying and pasting somewhat disrupted it.
Your display*pop() functions return a value, not a variable. You can't assign to that function result. Just assign directly to the attributes:
a.pop = newjuv
b.pop = newsen
c.pop = newadu