Home > Mobile >  How to create return to x?
How to create return to x?

Time:12-01

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)

CodePudding user response:

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.

Explanation

As you can see, there are two while-loop used in the function input_weight().

  1. the first loop will continue to ask user for metric system, and if a user inputs anything other than ['P', 'p', 'K', 'k'] then the loop will rerun prompting the user of wrong input.
  2. similarly, the second loop asks user of weight. if the weight is anything but a number, then it will continue to ask user to provide proper input.
  • Related