Izzat Rashid
Izzat Rashid

Reputation: 31

Exit option not function :(

Dear fellow python masters, please be nice with me, I'm just a newbie in python program. Right now I'm stuck with 'Exit' option. Below is my code to calculate BMI. Any suggestion? Thanks so much :)

import os
import math

def menu():
    print('\tBMI Calculator')
    print('\t1. Metric Unit - kg and m')
    print('\t2. Exit - not function yet')
    inp = input('>> ')
    
def metric():
    inp1 = input('Enter your weight in kg: ')
    inp2 = input('Enter your height in m: ')

    weight = int(inp1)
    height = float(inp2)

    bmi = weight / (height * height)
    if bmi <= 18.5:
        print('You are underweight')
        print('{:.2f}'.format(bmi))

    elif bmi >= 18.5 and bmi <= 24.9:
        print('You are in normal weight')
        print('{:.2f}'.format(bmi))

    elif bmi >= 25.0 and bmi <= 29.9:
        print('You are overweight')
        print('{:.2f}'.format(bmi))
    
    elif bmi  > 30.0:
        print('Obese')
        print('{:.2f}'.format(bmi))
    
    else:
        print('Wrong input')
    
    print('Keep continue consume healthy food!\n')

while True:
    menu()
    metric()
    os.system('pause')
    os.system('cls')

Upvotes: 0

Views: 45

Answers (3)

Joe Ferndz
Joe Ferndz

Reputation: 8508

You can always do a simple check. Instead of checking for True, you can check for while menu() == '1'. The while statement will call the menu() function and the return from menu() will provide the necessary input for the while to check. This will ensure you get into the loop only to process the metrics. If the value is anything other than 1, the code will exit and end the program.

To make this work, you also need to make a small change to your menu() function.

def menu():
    print('\tBMI Calculator')
    print('\t1. Metric Unit - kg and m')
    print('\t2. Exit - not function yet')
    return input('>> ')

#your metrics() function will come here
def metric():
    ......

while menu() == '1':
    metric()
    os.system('pause')
    os.system('cls')

Upvotes: 0

BlackList96
BlackList96

Reputation: 419

Just use break in the while loop depending on the returned value from menu().

def menu():
  ...
  ...
  return input('>>')
if menu() == '1':
   metric()

else:
   break

Upvotes: 0

ewokx
ewokx

Reputation: 2425

your metric function is run regardless of what you entered as a response in ```menu``.

Try the following:

def menu():
    print('\tBMI Calculator')
    print('\t1. Metric Unit - kg and m')
    print('\t2. Exit - not function yet')
    return input('>> ')

Then in the loop:

while True:
    resp = menu()
    if resp == "1":
        metric()
    else:
        break
os.system('pause')
os.system('cls')

That way, if the user selects 1, it runs the metric() function. Otherwise, it quits the loop.

Upvotes: 2

Related Questions