简体   繁体   English

Python 的简单 If 语句问题

[英]Simple If Statement issue with Python

Can you guys point out the problem when using "if" repetitively in the codes, for example:你们能指出代码中重复使用“if”时的问题吗,例如:

if x == 2:
    do something
if x == 3:
    do something
if x == 4:
    do something

Thanks谢谢

This will not cause any errors.这不会导致任何错误。 Whether you use if or elif will depend on your purpose.使用if还是elif取决于您的目的。 Sometimes you want to check several things that are not related.有时你想检查几个不相关的东西。 For example, you might have something like例如,你可能有类似的东西

if action is None:
    action = DEFAULT_ACTION
if args is None:
    args = ()

Whether or not action is None will not effect your decision to check if args is None . action是否为None不会影响您检查args是否为None决定。 You might have something else, however, where it makes a difference.但是,您可能还有其他东西,它会有所作为。 For example:例如:

if action is ACTION_JUMP:
    action_jump()
elif distance > 4:
    action_run(distance)

In this case, you don't want action_run() to be called unless the action is not ACTION_JUMP .在这种情况下,您不希望action_run()被调用,除非操作不是ACTION_JUMP What you use simply depends on your purpose.您使用什么仅取决于您的目的。

x Traceback (most recent call last): File "", line 1, in x NameError: name 'x' is not defined x 回溯(最近一次调用最后一次):文件“”,第 1 行,在 x NameError 中:名称“x”未定义

If you just assign sth.如果你只是分配某物。 to x, this won't make errors, but picture: You want sb.到x,这不会出错,但是图片:你想要某人。 input 1-5, but he might input 6. You need to add "else".输入1-5,但他可能输入6。你需要加上“else”。 But you just used so many "if".但你只是用了这么多“如果”。 I recommend using "if---elif(else)---else".我建议使用“if---elif(else)---else”。

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

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