While loop is not executing at all and everything else looks right - python

I cannot get this while loop to work. Every time, it says something is wrong with it and I have NO idea what. I've tried capitalizing and uncapitalizing, tabbing, just about everything. I'm truly at my wits end, please help
def inputM():
print("Enter weight in kg")
weightm = float(input())
print("Enter heigh in meters")
heightm = float(input())
return weightm, heightm
def inputI():
print("Enter weight in pounds")
weighti = float(input())
print("Enter height in inches")
heighti = float(input())
return weighti, heighti
def healthindex (BMIList, BMINum, bmi, healthy):
if healthy == "b":
print (str(bmi))
elif healthy == "h":
index = 0
print ("Your bmi is" + (str(bmi))
while index < len(BMIList):
if bmi < BMINum[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
return
BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
print("Welcome to BMI Calculator!")
print("Enter I for Imperial or M for Metric")
request = input().upper()
if request == "M":
weightm, heightm = inputM()
bmi = weightm/(heightm**2)
elif request == "I":
weighti, heighti = inputI()
bmi = (703*weighti)/(heighti**2)
else:
print("Invalid input")
print("Enter b to only see your bmi or enter h if you would like to see your bmi and health index")
healthy= input()
healthindex (BMIList, BMINum, bmi, healthy)

You have a syntax error in the print statement above the while loop. You are missing the closing parenthesis as you can see from the following snippet of your code:
print ("Your bmi is" + str(bmi)
while index < len(BMIList):

Related

Python is overlooking this section of code

I am trying to get python to loop a section of code by naming that piece of code and trying to loop it back when the else is called. But, I don't even have to put the code to loop in for python to overlook the defined code. It is almost like I made it invisible:
def main(): from here
weight = int(input("How much do you weigh?: "))
unit = input("Lbs or Kgs?: ")
if unit.upper() == ("KGS"):
converted = weight * 2.2
print("Your weight in pounds is: " + str(converted) + "pounds")
elif unit.upper() == ("LBS"):
converted = weight / 2.2
print("Your weight in kilograms is: " + str(converted) + "pounds")
to here
correct = input("Does This Look Correct? ")
if correct.upper() == "NO":
print("Let's try again then")
weight = float(input("How much do you weigh: "))
unit = input("Kgs or Lbs?: ")
if unit.upper() == "KGS":
converted = weight * 2.2
print("Your weight in pounds is: " + str(converted) + " pounds")
elif unit.upper() == ("LBS"):
converted = weight / 2.2
print("Your weight in kilos is: " + str(converted) + " kilograms")
else:
print("Have A Great Day Then!")
Functions only run when they're called. You have to call main() in the loop.
while True:
main()
correct = input("Does this look correct? ")
if correct.upper() == "NO":
print("Let's try again then")
else:
print("Have a great day then!")
break

bmi calculator how do restart the calculator to go back to yes/no at the top

Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1):
bmi = float(weight_kg1) / (float(height_m1)** 2)
#The input function returns a string. So to get your output you
#need to use "float()" for height and weight:
print("bmi: ")
if bmi < 25 :
print(bmi)
return name1 + " not overweight"
else:
print(bmi)
return name1 + " is overweight"
result= bmi_calculator(name1,float(height_m1),float(weight_kg1))
print(result)
else:
print("thank you")
how do i like repeat this test like print(do you wan to take again)
goes back to would you like to take bmu yes /no at the top
The input function returns a string.
So to get your output you need to use "float()" for height and weight:
bmi = float(weight_kg1) / (float(height_m1)** 2)
Also, you have to call your function, e.g.
bmi_calculator(name1,float(height_m1),float(weight_kg1))
After printing the result
You can add a if else condition where you can take input from the user and ask them, then accordingly you can recall your function or else exit it.
Like this:-
Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
def takeBMI():
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1):
bmi = float(weight_kg1) / (float(height_m1)** 2)
if bmi < 25 :
print(bmi)
return name1 + " not overweight"
else:
print(bmi)
return name1 + " is overweight"
result= bmi_calculator(name1,float(height_m1),float(weight_kg1))
print(result)
again=(input("Take bmi again yes or no "))
if again=="yes":
takeBMI()
else:
exit(0)
takeBMI()
else:
print("thank you")

How to remove a set of characters from a user inputted float - Python

I just started picking up python and I want to know how to do what I said in the title. The only background in programming I have is a semester long C++ class that I had in high school that I got a C in and forgot almost everything from. Here's my code:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")
As you can see, it's just a basic BMI calculator. However, what I wanted to do was make it so that if someone were to input "1.8 m", "1.8 meters" or "1.8 ms" and the equivalent for kilograms, the program would remove the extra input and process it as if they hadn't added that. Also, any extra tips you have for me would be great. Thanks!
Replace the third line with this:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
It works by removing all alphabets before converting to float.
In general, this works
Height_List = []
Height = input("What is your height")
for i in Height:
if i in "1234567890.":
Height_List.append(i)
Actual_Height = float("".join(Height_List))

Adding input validation to a function with three separate inputs

I have the program working how I'd like it to, but I cannot seem to figure out how to add validation for the user test score input. The inputs need to be from 0 - 100 and validate each entered score.
How would I modify my code to use a validation loop for input to be >= 0 and <= 100 in the prompt_scores function?
I previously attempted a while loop but it was ignored when placed on each individual input.
def calc_average(scoreOne, scoreTwo, scoreThree):
average = (scoreOne + scoreTwo + scoreThree)/3
return average
def determine_grade(studentScore):
if studentScore < 60:
return "F"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def prompt_scores():
enteredScoreOne = int(input("Please enter score 1: "))
enteredScoreTwo = int(input("Please enter score 2: "))
enteredScoreThree = int(input("Please enter score 3: "))
return enteredScoreOne, enteredScoreTwo, enteredScoreThree
def print_results(scoreOne, scoreTwo, scoreThree):
print("\nScore\tLetter Grade" )
print(str(scoreOne) + "\t\t" + determine_grade(scoreOne), \
str(scoreTwo) + "\t\t" + determine_grade(scoreTwo), \
str(scoreThree) + "\t\t" + determine_grade(scoreThree), sep = "\n")
def main():
scoreOne, scoreTwo, scoreThree = prompt_scores()
print_results(scoreOne, scoreTwo, scoreThree)
print("-----------------------")
print("Average score: " + str(int(calc_average(scoreOne, scoreTwo,scoreThree))))
print(" Final grade: " + determine_grade(int(calc_average(scoreOne, scoreTwo, scoreThree))))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main == "Y" or rerun_main == "y":
main()
main()
enteredScoreOne = int(input("Please enter score 1: "))
while enteredScoreOne not in range(0, 101):
print("[!] Invalid input!")
enteredScoreOne = int(input("Please enter score 1: "))
And so on for the other variables.
If you're running Python 2 (given that you're using input to read strings, you're not, but I'll add this just in case), you'd better replace in range(...) with (0 <= enteredScoreOne <= 100) as range would return a list, which would consume a little bit of extra memory.
You can check the entered value while getting input if you use function and can force the user to enter the value between 0-100 using recursion also i can see you are using additional functions for which python itself has a built in eg: sum(). Also try to save memory and processing wherever possible now it may not seem a big issue but when you have 1000 lines of code even these small things will save you. Here i mean instead of calling a function twice you can save the result in a variable and use it. I added all these in my code and have given the answer.
def get_input():
try:
score=int(input("please enter score : "))
if (score >=0 and score <100):
return score
else:
print("Score should be inbetween 0-100. Try again :-(:-(:-(")
get_input()
except:#if user enters any special char except float or int tell him to enter int
print("Only integer is accepted")
def determine_grade(avg):
if studentScore < 60:
return "E"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def print_results(*args):
for i,j in enumerate(args):
print("score "+str(i)+" = "+str(j)+" grade = "+determine_grade(j))
def main():
score1 = get_input()
score2 = get_input()
score3 = get_input()
print_results(score1, score2, score3)
print("-----------------------")
avg=sum([score1,score2,score3])/3
print("Average score: " + str(avg))
print(" Final grade: " + determine_grade(avg))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main.lower() == "y":
main()
main()

Python - Returning variable from function trouble

I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())

Categories

Resources