while True:
print("Welcome to this BMI calculator")
x = str(input("Are you using Pounds or Kg, if you are using Kg press K if you are using Pounds press P:"))
if x in ['P', 'p']:
h = float(input("Key in your weight:"))
elif x in ['K', 'k']:
h = float(input("Key in your weight:"))
else:
**return(x)**
print(x)
Bold indicates error and how to return if the user does not key in any of the characters (P/p/K/k)
From what I understood, you want to take user input and return the value - probably from a function? Then you should consider returning both x
and h
if you intend to use them further in your code.
def input_weight():
"""Ask user for their weight and the metric system they want to use"""
while True:
x = input("Are you using Pounds or Kg, if you are using Kg press K if you are using Pounds press P:")
if x in ['P', 'p', 'K', 'k']:
break # user has provided correct metric
else:
print(x + " is not valid. try again")
while True:
try:
h = float(input("Key in your weight:"))
except ValueError:
print("sorry this is not a valid weight. try again")
continue
else:
break
return h, x
print("Welcome to this BMI calculator")
h, x = input_weight()
print(h, x)
You may also want to check this answer. There are several factors that has to be modified or changed in your code.
As you can see, there are two while
-loop used in the function input_weight()
.
['P', 'p', 'K', 'k']
then the loop will rerun prompting the user of wrong input.