Can you guys point out the problem when using "if" repetitively in the codes, for example:
if x == 2:
do something
if x == 3:
do something
if x == 4:
do something
Thanks
Can you guys point out the problem when using "if" repetitively in the codes, for example:
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. 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
. 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
. 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
If you just assign sth. to x, this won't make errors, but picture: You want sb. input 1-5, but he might input 6. You need to add "else". But you just used so many "if". I recommend using "if---elif(else)---else".