if 절을 종료하는 방법
if
절 을 조기에 종료하는 방법에는 어떤 것이 있습니까?
코드를 작성할 때 break
문을 if
절 안에 넣고 싶을 때가 있는데 , 그것들은 루프에만 사용할 수 있다는 것을 기억하기 위해서입니다.
다음 코드를 예로 들어 보겠습니다.
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
이 작업을 수행하는 한 가지 방법을 생각할 수 있습니다. 종료 사례가 중첩 된 if 문 내에서 발생한다고 가정하고 나머지 코드를 큰 else 블록으로 래핑합니다. 예:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
else:
...
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
이 문제는 더 많은 종료 위치가 더 많은 중첩 / 들여 쓰기 코드를 의미한다는 것입니다.
또는 if
절을 가능한 한 작게 만들고 종료가 필요하지 않도록 코드를 작성할 수 있습니다.
if
절 을 종료하는 좋은 / 더 나은 방법을 아는 사람이 있습니까?
연관된 else-if 및 else 절이 있으면 종료하면 해당 절을 건너 뛸 수 있습니다.
(이 방법은 if
s, 다중 중첩 루프 및 break
쉽게 얻을 수없는 기타 구문에 대해 작동합니다 .)
자체 함수로 코드를 래핑합니다. 대신 break
, 사용 return
.
예:
def some_function():
if condition_a:
# do something and return early
...
return
...
if condition_b:
# do something else and return early
...
return
...
return
if outer_condition:
...
some_function()
...
에서 고토 수입 고토, 라벨 some_condition : ... condition_a 인 경우 : # 뭔가를 # 다음 외부 if 블록을 종료합니다. goto .end ... condition_b 인 경우 : # 뭔가를 # 다음 외부 if 블록을 종료합니다. goto .end # 여기에 더 많은 코드 label .end
(실제로 사용하지 마세요.)
while some_condition:
...
if condition_a:
# do something
break
...
if condition_b:
# do something
break
# more code here
break
예외를 제외하고 goto의 기능을 에뮬레이션 할 수 있습니다.
try:
# blah, blah ...
# raise MyFunkyException as soon as you want out
except MyFunkyException:
pass
Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)
may be this?
if some_condition and condition_a:
# do something
elif some_condition and condition_b:
# do something
# and then exit the outer if block
elif some_condition and not condition_b:
# more code here
else:
#blah
if
Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.
However, if you must:
if condition_a:
def condition_a_fun():
do_stuff()
if we_wanna_escape:
return
condition_a_fun()
if condition_b:
def condition_b_fun():
do_more_stuff()
if we_wanna_get_out_again:
return
condition_b_fun()
Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.
For what was actually asked, my approach is to put those if
s inside a one-looped loop
while (True):
if (some_condition):
...
if (condition_a):
# do something
# and then exit the outer if block
break
...
if (condition_b):
# do something
# and then exit the outer if block
break
# more code here
# make sure it is looped once
break
Test it:
conditions = [True,False]
some_condition = True
for condition_a in conditions:
for condition_b in conditions:
print("\n")
print("with condition_a", condition_a)
print("with condition_b", condition_b)
while (True):
if (some_condition):
print("checkpoint 1")
if (condition_a):
# do something
# and then exit the outer if block
print("checkpoint 2")
break
print ("checkpoint 3")
if (condition_b):
# do something
# and then exit the outer if block
print("checkpoint 4")
break
print ("checkpoint 5")
# more code here
# make sure it is looped once
break
Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.
However, cleaner still would be:
if some_condition:
...
if condition_a:
your_function1()
else:
your_function2()
...
def your_function2():
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
There is another way which doesn't rely on defining functions (because sometimes that's less readable for small code snippets), doesn't use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn't use goto (...) and most importantly let's you keep your indentation level for the outer if so you don't have to start nesting stuff.
if some_condition:
...
if condition_a:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
# keep doing something
if condition_b:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if:
# keep doing something
Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn't require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it's easily readable, all in one place and with the same indentation.
And it should be pretty efficient.
So here i understand you're trying to break out of the outer if code block
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
One way out of this is that you can test for for a false condition in the outer if block, which will then implicitly exit out of the code block, you then use an else block to nest the other ifs to do something
if test_for_false:
# Exit the code(which is the outer if code)
else:
if condition_a:
# Do something
if condition_b:
# Do something
use return
in the if condition will returns you out from the function, so that you can use return to break the the if condition.
참고URL : https://stackoverflow.com/questions/2069662/how-to-exit-an-if-clause
'program story' 카테고리의 다른 글
MongoDB에서 '좋지 않음'연산자를 어떻게 사용할 수 있습니까? (0) | 2020.09.16 |
---|---|
Ruby는 기능적인 언어입니까? (0) | 2020.09.16 |
이드의 의미는 무엇입니까? (0) | 2020.09.16 |
단일 행 중첩 For 루프 (0) | 2020.09.16 |
포인터 선언에 별표 배치 (0) | 2020.09.15 |