繁体   English   中英

如何简化代码中的 if/else 语句,或者是否有另一种方法可以替换它们以提供更好的修改?

[英]How can I simplify my if/else statements in my code or is there another way I can replace them to provide for better revising?

因此,我在 python 中进行了大约一年的自学编码,我有幸为卡路里计算器编写了代码,该计算器确定了在特定体重、身高、年龄和性别的情况下个人需要增加或减轻体重的卡路里。 该计算器运行良好,每次根据我的目标制定新的营养计划时,我都会不断使用它。 我的问题是我想组织并简化代码中使用的 if/else 语句,以便更容易实现我对代码的未来目标。 如:

if operation == 'm':
    mBMR = int(66.5 + (13.75 * kg) + (5.003 * cm) - (6.755 * number_1))
    print('66.5 + (13.75 * {}) + (5.003 * {}) - (6.755 * {})  = '.format(kg, cm, number_1))
    print(mBMR)
    
    multiply = input('''What's your level of activity? 
    Type in the number that accossiates with your activity level. 
    1. Little to no exercise  
    2. Light exercise a few times/week  
    3. Moderate exercise 3-5 times/week  
    4. Heavy exercise 6-7 times/week 
    ''')
    
    if multiply == '1':
        mBMRa = int(mBMR * 1.2)
        print(mBMR * 1.2)

这段代码的结尾有更多的 if/else 语句,并且只持续了 200 行代码。 任何建议都会有所帮助,谢谢。

就个人而言,我会使用 tkinter 创建一个带有按钮和字段的小 GUI 来处理这些选项。 您可以使用单独的 windows 或更改相同 window 的内容,添加滑块、下拉菜单、复选框等,使其变得尽可能复杂。

If you're not familiar, tkinter is included with Python by default: https://docs.python.org/3/library/tkinter.html

听起来您想使用一些用户输入来查找适当的乘数。 这是字典的完美应用。

这可能看起来像:

multipliers = {
    "1": 1.2,
    "2": 1.375,
    "3": 1.55,
    "4": 1.725,
}

if multiply in multipliers:
    mBMRa = mBMR * multipliers[multiply]
    print(mBMRa)
else:
    print("Error - invalid input.")

我们在字典中查找用户的选择以找到乘数。 请注意,我们需要捕获无效的用户输入,否则如果他们输入像“asdf”这样的疯狂内容,我们可能会抛出 KeyError。

我建议将其设为 function

def bmr_func(kg, cm, number_1, activity_level=None, other_stuff=None):

    response = {} # for example a dict, or whatever

    mBMR = int(66.5 + (13.75 * kg) + (5.003 * cm) - (6.755 * number_1))
    print('66.5 + (13.75 * {}) + (5.003 * {}) - (6.755 * {})  = '.format(kg, cm, number_1))
    print("mBMR:",mBMR)
    response |= {"mBMR": mBMR}

    if activity_level: #only does this bit is passed as argument
        mBMRa = int( mBMR * aux_dict_for_activity_level_or_whatever.get(activity_level) )
        print(f"for activity level {activity_level} mBMRa is {mBMRa}")
        response |= {"mBMRa":mBMRa}

    if other_stuff:
         #do other stuff if asked
        response |= {"other_stuff": other_stuff}
    return response

然后你像这样使用它

last_one = mbr_func(kg, cm, number_1, activity_level=input(wall_of_text_asking_for_activity_level) )

不确定 last_one 是否有活动?

"mBMRa" in last_one #for example, you get the idea

这样,现在您可以使用其他“输入”而不仅仅是输入,也许是 web 请求 gui 或其他东西。

然后你可以玩更多,而不是在 de function 中打印,你可以将它作为描述添加到响应字典中。 您可以在函数内插入数据库。 等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM