首页 > 解决方案 > 退出选项不起作用:(

问题描述

亲爱的python高手们,请对我好一点,我只是python程序的新手。现在我被“退出”选项卡住了。下面是我计算 BMI 的代码。有什么建议吗?非常感谢 :)

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')

标签: python-3.x

解决方案


metric无论您在“菜单”中输入什么作为响应,您的函数都会运行。

尝试以下操作:

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

然后在循环中:

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

这样,如果用户选择 1,它将运行该metric()函数。否则,它退出循环。


推荐阅读