Error with an if statement that I can't figure out - python
I am making a project for school using Python, and I keep getting a traceback error after I input the age, no matter what age I input. I can't figure out why, so hopefully someone else can figure it out.
After I input the age, it does tell me "You have selected a 15-year-old character." (or any other age), but after that, the error comes up.
I don't know where the error is, so I'm just going to put the entire project here.
error001 = "Error 001: Invalid Sex!"
error002 = "Error 002: Invalid Age!"
error003 = "Error 003: Invalid Activity Level!"
error004 = "Error 004: Invalid Age Group!"
print("Hello! Welcome to Nutrition Info!")
sexInput = input("To get started, choose the sex of your character (gender, sexual orientation, etc. do not matter, as these do not matter for your physical health). Type 'M' for male or 'F' for female.")
if sexInput == "M":
sex = "male"
print("You have selected a male character.")
elif sexInput == "F":
sex = "female"
print("You have selected a female character.")
else:
quit(error001)
ageInput = input("How old is your character? Type just the number.")
age = int(ageInput)
if ageInput.isnumeric():
if age == range(1,3):
ageGroup = "toddler"
elif age == range(4,8):
ageGroup = "young child"
elif age == range(9,13):
ageGroup = "older child"
elif age == range(14,18):
ageGroup = "teenager"
elif age == range(19,30):
ageGroup = "young adult"
elif age == range(31,50):
ageGroup = "older adult"
elif age == range(51,130):
ageGroup = "senior"
else:
quit(error002)
print("You have selected a " + ageInput + "-year-old character.")
if ageGroup == "toddler":
dailyCaloriesInt = 1000
dailyProteinInt = 13
dailyCarbohydrateInt = 130
dailyDietryFiberInt = 14
dailyTotalFatLowerInt = 30
dailyTotalFatUpperInt = 40
dailySaturatedFat = 10
dailyLinoleicAcidInt = 7
dailyLinolenicAcidInt - 0.7
dailyCalciumInt = 700
dailyIronInt = 7
dailyMagnesiumInt = 80
dailyPhosphorusInt = 260
dailyPotassiumInt = 3000
dailySodiumInt = 1500
dailyZincInt = 3
dailyCopperInt = 0.34
dailyManganeseInt = 1.2
dailySeleniumInt = 20
dailyVitaminAInt = 300
dailyVitaminB6Int = 0.5
dailyVitaminB12Int = 0.9
dailyVitaminCInt = 15
dailyVitaminDInt = 600
dailyVitaminEInt = 6
dailyVitaminKInt = 30
dailyThiaminInt = 0.5
dailyRiboflavinInt = 0.5
dailyNiacinInt = 6
dailyCholineInt = 200
dailyFolateInt = 150
elif ageGroup == "young child":
dailyProteinInt = 19
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyLinoleicAcidInt = 10
dailyLinolenicAcidInt = 0.9
dailyCalciumInt = 1000
dailyIronInt = 10
dailyMagnesiumInt = 130
dailyPhosphorusInt = 500
dailyPotassiumInt = 3800
dailySodiumInt = 1900
dailyZincInt = 5
dailyCopperInt = 0.44
dailyManganeseInt = 1.5
dailySeleniumInt = 30
dailyVitaminAInt = 400
dailyVitaminB6Int = 0.6
dailyVitaminB12Int = 1.2
dailyVitaminCInt = 25
dailyVitaminDInt = 600
dailyVitaminEInt = 7
dailyVitaminKInt = 55
dailyThiaminInt = 0.6
dailyRiboflavinInt = 0.6
dailyNiacinInt = 8
dailyCholineInt = 0.6
dailyFolateInt = 1.2
if sex == "female":
dailyCaloriesInt = 1200
dailyDietaryFiberInt = 16.8
elif sex == "male":
dailyDietaryFiberInt = 19.6
activityInputMaleYoungChild = input("How active is your character? Type '1' for inactive or '2' for active.")
if activityInputMaleYoungChild == "1":
activity = "inactive"
elif activityInputMaleYoungChild == "2":
activity = "active"
else:
quit(error003)
if activity == "inactive":
dailyCaloriesInt = 1400
elif activity == "active":
dailyCaloriesInt = 1600
else:
quit(error003)
else:
quit(error001)
elif ageGroup == "older child":
dailyProteinInt = 34
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1300
dailyIronInt = 8
dailyMagnesiumInt = 240
dailyPhosphorusInt = 1250
dailyPotassiumInt = 4500
dailySodiumInt = 2200
dailyZincInt = 8
dailyCopperInt = 0.7
dailySeleniumInt = 40
dailyVitaminAInt = 600
dailyVitaminB6Int = 1
dailyVitaminB12Int = 1.8
dailyVitaminCInt = 45
dailyVitaminDInt = 600
dailyVitaminEInt = 11
dailyVitaminKInt = 60
dailyThiaminInt = 0.9
dailyRiboflavinInt = 0.9
dailyNiacinInt = 12
dailyCholineInt = 375
dailyFolateInt = 300
if sex == "female":
dailyCaloriesInt = 1600
dailyDietaryFiberInt = 22.4
dailyLinoleicAcidInt = 10
dailyLinolenicAcidInt = 1
dailyManganeseInt = 1.6
elif sex == "male":
dailyCaloriesInt = 1800
dailyFietaryFiberInt = 25.2
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.2
dailyManganeseInt = 1.9
else:
quit(error001)
elif ageGroup == "teenager":
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = "10"
dailyCalciumInt = 1300
dailyPhosphorusInt = 1250
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.89
dailySeleniumInt = 55
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyDairyInt = 3
if sex == "female":
dailyCaloriesInt = 1800
dailyProteinInt = 46
dailyDietaryFiberInt = 25.2
dailyLinoleicAcidInt = 11
dailyLinolenicAcidInt = 1.1
dailyIronInt = 15
dailyMagnesiumInt = 360
dailyZincInt = 9
dailyManganeseInt = 1.6
dailyVitaminAInt = 700
dailyVitaminB6Int = 1.2
dailyVitaminCInt = 65
dailyThiaminInt = 1
dailyRiboflavinInt = 1
dailyNiacinInt = 14
dailyCholineInt = 400
activityInputFemaleTeenager = input("How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active, then press the 'ENTER' or 'RETURN' key.")
if activityInputFemaleTeenager == "1":
activity = "inactive"
elif activityInputFemaleTeenager == "2":
activity = "moderately active"
elif activityInputFemaleTeenager == "3":
activity = "active"
else:
quit(error003)
if activity == "inactive":
dailyCaloriesInt = 1800
dailyGrainsInt = 6
dailyVegetablesInt = 2.5
dailyFruitsInt = 1.5
elif activity == "moderately active":
dailyCaloriesInt = 2000
dailyGrainsInt = 6
dailyVegetablesInt = 2.5
dailyFruitsInt = 2
elif activity == "active":
dailyCaloriesInt = 2400
dailyGrainsInt = 8
dailyVegetablesInt = 3
dailyFruitsInt = 2
else:
quit(error003)
elif sex == "male":
dailyProteinInt = 52
dailyDietaryFiberInt = 30.8
dailyLinoleicAcidInt = 16
dailyLinolenicAcidInt = 1.6
dailyIronInt = 11
dailyMagnesiumInt = 410
dailyZincInt = 11
dailyManganeseInt = 2.2
dailyVitaminAInt = 900
dailyVitaminB6Int = 1.3
dailyVitaminCInt = 75
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 1.6
dailyCholineInt = 550
activityInputMaleTeenager = input("How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active, then press the 'ENTER' or 'RETURN' key.")
if activityInputMaleTeenager == "1":
activty = "inactive"
elif activityInputMaleTeenager == "2":
activity = "moderately active"
elif activityInputMaleTeenager == "3":
activity = "active"
else:
quit(error003)
if activity == "inactive":
dailyCaloriesInt = 2200
dailyGrainsInt = 7
dailyVegetablesInt = 3
dailyFruitsInt = 2
elif activity == "moderately active":
dailyCaloriesInt = 2800
dailyGrainsInt = 10
dailyVegetablesInt = 3.5
dailyFruitsInt = 2.5
elif activity == "active":
dailyCaloriesInt = 3200
dailyGrainsInt = 10
dailyVegetablesInt = 4
dailyFruitsInt = 2.5
else:
quit(error003)
else:
quit(error001)
elif ageGroup == "young adult":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB6Int = 1.3
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 2000
dailyProteinInt = 46
dailyDietaryFiberInt = 28
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.1
dailyIronInt = 18
dailyMagneseumInt = 310
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
elif sex == "male":
dailyProteinInt = 56
dailyDietaryFiberInt = 33.6
dailyLinoleicAcidInt = 17
dailyLinolenicAcidInt = 1.6
dailyIronInt = 8
dailyMagneseumInt = 400
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
activityInputMaleYoungAdult = input("How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active.")
if activityInputMaleYoungAdult == "1":
activity = "inactive"
elif activityInputMaleYoungAdult == "2":
activty = "moderately active"
elif activityInputMaleYoungAdult == "3":
activity = "active"
else:
quit(error003)
if activity == "inactive":
dailyCaloriesInt = 2400
elif activity == "moderately active":
dailyCaloriesInt = 2600
elif activity == "active":
dailyCaloriesInt = 3000
else:
quit(error003)
else:
quit(error001)
elif ageGroup == "older adult":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB6Int = 1.3
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 1800
dailyProteinInt = 46
dailyDietaryFiberInt = 25.2
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.1
dailyIronInt = 18
dailyMagneseumInt = 320
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
elif sex == "male":
dailyCaloriesInt = 2200
dailyProteinInt = 56
dailyDietaryFiberInt = 30.8
dailyLinoleicAcidInt = 17
dailyLinolenicAcidInt = 1.6
dailyIronInt = 8
dailyMagneseumInt = 420
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
else:
quit(error001)
elif ageGroup == "senior":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyIronInt = 8
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 2000
dailyProteinInt = 46
dailyDietaryFiberInt = 22.4
dailyLinoleicAcidInt = 11
dailyLinolenicAcidInt = 1.1
dailyMagneseumInt = 310
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminB6Int = 1.5
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
elif sex == "male":
dailyProteinInt = 56
dailyDietaryFiberInt = 28
dailyLinoleicAcidInt = 14
dailyLinolenicAcidInt = 1.6
dailyMagneseumInt = 400
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminB6Int = 1.7
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
else:
quit(error001)
else:
quit(error004)
if activity == "inactive":
print("You have selected an inactive character.")
if activity == "moderately active":
print("You have selected a moderately active character.")
if activity == "active":
print("You have selected an active character.")
dailyCalories = str(dailyCaloriesInt)
dailyProtein = str(dailyProteinInt)
dailyCarbohydrate = str(dailyCarbohydrateInt)
dailyDietaryFiber = str(dailyDietaryFiberInt)
dailyTotalFatLower = str(dailyTotalFatLowerInt)
dailyTotalFatUpper = str(dailyTotalFatUpperInt)
dailySaturatedFat = str(dailySaturatedFatInt)
dailyLinoleicAcid = str(dailyLinoleicAcidInt)
dailyLinolenicAcid = str (dailyLinolenicAcidInt)
dailyCalcium = str(dailyCalciumInt)
dailyIron = str(dailyIronInt)
dailyMagneseum = str(dailyMagneseumInt)
dailyPhosphorus = str(dailyPhosphorusInt)
dailyPotassium = str(dailyPotassiumInt)
dailySodium = str(dailySodiumInt)
dailyZinc = str(dailyZincInt)
dailyCopper = str(dailyCopperInt)
dailyManganese = str(dailyManganeseInt)
dailySelenium = str(dailySeleniumInt)
dailyVitaminA = str(dailyVitaminAInt)
dailyVitaminB6 = str(dailyVitaminB6Int)
dailyVitaminB12 = str(dailyVitaminB12Int)
dailyVitaminC = str(dailyVitaminCInt)
dailyVitaminD = str(dailyVitaminDInt)
dailyVitaminE = str(dailyVitaminEInt)
dailyVitaminK = str(dailyVitaminKInt)
dailyThiamin = str(dailyThiaminInt)
dailyRiboflavin = str(dailyRiboflavinInt)
dailyNiacin = str(dailyNiacinInt)
dailyCholine = str(dailyCholineInt)
dailyFolate = str (dailyFolateInt)
if ageGroup == "teenager":
dailyVegetables = str(dailyVegetablesInt)
dailyFruits = str(dailyFruitsInt)
dailyDairy = str(dailyDairyInt)
dailyCalciumGramsInt = dailyCalciumInt/1000
dailyIronGramsInt = dailyIronInt/1000
dailyMagneseumGramsInt = dailyMagneseumInt/1000
dailyPhosphorusGramsInt = dailyPhosphorusInt/1000
dailyPotassiumGramsInt = dailyPotassiumInt/1000
dailySodiumGramsInt = dailysSodiumInt/1000
dailyZincGramsInt = dailyZincInt/1000
dailyCopperGramsInt = dailyCopperInt/1000
dailyManganeseGramsInt = dailyManganeseInt/1000
dailySeleniumGramsInt = dailySeleniumInt/1000
dailyVitaminAGramsInt = dailyVitaminAInt/1000
dailyVitaminB6GramsInt = dailyVitaminB6Int/1000
dailyVitaminB12GramsInt = dailyVitaminB12Int/1000
dailyVitaminCGramsInt = dailyVitaminCInt/1000
dailyVitaminDGramsInt = dailyVitaminDInt/1000
dailyVitaminEGramsInt = dailyVitaminEInt/1000
dailyVitaminKGramsInt = dailyVitaminKInt/1000
dailyThiaminGramsInt = dailyThiaminInt/1000
dailyRiboflavinGramsInt = dailyRiboflavinInt/1000
dailyNiacinGramsInt = dailyNiacinInt/1000
dailyCholineGramsInt = dailyCholineInt/1000
dailyFolateGramsInt = dailyFolateInt/1000
if ageGroup == "teenager":
dailyVegetablesOuncesInt = dailyVegetablesInt*8
dailyFruitsOuncesInt = dailyFruitsInt*8
dailyDairyOuncesInt = dailyDairyInt*8
dailyCalciumGrams = str(dailyCalciumGramsInt)
dailyIronGrams = str(dailyIronGramsInt)
dailyMagneseumGrams = str(dailyMagneseumGramsInt)
dailyPhosphorusGrams = str(dailyPhosphorusGramsInt)
dailyPotassiumGrams = str(dailyPotassiumGramsInt)
dailySodiumGrams = str (dailySodiumGramsInt)
dailyZincGrams = str(dailyZincGramsInt)
dailyCopperGrams = str(dailyCopperGramsInt)
dailyManganeseGrams = str(dailyManganeseGramsInt)
dailySeleniumGrams = str(dailySeleniumGramsInt)
dailyVitaminAGrams = str(dailyVitaminAGramsInt)
dailyVitaminB6Grams = str(dailyVitaminB6GramsInt)
dailyVitaminB12Grams = str(dailyVitaminB12GramsInt)
dailyVitaminCGrams = str(dailyVitaminCGramsInt)
dailyVitaminDGrams = str(dailyVitaminDGramsInt)
dailyVitaminEGrams = str(dailyVitaminEGramsInt)
dailyVitaminKGrams = str(dailyVitaminKGramsInt)
dailyThiaminGrams = str(dailyThiaminGramsInt)
dailyRiboflavinGrams = str(dailyRiboflavinGramsInt)
dailyNiacinGrams = str(dailyNiacinGramsInt)
dailyCholineGrams = str(dailyCholineGramsInt)
dailyFolateGrams = str(dailyFolateGramsInt)
if ageGroup == "teenager":
dailyVegtablesOunces = str(dailyVegetablesOuncesInt)
dailyFruitsOunces = str(dailyFruitsOuncesInt)
dailyDairyOunces = str(dailyDairyOuncesInt)
print("You should be getting about " + dailyCalories + " calories per day.")
print("You should be getting about " + dailyProtein + " grams of protein per day.")
print("You should be getting about " + dailyCarbohydrate + " grams of carbohydrates per day.")
print("You should be getting about " + dailyDietaryFiber + " grams of dietary fiber per day.")
print("Between " + dailyTotalFatLower + "% and " + dailyTotalFatUpper + "% of your daily calories should come from total fat.")
print("No more than " + dailySaturatedFat + "% of your daily total fat should come from saturated fat.")
print(dailyLinoleicAcid + " grams per day is an adequate amount of linoleic acid.")
print(dailyLinolenicAcid + " grams per day is an adequate amount of linolenic acid.")
print("You should be getting about " + dailyCalcium + " milligrams (" + dailyCalciumGrams + " grams) of calcium per day.")
print("You should be getting about " + dailyIron + " milligrams (" + dailyIronGrams + " grams) of iron per day.")
print("You should be getting about " + dailyMagneseium + " milligrams (" + dailyMagneseumGrams + " grams) of magneseum per day.")
print("You should be getting about " + dailyPhosphorus + " milligrams (" + dailyPhosphorusGrams + " grams) of phosphorus per day.")
print(dailyPotassium + " milligrams (" + dailyPotassiumGrams + " grams per day is an adequate amount of potassium.")
print("You should be getting no more than " + dailySodium + " milligrams (" + dailySodiumGrams + " grams) of sodium per day.")
print("You should be getting about " + dailyZinc + " milligrams (" + dailyZincGrams + " grams) of zinc per day.")
print("You should be getting about " + dailyCopper + " milligrams (" + dailyCopperGrams + " grams) of copper per day.")
print(dailyManganese + " milligrams (" + dailyManganeseGrams + " grams) per day is an adequate amount of manganese.")
print("You should be getting about " + dailyVitaminA + " milligrams (" + dailyVitaminAGrams + " grams) of Vitamin A per day.")
print("You should be getting about " + dailyVitaminB6 + " milligrams (" + dailyVitaminB6Grams + " grams) of Vitamin B-6 per day.")
print("You should be getting about " + dailyVitaminB12 + " milligrams (" + dailyVitaminB12Grams + " grams) of Vitamin B-12 per day.")
print("You should be getting about " + dailyVitaminC + " milligrams (" + dailyVitaminCGrams + " grams) of Vitamin C per day.")
print("You should be getting about " + dailyVitaminD + " milligrams (" + dailyVitaminDGrams + " grams) of Vitamin D per day.")
print("You should be getting about " + dailyVitaminE + " milligrams (" + dailyVitaminEGrams + " grams) of Vitamin E per day.")
print(dailyVitaminK + " milligrams (" + dailyVitaminKGrams + " grams) per day is an adequate amount of Vitamin K.")
print("You should be getting about " + dailyThiamin + " milligrams (" + dailyThiaminGrams + " grams) of thiamin per day.")
print("You should be getting about " + dailyRiboflavin + " milligrams (" + dailyRiboflavinGrams + " grams) of riboflavin per day.")
print("You should be getting about " + dailyNiacin + " milligrams (" + dailyNiacinGrams + " grams) of niacin per day.")
print(dailyCholine + " milligrams (" + dailyCholineGrams + " grams) per day is an adequate amount of choline.")
print("You should be getting about " + dailyFolate + " milligrams (" + dailyFolateGrams + " grams) of folate per day.")
if ageGroup == "teenager":
print("You should be eating about " + dailyVegetables + " cups (" + dailyVegetablesOunces + " ounces) of vegetables per day.")
print("You should be eating about " + dailyFruits + " cups (" + dailyFruitsOunces + " ounces) of fruits each day.")
print("You should be eating about " + dailyDairy + " cups (" + dailyDairyOunces + " ounces) of dairy each day.")
I don't know what is wrong with Replit, but it isn't showing the entire error, only part of it. This is the part of the error that I can see:
Traceback (most recent call last):
4 <module>
f g u
N ' g u ' f
Not sure if the partial error helps.
Here is a working solution. But the code could be improved, see at the bottom there are some recommendations.
error001 = "\nError 001: Invalid Sex!"
error002 = "\nError 002: Invalid Age!"
error003 = "\nError 003: Invalid Activity Level!"
error004 = "\nError 004: Invalid Age Group!"
print("Hello! Welcome to Nutrition Info!")
sexInput = input(
"To get started, choose the sex of your character (gender, sexual orientation, etc. do not matter, as these do not matter for your physical health). Type 'M' for male or 'F' for female.")
if sexInput == "M":
sex = "male"
print("You have selected a male character.")
elif sexInput == "F":
sex = "female"
print("You have selected a female character.")
else:
quit(error001)
ageInput = input("How old is your character? Type just the number.")
if ageInput.isnumeric():
age = int(ageInput) # It should be casted after checking is numeric
if age in range(1, 3):
ageGroup = "toddler"
elif age in range(4, 8):
ageGroup = "young child"
elif age in range(9, 13):
ageGroup = "older child"
elif age in range(14, 18):
ageGroup = "teenager"
elif age in range(19, 30):
ageGroup = "young adult"
elif age in range(31, 50):
ageGroup = "older adult"
elif age in range(51, 130):
ageGroup = "senior"
else:
quit(error002)
else:
quit(error002)
print("You have selected a " + ageInput + f"-year-old character, which is {ageGroup}.")
if ageGroup == "toddler":
dailyCaloriesInt = 1000
dailyProteinInt = 13
dailyCarbohydrateInt = 130
dailyDietryFiberInt = 14
dailyTotalFatLowerInt = 30
dailyTotalFatUpperInt = 40
dailySaturatedFat = 10
dailyLinoleicAcidInt = 7
dailyLinolenicAcidInt = 0.7
dailyCalciumInt = 700
dailyIronInt = 7
dailyMagnesiumInt = 80
dailyPhosphorusInt = 260
dailyPotassiumInt = 3000
dailySodiumInt = 1500
dailyZincInt = 3
dailyCopperInt = 0.34
dailyManganeseInt = 1.2
dailySeleniumInt = 20
dailyVitaminAInt = 300
dailyVitaminB6Int = 0.5
dailyVitaminB12Int = 0.9
dailyVitaminCInt = 15
dailyVitaminDInt = 600
dailyVitaminEInt = 6
dailyVitaminKInt = 30
dailyThiaminInt = 0.5
dailyRiboflavinInt = 0.5
dailyNiacinInt = 6
dailyCholineInt = 200
dailyFolateInt = 150
elif ageGroup == "young child":
dailyProteinInt = 19
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyLinoleicAcidInt = 10
dailyLinolenicAcidInt = 0.9
dailyCalciumInt = 1000
dailyIronInt = 10
dailyMagnesiumInt = 130
dailyPhosphorusInt = 500
dailyPotassiumInt = 3800
dailySodiumInt = 1900
dailyZincInt = 5
dailyCopperInt = 0.44
dailyManganeseInt = 1.5
dailySeleniumInt = 30
dailyVitaminAInt = 400
dailyVitaminB6Int = 0.6
dailyVitaminB12Int = 1.2
dailyVitaminCInt = 25
dailyVitaminDInt = 600
dailyVitaminEInt = 7
dailyVitaminKInt = 55
dailyThiaminInt = 0.6
dailyRiboflavinInt = 0.6
dailyNiacinInt = 8
dailyCholineInt = 0.6
dailyFolateInt = 1.2
if sex == "female":
dailyCaloriesInt = 1200
dailyDietaryFiberInt = 16.8
else: # If it's not female, for sure will be "male", it was checked before
dailyDietaryFiberInt = 19.6
activityInputMaleYoungChild = input(
"How active is your character? Type '1' for inactive or '2' for active.")
if activityInputMaleYoungChild == "1":
activity = "inactive"
dailyCaloriesInt = 1400 # Not needed to add another if statement
elif activityInputMaleYoungChild == "2":
activity = "active"
dailyCaloriesInt = 1600 # Not needed to add another elif statement
else:
quit(error003)
elif ageGroup == "older child":
dailyProteinInt = 34
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1300
dailyIronInt = 8
dailyMagnesiumInt = 240
dailyPhosphorusInt = 1250
dailyPotassiumInt = 4500
dailySodiumInt = 2200
dailyZincInt = 8
dailyCopperInt = 0.7
dailySeleniumInt = 40
dailyVitaminAInt = 600
dailyVitaminB6Int = 1
dailyVitaminB12Int = 1.8
dailyVitaminCInt = 45
dailyVitaminDInt = 600
dailyVitaminEInt = 11
dailyVitaminKInt = 60
dailyThiaminInt = 0.9
dailyRiboflavinInt = 0.9
dailyNiacinInt = 12
dailyCholineInt = 375
dailyFolateInt = 300
if sex == "female":
dailyCaloriesInt = 1600
dailyDietaryFiberInt = 22.4
dailyLinoleicAcidInt = 10
dailyLinolenicAcidInt = 1
dailyManganeseInt = 1.6
else: # If it's not female, for sure will be "male", it was checked before
dailyCaloriesInt = 1800
dailyFietaryFiberInt = 25.2
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.2
dailyManganeseInt = 1.9
elif ageGroup == "teenager":
dailyCarbohydrateInt = 130
dailyTotalFatLowerInt = 25
dailyTotalFatUpperInt = 35
dailySaturatedFat = "10"
dailyCalciumInt = 1300
dailyPhosphorusInt = 1250
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.89
dailySeleniumInt = 55
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyDairyInt = 3
if sex == "female":
dailyCaloriesInt = 1800
dailyProteinInt = 46
dailyDietaryFiberInt = 25.2
dailyLinoleicAcidInt = 11
dailyLinolenicAcidInt = 1.1
dailyIronInt = 15
dailyMagnesiumInt = 360
dailyZincInt = 9
dailyManganeseInt = 1.6
dailyVitaminAInt = 700
dailyVitaminB6Int = 1.2
dailyVitaminCInt = 65
dailyThiaminInt = 1
dailyRiboflavinInt = 1
dailyNiacinInt = 14
dailyCholineInt = 400
activityInputFemaleTeenager = input(
"How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active, then press the 'ENTER' or 'RETURN' key.")
if activityInputFemaleTeenager == "1":
activity = "inactive"
elif activityInputFemaleTeenager == "2":
activity = "moderately active"
elif activityInputFemaleTeenager == "3":
activity = "active"
else:
quit(error003)
if activity == "inactive":
dailyCaloriesInt = 1800
dailyGrainsInt = 6
dailyVegetablesInt = 2.5
dailyFruitsInt = 1.5
elif activity == "moderately active":
dailyCaloriesInt = 2000
dailyGrainsInt = 6
dailyVegetablesInt = 2.5
dailyFruitsInt = 2
elif activity == "active":
dailyCaloriesInt = 2400
dailyGrainsInt = 8
dailyVegetablesInt = 3
dailyFruitsInt = 2
else:
quit(error003)
else: # If it's not female, for sure will be "male", it was checked before
dailyProteinInt = 52
dailyDietaryFiberInt = 30.8
dailyLinoleicAcidInt = 16
dailyLinolenicAcidInt = 1.6
dailyIronInt = 11
dailyMagnesiumInt = 410
dailyZincInt = 11
dailyManganeseInt = 2.2
dailyVitaminAInt = 900
dailyVitaminB6Int = 1.3
dailyVitaminCInt = 75
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 1.6
dailyCholineInt = 550
activityInputMaleTeenager = input(
"How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active, then press the 'ENTER' or 'RETURN' key.")
if activityInputMaleTeenager == "1":
activty = "inactive"
dailyCaloriesInt = 2200 # Not needed to add another if statement
dailyGrainsInt = 7
dailyVegetablesInt = 3
dailyFruitsInt = 2
elif activityInputMaleTeenager == "2":
activity = "moderately active"
dailyCaloriesInt = 2800 # Not needed to add another elif statement
dailyGrainsInt = 10
dailyVegetablesInt = 3.5
dailyFruitsInt = 2.5
elif activityInputMaleTeenager == "3":
activity = "active"
dailyCaloriesInt = 3200 # Not needed to add another elif statement
dailyGrainsInt = 10
dailyVegetablesInt = 4
dailyFruitsInt = 2.5
else:
quit(error003)
elif ageGroup == "young adult":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB6Int = 1.3
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 2000
dailyProteinInt = 46
dailyDietaryFiberInt = 28
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.1
dailyIronInt = 18
dailyMagneseumInt = 310
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
else: # If it's not female, for sure will be "male", it was checked before
dailyProteinInt = 56
dailyDietaryFiberInt = 33.6
dailyLinoleicAcidInt = 17
dailyLinolenicAcidInt = 1.6
dailyIronInt = 8
dailyMagneseumInt = 400
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
activityInputMaleYoungAdult = input(
"How active is your character? Type '1' for inactive, '2' for moderately active, or '3' for active.")
if activityInputMaleYoungAdult == "1":
activity = "inactive"
dailyCaloriesInt = 2400 # Not needed to add another if statement
elif activityInputMaleYoungAdult == "2":
activty = "moderately active"
dailyCaloriesInt = 2600 # Not needed to add another elif statement
elif activityInputMaleYoungAdult == "3":
activity = "active"
dailyCaloriesInt = 3000 # Not needed to add another elif statement
else:
quit(error003)
elif ageGroup == "older adult":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB6Int = 1.3
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 1800
dailyProteinInt = 46
dailyDietaryFiberInt = 25.2
dailyLinoleicAcidInt = 12
dailyLinolenicAcidInt = 1.1
dailyIronInt = 18
dailyMagneseumInt = 320
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
else: # If it's not female, for sure will be "male", it was checked before
dailyCaloriesInt = 2200
dailyProteinInt = 56
dailyDietaryFiberInt = 30.8
dailyLinoleicAcidInt = 17
dailyLinolenicAcidInt = 1.6
dailyIronInt = 8
dailyMagneseumInt = 420
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
elif ageGroup == "senior":
dailyCarbohydateInt = 130
dailyTotalFatLowerInt = 20
dailyTotalFatUpperInt = 35
dailySaturatedFat = 10
dailyCalciumInt = 1000
dailyIronInt = 8
dailyPhosphorusInt = 700
dailyPotassiumInt = 4700
dailySodiumInt = 2300
dailyCopperInt = 0.9
dailySeleniumInt = 55
dailyVitaminB12Int = 2.4
dailyVitaminDInt = 600
dailyVitaminEInt = 15
dailyFolateInt = 400
if sex == "female":
dailyCaloriesInt = 2000
dailyProteinInt = 46
dailyDietaryFiberInt = 22.4
dailyLinoleicAcidInt = 11
dailyLinolenicAcidInt = 1.1
dailyMagneseumInt = 310
dailyZincInt = 8
dailyManganeseInt = 1.8
dailyVitaminAInt = 700
dailyVitaminB6Int = 1.5
dailyVitaminCInt = 75
dailyVitaminKInt = 90
dailyThimainInt = 1.1
dailyRiboflavinInt = 1.1
dailyNiacinInt = 14
dailyCholineInt = 425
else: # If it's not female, for sure will be "male", it was checked before
dailyProteinInt = 56
dailyDietaryFiberInt = 28
dailyLinoleicAcidInt = 14
dailyLinolenicAcidInt = 1.6
dailyMagneseumInt = 400
dailyZincInt = 11
dailyManganeseInt = 2.3
dailyVitaminAInt = 900
dailyVitaminB6Int = 1.7
dailyVitaminCInt = 90
dailyVitaminKInt = 120
dailyThiaminInt = 1.2
dailyRiboflavinInt = 1.3
dailyNiacinInt = 16
dailyCholineInt = 550
else:
quit(error004)
try:
if activity == "inactive":
print("You have selected an inactive character.")
if activity == "moderately active":
print("You have selected a moderately active character.")
if activity == "active":
print("You have selected an active character.")
except NameError:
print("You have NOT selected any activity.") # Skipping "referenced before assignment" Traceback
dailyCalories = str(dailyCaloriesInt) if 'dailyCalories' in locals() else '?'
dailyProtein = str(dailyProteinInt) if 'dailyProteinInt' in locals() else '?'
dailyCarbohydrate = str(dailyCarbohydrateInt) if 'dailyCarbohydrateInt' in locals() else '?'
dailyDietaryFiber = str(dailyDietaryFiberInt) if 'dailyDietaryFiberInt' in locals() else '?'
dailyTotalFatLower = str(dailyTotalFatLowerInt) if 'dailyTotalFatLowerInt' in locals() else '?'
dailyTotalFatUpper = str(dailyTotalFatUpperInt) if 'dailyTotalFatUpperInt' in locals() else '?'
dailySaturatedFat = str(dailySaturatedFatInt) if 'dailySaturatedFatInt' in locals() else '?'
dailyLinoleicAcid = str(dailyLinoleicAcidInt) if 'dailyLinoleicAcidInt' in locals() else '?'
dailyLinolenicAcid = str(dailyLinolenicAcidInt) if 'dailyLinolenicAcidInt' in locals() else '?'
dailyCalcium = str(dailyCalciumInt) if 'dailyCalciumInt' in locals() else '?'
dailyIron = str(dailyIronInt) if 'dailyIronInt' in locals() else '?'
dailyMagneseum = str(dailyMagneseumInt) if 'dailyMagneseumInt' in locals() else '?'
dailyPhosphorus = str(dailyPhosphorusInt) if 'dailyPhosphorusInt' in locals() else '?'
dailyPotassium = str(dailyPotassiumInt) if 'dailyPotassiumInt' in locals() else '?'
dailySodium = str(dailySodiumInt) if 'dailySodiumInt' in locals() else '?'
dailyZinc = str(dailyZincInt) if 'dailyZincInt' in locals() else '?'
dailyCopper = str(dailyCopperInt) if 'dailyCopperInt' in locals() else '?'
dailyManganese = str(dailyManganeseInt) if 'dailyManganeseInt' in locals() else '?'
dailySelenium = str(dailySeleniumInt) if 'dailySeleniumInt' in locals() else '?'
dailyVitaminA = str(dailyVitaminAInt) if 'dailyVitaminAInt' in locals() else '?'
dailyVitaminB6 = str(dailyVitaminB6Int) if 'dailyVitaminB6Int' in locals() else '?'
dailyVitaminB12 = str(dailyVitaminB12Int) if 'dailyVitaminB12Int' in locals() else '?'
dailyVitaminC = str(dailyVitaminCInt) if 'dailyVitaminCInt' in locals() else '?'
dailyVitaminD = str(dailyVitaminDInt) if 'dailyVitaminDInt' in locals() else '?'
dailyVitaminE = str(dailyVitaminEInt) if 'dailyVitaminEInt' in locals() else '?'
dailyVitaminK = str(dailyVitaminKInt) if 'dailyVitaminKInt' in locals() else '?'
dailyThiamin = str(dailyThiaminInt) if 'dailyThiaminInt' in locals() else '?'
dailyRiboflavin = str(dailyRiboflavinInt) if 'dailyRiboflavinInt' in locals() else '?'
dailyNiacin = str(dailyNiacinInt) if 'dailyNiacinInt' in locals() else '?'
dailyCholine = str(dailyCholineInt) if 'dailyCholineInt' in locals() else '?'
dailyFolate = str(dailyFolateInt) if 'dailyFolateInt' in locals() else '?'
if ageGroup == "teenager":
dailyVegetables = str(dailyVegetablesInt) if 'dailyVegetablesInt' in locals() else '?'
dailyFruits = str(dailyFruitsInt) if 'dailyFruitsInt' in locals() else '?'
dailyDairy = str(dailyDairyInt) if 'dailyDairyInt' in locals() else '?'
dailyCalciumGrams = str(dailyCalciumInt / 1000) if 'dailyCalciumInt' in locals() else '?'
dailyIronGrams = str(dailyIronInt / 1000) if 'dailyIronInt' in locals() else '?'
dailyMagneseumGrams = str(dailyMagneseumInt / 1000) if 'dailyMagneseumInt' in locals() else '?'
dailyPhosphorusGrams = str(dailyPhosphorusInt / 1000) if 'dailyPhosphorusInt' in locals() else '?'
dailyPotassiumGrams = str(dailyPotassiumInt / 1000) if 'dailyPotassiumInt' in locals() else '?'
dailySodiumGrams = str(dailysSodiumInt / 1000) if 'dailysSodiumInt' in locals() else '?'
dailyZincGrams = str(dailyZincInt / 1000) if 'dailyZincInt' in locals() else '?'
dailyCopperGrams = str(dailyCopperInt / 1000) if 'dailyCopperInt' in locals() else '?'
dailyManganeseGrams = str(dailyManganeseInt / 1000) if 'dailyManganeseInt' in locals() else '?'
dailySeleniumGrams = str(dailySeleniumInt / 1000) if 'dailySeleniumInt' in locals() else '?'
dailyVitaminAGrams = str(dailyVitaminAInt / 1000) if 'dailyVitaminAInt' in locals() else '?'
dailyVitaminB6Grams = str(dailyVitaminB6Int / 1000) if 'dailyVitaminB6Int' in locals() else '?'
dailyVitaminB12Grams = str(dailyVitaminB12Int / 1000) if 'dailyVitaminB12Int' in locals() else '?'
dailyVitaminCGrams = str(dailyVitaminCInt / 1000) if 'dailyVitaminCInt' in locals() else '?'
dailyVitaminDGrams = str(dailyVitaminDInt / 1000) if 'dailyVitaminDInt' in locals() else '?'
dailyVitaminEGrams = str(dailyVitaminEInt / 1000) if 'dailyVitaminEInt' in locals() else '?'
dailyVitaminKGrams = str(dailyVitaminKInt / 1000) if 'dailyVitaminKInt' in locals() else '?'
dailyThiaminGrams = str(dailyThiaminInt / 1000) if 'dailyThiaminInt' in locals() else '?'
dailyRiboflavinGrams = str(dailyRiboflavinInt / 1000) if 'dailyRiboflavinInt' in locals() else '?'
dailyNiacinGrams = str(dailyNiacinInt / 1000) if 'dailyNiacinInt' in locals() else '?'
dailyCholineGrams = str(dailyCholineInt / 1000) if 'dailyCholineInt' in locals() else '?'
dailyFolateGrams = str(dailyFolateInt / 1000) if 'dailyFolateInt' in locals() else '?'
if ageGroup == "teenager":
dailyVegetablesOunces = str(dailyVegetablesInt * 8) if 'dailyVegetablesInt' in locals() else '?'
dailyFruitsOunces = str(dailyFruitsInt * 8) if 'dailyFruitsInt' in locals() else '?'
dailyDairyOunces = str(dailyDairyInt * 8) if 'dailyDairyInt' in locals() else '?'
print("You should be getting about " + dailyCalories + " calories per day.")
print("You should be getting about " + dailyProtein + " grams of protein per day.")
print("You should be getting about " + dailyCarbohydrate + " grams of carbohydrates per day.")
print("You should be getting about " + dailyDietaryFiber + " grams of dietary fiber per day.")
print(
"Between " + dailyTotalFatLower + "% and " + dailyTotalFatUpper + "% of your daily calories should come from total fat.")
print("No more than " + dailySaturatedFat + "% of your daily total fat should come from saturated fat.")
print(dailyLinoleicAcid + " grams per day is an adequate amount of linoleic acid.")
print(dailyLinolenicAcid + " grams per day is an adequate amount of linolenic acid.")
print(
"You should be getting about " + dailyCalcium + " milligrams (" + dailyCalciumGrams + " grams) of calcium per day.")
print("You should be getting about " + dailyIron + " milligrams (" + dailyIronGrams + " grams) of iron per day.")
# This is not defined!
# print(
# "You should be getting about " + dailyMagneseium + " milligrams (" + dailyMagneseumGrams + " grams) of magneseum per day.")
print(
"You should be getting about " + dailyPhosphorus + " milligrams (" + dailyPhosphorusGrams + " grams) of phosphorus per day.")
print(dailyPotassium + " milligrams (" + dailyPotassiumGrams + " grams per day is an adequate amount of potassium.")
print(
"You should be getting no more than " + dailySodium + " milligrams (" + dailySodiumGrams + " grams) of sodium per day.")
print("You should be getting about " + dailyZinc + " milligrams (" + dailyZincGrams + " grams) of zinc per day.")
print(
"You should be getting about " + dailyCopper + " milligrams (" + dailyCopperGrams + " grams) of copper per day.")
print(
dailyManganese + " milligrams (" + dailyManganeseGrams + " grams) per day is an adequate amount of manganese.")
print(
"You should be getting about " + dailyVitaminA + " milligrams (" + dailyVitaminAGrams + " grams) of Vitamin A per day.")
print(
"You should be getting about " + dailyVitaminB6 + " milligrams (" + dailyVitaminB6Grams + " grams) of Vitamin B-6 per day.")
print(
"You should be getting about " + dailyVitaminB12 + " milligrams (" + dailyVitaminB12Grams + " grams) of Vitamin B-12 per day.")
print(
"You should be getting about " + dailyVitaminC + " milligrams (" + dailyVitaminCGrams + " grams) of Vitamin C per day.")
print(
"You should be getting about " + dailyVitaminD + " milligrams (" + dailyVitaminDGrams + " grams) of Vitamin D per day.")
print(
"You should be getting about " + dailyVitaminE + " milligrams (" + dailyVitaminEGrams + " grams) of Vitamin E per day.")
print(dailyVitaminK + " milligrams (" + dailyVitaminKGrams + " grams) per day is an adequate amount of Vitamin K.")
print(
"You should be getting about " + dailyThiamin + " milligrams (" + dailyThiaminGrams + " grams) of thiamin per day.")
print(
"You should be getting about " + dailyRiboflavin + " milligrams (" + dailyRiboflavinGrams + " grams) of riboflavin per day.")
print(
"You should be getting about " + dailyNiacin + " milligrams (" + dailyNiacinGrams + " grams) of niacin per day.")
print(dailyCholine + " milligrams (" + dailyCholineGrams + " grams) per day is an adequate amount of choline.")
print(
"You should be getting about " + dailyFolate + " milligrams (" + dailyFolateGrams + " grams) of folate per day.")
if ageGroup == "teenager":
print(
"You should be eating about " + dailyVegetables + " cups (" + dailyVegetablesOunces + " ounces) of vegetables per day.")
print(
"You should be eating about " + dailyFruits + " cups (" + dailyFruitsOunces + " ounces) of fruits each day.")
print("You should be eating about " + dailyDairy + " cups (" + dailyDairyOunces + " ounces) of dairy each day.")
Recommendations:
Use functions, this is too long.
In your future new implementation avoid using "locals()", it's a dirty shortcut just to make it work in the way you had the code
Use classes with attributes or something to keep the different multiple options you have. A simple example:
class Errors(str):
Sex = "Error 001: Invalid Sex!"
Age = "Error 002: Invalid Age!"
Activity = "Error 003: Invalid Activity Level!"
Group = "Error 004: Invalid Age Group!"
# Use it like this:
quit(Errors.Sex)
Avoid statements doing the same
Don't check something more than once
Catch exceptions with try-except
Take care with variables referenced before assign them. I used locals() as shortcut, avoid that. Another option could be to initialize all the variables.
Clean the code and save data somehow out of the main function
Related
How to deal with indexes length while reusing existing data frames with columns name?
I am using a for loop to reuse existing data frames. Sample Code: for i in range(0, 5, 1): RGU_TT_TempX = pd.DataFrame() RGU_TT_TempX = RGU_TT_Temp #Merging Regular Ambulance TT with MSUs TT #Updating MSUs TT according to the Formula RGU_TT_TempX["MSU_X_DURATION"] = 0.05 + df_temp_MSU1["MSU_X_DURATION"].values + 0.25 + 0.25 RGU_TT_TempX["MSU_Y_DURATION"] = 0.05 + df_temp_MSU2["MSU_Y_DURATION"].values + 0.25 + 0.25 RGU_TT_TempX["MSU_Z_DURATION"] = 0.05 + df_temp_MSU3["MSU_Z_DURATION"].values + 0.25 + 0.25 This gives me the error: ---> 44 RGU_TT_TempX["MSU_X_DURATION"] = 0.05 + df_temp_MSU1["MSU_X_DURATION"].values + 0.25 + 0.25 ValueError: Length of values (0) does not match length of index (16622) In each data frame, I have 16622 values. Still, this gives me the length of the index error. Data Frame (MSU_TT_Temp) Samples: FROM_ID TO_ID DURATION_H DIST_KM 1 7 0.528556 38.43980 1 26 0.512511 37.38515 1 71 0.432453 32.57571 1 83 0.599486 39.26188 1 98 0.590517 35.53107 Data Frame (RGU_TT_Temp) Samples: Ambulance_ID Centroid_ID Hospital_ID Regular_Ambu_TT 37 1 6 1.871885 39 2 13 1.599971 6 3 6 1.307165 42 4 12 1.411554 37 5 14 1.968138 The problem is, if I iterate my loop once, the code works absolutely fine. Sample Code: for i in range(0, 1, 1): s = my_chrome_list[i] MSU_X,MSU_Y,MSU_Z = s #print (MSU_X,MSU_Y,MSU_Z) #Three scenario df_temp_MSU1 = pd.DataFrame() df_temp_MSU2 = pd.DataFrame() df_temp_MSU3 = pd.DataFrame() df_temp_MSU1 = MSU_TT_Temp.loc[(MSU_TT_Temp['FROM_ID'] == MSU_X)] df_temp_MSU1.rename(columns = {'DURATION_H':'MSU_X_DURATION'}, inplace = True) #df_temp_MSU1 df_temp_MSU2 = MSU_TT_Temp.loc[(MSU_TT_Temp['FROM_ID'] == MSU_Y)] df_temp_MSU2.rename(columns = {'DURATION_H':'MSU_Y_DURATION'}, inplace = True) #df_temp_MSU2 df_temp_MSU3 = MSU_TT_Temp.loc[(MSU_TT_Temp['FROM_ID'] == MSU_Z)] df_temp_MSU3.rename(columns = {'DURATION_H':'MSU_Z_DURATION'}, inplace = True) #df_temp_MSU3 RGU_TT_TempX = pd.DataFrame() RGU_TT_TempX = RGU_TT_Temp #Merging Regular Ambulance TT with MSUs TT #Updating MSUs TT according to the Formula RGU_TT_TempX["MSU_X_DURATION"] = 0.05 + df_temp_MSU1["MSU_X_DURATION"].values + 0.25 + 0.25 RGU_TT_TempX["MSU_Y_DURATION"] = 0.05 + df_temp_MSU2["MSU_Y_DURATION"].values + 0.25 + 0.25 RGU_TT_TempX["MSU_Z_DURATION"] = 0.05 + df_temp_MSU3["MSU_Z_DURATION"].values + 0.25 + 0.25 #RGU_TT_TempX #MSUs Average Time to Treatment MSU1=RGU_TT_TempX["MSU_X_DURATION"].mean() MSU2=RGU_TT_TempX["MSU_Y_DURATION"].mean() MSU3=RGU_TT_TempX["MSU_Z_DURATION"].mean() MSU_AVG_TT = (MSU1+MSU2+MSU3)/3 parents_chromosomes_list.append(MSU_AVG_TT) Output: After 1 iteration - Data Frame (RGU_TT_Temp): Ambulance_ID Centroid_ID Hospital_ID Regular_Ambu_TT MSU_X_DURATION MSU_Y_DURATION MSU_Z_DURATION 37 1 6 1.871885 2.091039 1.359664 2.037758 39 2 13 1.599971 1.950039 1.343619 1.948425 6 3 6 1.307165 2.026553 1.263561 2.024942 42 4 12 1.411554 1.854397 1.430594 1.852783 37 5 14 1.968138 2.255394 1.421625 2.298842 Output: [2.0241383927258387] Note: The data length in the three data frames are equal: Indexes are the same length Loop for multiple iteration:Erorr for i in range(0, 5, 1): Full Error Track: ValueError Traceback (most recent call last) Input In [21], in <cell line: 16>() 41 RGU_TT_TempX = RGU_TT_Temp 42 #Merging Regular Ambulance TT with MSUs TT 43 #Updating MSUs TT according to the Formula ---> 44 RGU_TT_TempX["MSU_X_DURATION"] = 0.05 + df_temp_MSU1["MSU_X_DURATION"].values + 0.25 + 0.25 45 RGU_TT_TempX["MSU_Y_DURATION"] = 0.05 + df_temp_MSU2["MSU_Y_DURATION"].values + 0.25 + 0.25 46 RGU_TT_TempX["MSU_Z_DURATION"] = 0.05 + df_temp_MSU3["MSU_Z_DURATION"].values + 0.25 + 0.25 File ~/opt/anaconda3/envs/geo_env/lib/python3.10/site-packages/pandas/core/frame.py:3977, in DataFrame.__setitem__(self, key, value) 3974 self._setitem_array([key], value) 3975 else: 3976 # set column -> 3977 self._set_item(key, value) File ~/opt/anaconda3/envs/geo_env/lib/python3.10/site-packages/pandas/core/frame.py:4171, in DataFrame._set_item(self, key, value) 4161 def _set_item(self, key, value) -> None: 4162 """ 4163 Add series to DataFrame in specified column. 4164 (...) 4169 ensure homogeneity. 4170 """ -> 4171 value = self._sanitize_column(value) 4173 if ( 4174 key in self.columns 4175 and value.ndim == 1 4176 and not is_extension_array_dtype(value) 4177 ): 4178 # broadcast across multiple columns if necessary 4179 if not self.columns.is_unique or isinstance(self.columns, MultiIndex): File ~/opt/anaconda3/envs/geo_env/lib/python3.10/site-packages/pandas/core/frame.py:4904, in DataFrame._sanitize_column(self, value) 4901 return _reindex_for_setitem(Series(value), self.index) 4903 if is_list_like(value): -> 4904 com.require_length_match(value, self.index) 4905 return sanitize_array(value, self.index, copy=True, allow_2d=True) File ~/opt/anaconda3/envs/geo_env/lib/python3.10/site-packages/pandas/core/common.py:561, in require_length_match(data, index) 557 """ 558 Check the length of data matches the length of the index. 559 """ 560 if len(data) != len(index): --> 561 raise ValueError( 562 "Length of values " 563 f"({len(data)}) " 564 "does not match length of index " 565 f"({len(index)})" 566 ) ValueError: Length of values (0) does not match length of index (16622) I am stuck here. What is the problem?
Grabbing a value from a dataframe based on random variables created
I have a dataframe with a specific value called rate_multiplier that I need to grab and compare it to the rate_multiplier I get from AWS s3 bucket. In order to grab the rate_multiplier in the dataframe, I need to take the random variables that I created for a "person" and match them to the dataframe which gives a specific rate_mulitplier based on these certain characteristics For example: Random variables created: Life_term = 25 Gender = F Rate_class = Best-AB Age = 27 Coverage = 2310 Dataframe: Life_term Benefit_Length_months Gender Rate_class Age State Coverage band (low end) Coverage band (high end) Coverage Band Rate_multiplier 0 15 180 M Best-AA 18 Default 500 1199 500-1199 2.31 1 15 180 M Best-AA 19 Default 500 1199 500-1199 2.21 2 15 180 M Best-AA 20 Default 500 1199 500-1199 2.11 3 15 180 M Best-AA 21 Default 500 1199 500-1199 2.03 4 15 180 M Best-AA 22 Default 500 1199 500-1199 1.95 ... ... ... ... ... ... ... ... ... ... ... 34987 10 120 F Nicotine Average-CD 61 Default 3600 10000 3600+ 19.10 34988 10 120 F Nicotine Average-CD 62 Default 3600 10000 3600+ 21.27 34989 10 120 F Nicotine Average-CD 63 Default 3600 10000 3600+ 23.44 34990 10 120 F Nicotine Average-CD 64 Default 3600 10000 3600+ 25.61 34991 10 120 F Nicotine Average-CD 65 Default 3600 10000 3600+ 27.78 So for this example, my randomly generated person would get a rate_multiplier of: 0.93 My code is as follows: rate_mult_df.loc[(rate_mult_df['Life_term'] == 15) & (rate_mult_df['Gender'] == 'F') & (rate_mult_df['Rate_class'] == 'Best-AB') & (rate_mult_df['Age'] == 27) & (rate_mult_df['Coverage band (low end)'] <= 2310) & (rate_mult_df['Coverage band (high end)'] >= 2310)] Is the right way to grab the rate_muliplier for the randomly genreated person or is there any easier way? Any and all help is appreciated. Please let me know if my question is clear enough. Working on that everyday.
For perfomance reasons I'd use .query() rate_multiplier = df.query( "Life_term == 15 &" " Gender == 'F' &" " Rate_class == 'Best-AB' &" " Age == 27 &" " `Coverage band (low end)` == 2310 &" " `Coverage band (high end)` == 2310" )["Rate_multiplier"].squeeze() "Easier" depends on your workflow. For example if you want to query from a dictionary you could use: def get_rate_multiplier(search_params: dict) -> str: return " and ".join( [f"({k} == '{v}')" if type(v) == str else f"({k} == {v})" for k, v in search_params.items()] ) random_person = { "Life_term": 15, "Gender": "F", "Rate_class": "Best-AB", "Age": 27, "Coverage band (low end)": 2310, "Coverage band (high end)": 2310 } rate_multiplier = float(df.query(get_rate_multiplier(random_person))["Rate_multiplier"].squeeze())
numpy - anyway to improve this further(PandasTook(1h26m), NumpyTakes(38m))
Initially had everything written pandas and for this exploratory exercise i had did a lot of groupby's and while running with the whole data it was ran for 1h 26m. Over the last weekend, i had changed everything from pandas to using numpy, currently it took(Wall time: 38min 27s). I would like to know if it can be further improved While converting to numpy, i had additionally used numpy_indexed. Overall what i am doing is calling the below function this loop(i have read in lots of places loops are bad). Dataset has around 657058 rows and there around 5000 tickers. for idx, ticker in enumerate(ticker_list): ... df_temp = weekly_trend_analysis(exchange, df_weekly, df_daily) ... df_weekly_all = pd.concat([df_weekly_all, df_temp], sort=False) def weekly_trend_analysis(exchange, df_weekly_all, df_daily): if exchange == 'BSE': ticker = df_daily.iloc[0]['sc_code'] else: ticker = df_daily.iloc[0]['symbol'] arr_yearWeek = df_daily['yearWeek'].to_numpy() arr_close = df_daily['close'].to_numpy() arr_prevclose = df_daily['prevclose'].to_numpy() arr_chng = df_daily['chng'].to_numpy() arr_chngp = df_daily['chngp'].to_numpy() arr_ts = df_daily['ts'].to_numpy() arr_volumes = df_daily['volumes'].to_numpy() # Close arr_concat = np.column_stack((arr_yearWeek, arr_close)) npi_gb = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) #a = df_temp[['yearWeek', 'close']].to_numpy() yearWeek, daysTraded = np.unique(arr_concat[:,0], return_counts=True) cmaxs, cmins = [], [] first, last, wChng, wChngp = [], [], [], [] for idx,subarr in enumerate(npi_gb): cmaxs.append( np.amax(subarr) ) cmins.append( np.amin(subarr) ) first.append(subarr[0]) last.append(subarr[-1]) wChng.append( subarr[-1] - subarr[0] ) wChngp.append( ( (subarr[-1] / subarr[0]) * 100) - 100 ) #npi_gb.clear() arr_concat = np.empty((100,100)) # Chng arr_concat = np.column_stack((arr_yearWeek, arr_chng)) npi_gb = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) HSDL, HSDG = [], [] for idx,subarr in enumerate(npi_gb): HSDL.append( np.amin(subarr) ) HSDG.append( np.amax(subarr) ) #npi_gb.clear() arr_concat = np.empty((100,100)) # Chngp arr_concat = np.column_stack((arr_yearWeek, arr_chngp)) npi_gb = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) HSDLp, HSDGp = [], [] for idx,subarr in enumerate(npi_gb): HSDLp.append( np.amin(subarr) ) HSDGp.append( np.amax(subarr) ) #npi_gb.clear() arr_concat = np.empty((100,100)) # Last Traded Date of the Week i = df_daily[['yearWeek', 'ts']].to_numpy() j = npi.group_by(i[:, 0]).split(i[:, 1]) lastTrdDoW = [] for idx,subarr in enumerate(j): lastTrdDoW.append( subarr[-1] ) i = np.empty((100,100)) #j.clear() # Times inreased TI = np.where(arr_close > arr_prevclose, 1, 0) # Below npi_gb_yearWeekTI is used in volumes section arr_concat = np.column_stack((arr_yearWeek, TI)) npi_gb_yearWeekTI = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) tempArr, TI = npi.group_by(arr_yearWeek).sum(TI) # Volume ( dependent on above section value t_group , thats the reason to move from top to here) arr_concat = np.column_stack((arr_yearWeek, arr_volumes)) npi_gb = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) vmaxs, vavgs, volAvgWOhv, HVdAV, CPveoHVD, lastDVotWk, lastDVdAV = [], [], [], [], [], [], [] for idx,subarr in enumerate(npi_gb): vavgs.append( np.mean(subarr) ) ldvotWk = subarr[-1] lastDVotWk.append(ldvotWk) #print(idx, 'O - ',subarr, np.argmax(subarr), ', average : ',np.mean(subarr)) ixDel = np.argmax(subarr) hV = subarr[ixDel] vmaxs.append( hV ) if(len(subarr)>1): subarr = np.delete(subarr, ixDel) vawoHV = np.mean(subarr) else: vawoHV = np.mean(subarr) volAvgWOhv.append( vawoHV ) HVdAV.append(hV / vawoHV) CPveoHVD.append( npi_gb_yearWeekTI[idx][ixDel] ) lastDVdAV.append(ldvotWk / vawoHV) #npi_gb.clear() arr_concat = np.empty((100,100)) # Preparing the dataframe # yearWeek and occurances #yearWeek, daysTraded = np.unique(a[:,0], return_counts=True) yearWeek = yearWeek.astype(int) HSDL = np.round(HSDL,2) HSDG = np.round(HSDG,2) HSDLp = np.round(HSDLp,2) HSDGp = np.round(HSDGp,2) first = np.round(first,2) last = np.round(last,2) wChng = np.round(wChng,2) wChngp = np.round(wChngp,2) vavgs = np.array(vavgs).astype(int) volAvgWOhv = np.array(volAvgWOhv).astype(int) HVdAV = np.round(HVdAV,2) dict_temp = {'yearWeek': yearWeek, 'closeH': cmaxs, 'closeL': cmins, 'volHigh':vmaxs, 'volAvg':vavgs, 'daysTraded':daysTraded ,'HSDL':HSDL, 'HSDG':HSDG, 'HSDLp':HSDLp, 'HSDGp':HSDGp, 'first':first, 'last':last, 'wChng':wChng, 'wChngp':wChngp ,'lastTrdDoW':lastTrdDoW, 'TI':TI, 'volAvgWOhv':volAvgWOhv, 'HVdAV':HVdAV, 'CPveoHVD':CPveoHVD ,'lastDVotWk':lastDVotWk, 'lastDVdAV':lastDVdAV} df_weekly = pd.DataFrame(data=dict_temp) df_weekly['sc_code'] = ticker cols = ['sc_code', 'yearWeek', 'lastTrdDoW', 'daysTraded', 'closeL', 'closeH', 'volAvg', 'volHigh' , 'HSDL', 'HSDG', 'HSDLp', 'HSDGp', 'first', 'last', 'wChng', 'wChngp', 'TI', 'volAvgWOhv', 'HVdAV' , 'CPveoHVD', 'lastDVotWk', 'lastDVdAV'] df_weekly = df_weekly[cols].copy() # df_weekly_all will be 0, when its a new company or its a FTA(First Time Analysis) if df_weekly_all.shape[0] == 0: df_weekly_all = pd.DataFrame(columns=list(df_weekly.columns)) # Removing all yearWeek in df_weekly2 from df_weekly a = set(df_weekly_all['yearWeek']) b = set(df_weekly['yearWeek']) c = list(a.difference(b)) #print('df_weekly_all={}, df_weekly={}, difference={}'.format(len(a), len(b), len(c)) ) df_weekly_all = df_weekly_all[df_weekly_all.yearWeek.isin(c)].copy() # Append the latest week data to df_weekly df_weekly_all = pd.concat([df_weekly_all, df_weekly], sort=False) #print('After concat : df_weekly_all={}'.format(df_weekly_all.shape[0])) return df_weekly_all Input data ts = ['2019-04-01 00:00:00','2019-04-01 00:00:00','2019-04-01 00:00:00','2019-04-01 00:00:00','2019-04-01 00:00:00','2019-04-02 00:00:00','2019-04-02 00:00:00','2019-04-02 00:00:00','2019-04-02 00:00:00','2019-04-02 00:00:00'] sc_code = ['500002','500002','500002','500002','500002','500002','500002','500002','500002','500002'] high = [1326.6, 208.45, 732.15, 14.87, 1979.0, 57.8, 11.55, 1.68, 8.1, 139.4] low = [1306.35, 204.0, 717.05, 13.41, 1937.65, 54.65, 11.2, 1.52, 7.75, 135.65] close = [1313.55, 206.65, 723.05, 13.53, 1955.25, 56.0, 11.21, 1.68, 8.1, 136.85] prevclose = [1319.85, 202.95, 718.95, 14.29, 1967.3, 54.65, 11.22, 1.6, 7.75, 135.05] volumes = [7785, 6150, 21641, 46296, 707019, 40089, 25300, 5920, 500, 235355] yearWeek = [201913, 201913, 201913, 201913, 201913, 201913, 201913, 201913, 201913, 201913] chng = [-6.29, 3.70, 4.09, -0.75, -12.04, 1.35, -0.09, 0.079, 0.34, 1.79] chngp = [-0.48, 1.82, 0.57, -5.32, -0.61, 2.47, -0.09, 5.0, 4.52, 1.33] dict_temp = {'ts':ts, 'sc_code':sc_code, 'high':high, 'low':low, 'close':close, 'prevclose':prevclose, 'volumes':volumes, 'yearWeek':yearWeek, 'chng':chng, 'chngp':chngp} df_weekly = pd.DataFrame(data=dict_temp) Adding line-profiler details, ('getcwd : ', '/home/bobby_dreamer') Timer unit: 1e-06 s Total time: 0.043637 s File: BTD-Analysis1V3.py Function: weekly_trend_analysis at line 36 Line # Hits Time Per Hit % Time Line Contents ============================================================== 36 def weekly_trend_analysis(exchange, df_weekly_all, df_daily): 37 38 1 3.0 3.0 0.0 if exchange == 'BSE': 39 1 963.0 963.0 2.2 ticker = df_daily.iloc[0]['sc_code'] 40 else: 41 ticker = df_daily.iloc[0]['symbol'] 42 95 # Last Traded Date of the Week 96 1 3111.0 3111.0 7.1 i = df_daily[['yearWeek', 'ts']].to_numpy() 97 1 128.0 128.0 0.3 j = npi.group_by(i[:, 0]).split(i[:, 1]) 98 160 161 1 3.0 3.0 0.0 dict_temp = {'yearWeek': yearWeek, 'closeH': cmaxs, 'closeL': cmins, 'volHigh':vmaxs, 'volAvg':vavgs, 'daysTraded':daysTraded 162 1 2.0 2.0 0.0 ,'HSDL':HSDL, 'HSDG':HSDG, 'HSDLp':HSDLp, 'HSDGp':HSDGp, 'first':first, 'last':last, 'wChng':wChng, 'wChngp':wChngp 163 1 2.0 2.0 0.0 ,'lastTrdDoW':lastTrdDoW, 'TI':TI, 'volAvgWOhv':volAvgWOhv, 'HVdAV':HVdAV, 'CPveoHVD':CPveoHVD 164 1 2.0 2.0 0.0 ,'lastDVotWk':lastDVotWk, 'lastDVdAV':lastDVdAV} 165 1 3677.0 3677.0 8.4 df_weekly = pd.DataFrame(data=dict_temp) 166 167 1 1102.0 1102.0 2.5 df_weekly['sc_code'] = ticker 168 169 1 3.0 3.0 0.0 cols = ['sc_code', 'yearWeek', 'lastTrdDoW', 'daysTraded', 'closeL', 'closeH', 'volAvg', 'volHigh' 170 1 1.0 1.0 0.0 , 'HSDL', 'HSDG', 'HSDLp', 'HSDGp', 'first', 'last', 'wChng', 'wChngp', 'TI', 'volAvgWOhv', 'HVdAV' 171 1 2.0 2.0 0.0 , 'CPveoHVD', 'lastDVotWk', 'lastDVdAV'] 172 173 1 2816.0 2816.0 6.5 df_weekly = df_weekly[cols].copy() 174 175 # df_weekly_all will be 0, when its a new company or its a FTA(First Time Analysis) 176 1 13.0 13.0 0.0 if df_weekly_all.shape[0] == 0: 177 1 20473.0 20473.0 46.9 df_weekly_all = pd.DataFrame(columns=list(df_weekly.columns)) 178 179 # Removing all yearWeek in df_weekly2 from df_weekly 180 1 321.0 321.0 0.7 a = set(df_weekly_all['yearWeek']) 181 1 190.0 190.0 0.4 b = set(df_weekly['yearWeek']) 182 1 5.0 5.0 0.0 c = list(a.difference(b)) 183 #print('df_weekly_all={}, df_weekly={}, difference={}'.format(len(a), len(b), len(c)) ) 184 1 1538.0 1538.0 3.5 df_weekly_all = df_weekly_all[df_weekly_all.yearWeek.isin(c)].copy() 185 186 # Append the latest week data to df_weekly 187 1 6998.0 6998.0 16.0 df_weekly_all = pd.concat([df_weekly_all, df_weekly], sort=False) 188 #print('After concat : df_weekly_all={}'.format(df_weekly_all.shape[0])) 189 190 1 2.0 2.0 0.0 return df_weekly_all After reviewing the above profile, made changes to code which consumed more time, basically added more numpy code removed pandas in the function. Below code when run with whole data took only Wall time: 7min 47s. Encountered some numpy errors like below, handled via writing intermediate files. I am using windows machine and intermediate files were < 3MB. Not sure if there were any limitations. MemoryError: Unable to allocate array with shape (82912, 22) and data type <U32 Line # Hits Time Per Hit % Time Line Contents ============================================================== 38 def weekly_trend_analysis_np(exchange, np_weekly_all, df_daily): 39 40 1 4.0 4.0 0.0 if exchange == 'BSE': 43 1 152.0 152.0 1.2 ticker = df_daily['sc_code'].to_numpy()[0] 44 else: 47 ticker = df_daily['symbol'].to_numpy()[0] 48 101 # Last Traded Date of the Week 102 1 33.0 33.0 0.3 arr_concat = np.column_stack((arr_yearWeek, arr_ts)) 103 1 341.0 341.0 2.6 npi_gb = npi.group_by(arr_concat[:, 0]).split(arr_concat[:, 1]) 104 152 1 5.0 5.0 0.0 yearWeek = yearWeek.astype(int) 153 1 59.0 59.0 0.5 HSDL = np.round(HSDL,2) 154 1 26.0 26.0 0.2 HSDG = np.round(HSDG,2) 155 1 23.0 23.0 0.2 HSDLp = np.round(HSDLp,2) 156 1 23.0 23.0 0.2 HSDGp = np.round(HSDGp,2) 157 158 1 23.0 23.0 0.2 first = np.round(first,2) 159 1 23.0 23.0 0.2 last = np.round(last,2) 160 1 23.0 23.0 0.2 wChng = np.round(wChng,2) 161 1 23.0 23.0 0.2 wChngp = np.round(wChngp,2) 162 163 1 12.0 12.0 0.1 vavgs = np.array(vavgs).astype(int) 164 1 16.0 16.0 0.1 volAvgWOhv = np.array(volAvgWOhv).astype(int) 165 1 24.0 24.0 0.2 HVdAV = np.round(HVdAV,2) 166 167 1 16.0 16.0 0.1 ticker = np.full(yearWeek.shape[0], ticker) 168 1 2.0 2.0 0.0 np_weekly = np.column_stack((ticker, yearWeek, lastTrdDoW, daysTraded, cmins, cmaxs, vavgs, vmaxs, HSDL 169 1 2.0 2.0 0.0 , HSDG, HSDLp, HSDGp, first, last, wChng, wChngp, TI, volAvgWOhv, HVdAV 170 1 546.0 546.0 4.2 , CPveoHVD, lastDVotWk, lastDVdAV)) 171 173 1 2.0 2.0 0.0 if len(np_weekly_all) > 0: 175 1 2.0 2.0 0.0 a = np_weekly_all[:,1] 176 1 1.0 1.0 0.0 b = np_weekly[:,1] 177 1 205.0 205.0 1.6 tf_1 = np.isin(a, b, invert=True) 179 1 13.0 13.0 0.1 t_result = list(compress(range(len(tf_1)), tf_1)) 181 1 13.0 13.0 0.1 np_weekly_all = np_weekly_all[t_result] 182 1 40.0 40.0 0.3 np_weekly_all = np.vstack((np_weekly_all, np_weekly)) 183 else: 184 np_weekly_all = [] 185 np_weekly_all = np.vstack((np_weekly)) 186 187 1 2.0 2.0 0.0 return np_weekly_all I would glad to hear your suggestions and thanks for pointing to profiler, i didn't know about that.
Edited and posted the line profiler code above. I have updated the code from pandas to numpy which had reduced the times considerable from inital 1h 26min to now 7mins.
Python compare each row, if it have same value A, then plus value B
I have data that have thousand row, therefore I want to compare some row that have same value and meaning and sum their other values into one row. 14:45:14 923.0 6.9 4,399 87,144 14:30:02 923.9 7.8 6 82,745 14:30:00 924.0 7.9 19 82,739 14:29:58 924.0 7.9 1 82,720 14:29:56 924.0 7.9 20 82,719 14:29:54 923.9 7.8 96 82,699 my code while True: dong_khop_lenh = driver.find_element_by_xpath( "//div[#id='derivative-info-table-scroll-area-VN30F1910']" + "/table/tbody/tr["+str(vitri1)+"]") tds = dong_khop_lenh.find_elements_by_tag_name('td') time_khop = tds[0].text gia_khop = tds[1].text lech_vn30 = tds[2].text kl_khop = tds[3].text kl_tluy = tds[4].text dong_khop_lenh_duoi = driver.find_element_by_xpath( "//div[#id='derivative-info-table-scroll-area-VN30F1910']" + "/table/tbody/tr["+str(vitri2)+"]") tds_duoi = dong_khop_lenh_duoi.find_elements_by_tag_name('td') time_khop_duoi = tds_duoi[0].text gia_khop_duoi = tds_duoi[1].text lech_duoi = tds_duoi[2].text kl_khop_duoi = tds_duoi[3].text kl_tluy_duoi = tds_duoi[4].text if float(gia_khop) == float(gia_khop_duoi) and \ int(kl_tluy.replace(',', '')) > int(kl_tluy_duoi.replace(',', '')): vitri1 += 1 vitri2 += 1 kl_khop1 = int(kl_khop_duoi.replace(',', '')) if float(gia_khop) == float(gia_khop_duoi): final_kl_khop_duoi = int(kl_khop1) + int(kl_khop_duoi.replace(',', '')) final_dong_khop_lenh_duoi = str(time_khop) + "->" + str(time_khop_duoi) + \ "\t" + str(gia_khop_duoi) + "\t" + str(lech_duoi ) + \ "\t" + str(final_kl_khop_duoi) + "\t" + str(kl_tluy_duoi) print final_dong_khop_lenh_duoi I tried to compare rows 3 4 5 which have same value at 924, then plus 19+1+20 the result: 14:30:02 923.9 7.8 6 82,745 14:30:00 924.0 7.9 19 82,739 14:30:00->14:29:58 924.0 7.9 2 82,720 14:29:58->14:29:56 924.0 7.9 40 82,719 14:29:54 923.9 7.8 96 82,699 14:29:52 924.0 7.9 3 82,603 14:29:52->14:29:50 924.0 7.9 34 82,600 14:29:50->14:29:48 924.0 7.9 66 82,583 14:29:48->14:29:46 924.0 7.9 126 82,550
Algorithm 11.2 Nonlinear Shooting Method (Burden and Faires) Python
I am trying to program nonlinear shooting method based on algorithm 11.2 from Numerical Analysis (Burden and Faires). However, after running the program, the numerical result i am getting is different from the answer in the textbook. i think there is something wrong in my coding but i cannot figure it out. I attached actual algorithm in the picture. Algorithm 11.2 Algorithm 11.2 Algorithm 11.2 Here is the code from numpy import zeros, abs def shoot_nonlinear(a,b,alpha, beta, n, tol, M): w1 = zeros(n+1) w2 = zeros(n+1) h = (b-a)/n k = 1 TK = (beta - alpha)/(b - a) print("i"" x" " " "W1"" " "W2") while k <= M: w1[0] = alpha w2[0] = TK u1 = 0 u2 = 1 for i in range(1,n+1): x = a + (i-1)*h #step 5 t = x + 0.5*(h) k11 = h*w2[i-1] #step 6 k12 = h*f(x,w1[i-1],w2[i-1]) k21 = h*(w2[i-1] + (1/2)*k12) k22 = h*f(t, w1[i-1] + (1/2)*k11, w2[i-1] + (1/2)*k12) k31 = h*(w2[i-1] + (1/2)*k22) k32 = h*f(t, w1[i-1] + (1/2)*k21, w2[i-1] + (1/2)*k22) t = x + h k41 = h*(w2[i-1]+k32) k42 = h*f(t, w1[i-1] + k31, w2[i-1] + k32) w1[i] = w1[i-1] + (k11 + 2*k21 + 2*k31 + k41)/6 w2[i] = w2[i-1] + (k12 + 2*k22 + 2*k32 + k42)/6 kp11 = h*u2 kp12 = h*(fy(x,w1[i-1],w2[i-1])*u1 + fyp(x,w1[i-1], w2[i-1])*u2) t = x + 0.5*(h) kp21 = h*(u2 + (1/2)*kp12) kp22 = h*((fy(t, w1[i-1],w2[i-1])*(u1 + (1/2)*kp11)) + fyp(x+h/2, w1[i-1],w2[i-1])*(u2 +(1/2)*kp12)) kp31 = h*(u2 + (1/2)*kp22) kp32 = h*((fy(t, w1[i-1],w2[i-1])*(u1 + (1/2)*kp21)) + fyp(x+h/2, w1[i-1],w2[i-1])*(u2 +(1/2)*kp22)) t = x + h kp41 = h*(u2 + kp32) kp42 = h*(fy(t, w1[i-1], w2[i-1])*(u1+kp31) + fyp(x + h, w1[i-1], w2[i-1])*(u2 + kp32)) u1 = u1 + (1/6)*(kp11 + 2*kp21 + 2*kp31 + kp41) u2 = u2 + (1/6)*(kp12 + 2*kp22 + 2*kp32 + kp42) r = abs(w1[n]) - beta #print(r) if r < tol: for i in range(0,n+1): x = a + i*h print("%.2f %.2f %.4f %.4f" %(i,x,w1[i],w2[i])) return TK = TK -(w1[n]-beta)/u1 k = k+1 print("Maximum number of iterations exceeded") return function for 2nd order boundary value problem def f(x,y,yp): fx = (1/8)*(32 + 2*x**3 -y*yp) return fx def fy(xp,z,zp): fyy = -(1/8)*(zp) return fyy def fyp(xpp,zpp,zppp): fypp = -(1/8)*(zpp) return fypp a = 1 # start point b = 3 # end point alpha = 17 # boundary condition beta = 43/3 # boundary condition N = 20 # number of subintervals M = 10 # maximum number of iterations tol = 0.00001 # tolerance shoot_nonlinear(a,b,alpha,beta,N,tol,M) My result i x W1 W2 0.00 1.00 17.0000 -16.2058 1.00 1.10 15.5557 -12.8379 2.00 1.20 14.4067 -10.2482 3.00 1.30 13.4882 -8.1979 4.00 1.40 12.7544 -6.5327 5.00 1.50 12.1723 -5.1496 6.00 1.60 11.7175 -3.9773 7.00 1.70 11.3715 -2.9656 8.00 1.80 11.1203 -2.0783 9.00 1.90 10.9526 -1.2886 10.00 2.00 10.8600 -0.5768 11.00 2.10 10.8352 0.0723 12.00 2.20 10.8727 0.6700 13.00 2.30 10.9678 1.2251 14.00 2.40 11.1165 1.7444 15.00 2.50 11.3157 2.2331 16.00 2.60 11.5623 2.6951 17.00 2.70 11.8539 3.1337 18.00 2.80 12.1883 3.5513 19.00 2.90 12.5635 3.9498 20.00 3.00 12.9777 4.3306 Actual result for w1 x W1 1.0 17.0000 1.1 15.7555 1.2 14.7734 1.3 13.3886 1.4 12.9167 1.5 12.5601 1.6 12.3018 1.7 12.1289 1.8 12.0311 1.9 12.0000 2.0 12.0291 2.1 12.1127 2.2 12.2465 2.3 12.4267 2.4 12.6500 2.5 12.9139 2.6 13.2159 2.7 13.5543 2.8 13.9272 2.9 14.3333 3.0 14.7713
On Line 48, you have r = abs(w1[n]) - beta Instead of r = abs(w1[n] - beta) Making this change gives the same solution as the text, x W1 1.0 17.0000 1.1 15.7555 1.2 14.7734 1.3 13.9978 1.4 13.3886 1.5 12.9167 1.6 12.5601 1.7 12.3018 1.8 12.1289 1.9 12.0311 2.0 12.0000 2.1 12.0291 2.2 12.1127 2.3 12.2465 2.4 12.4267 2.5 12.6500 2.6 12.9139 2.7 13.2159 2.8 13.5543 2.9 13.9272 3.0 14.3333
As a remark in fx = (1/8)*(32 + 2*x**3 -y*yp), 1/8 is going to give the result 0. You should use 1./8 instead.