Skip to content
← Back to Community
Break If Statement (Python)
Profile icon
littlepenguin

Can you break an if statement?
thanks

Answered by realTronsi [earned 5 cycles]
View Answer
Voters
Profile icon
salmaakram
Profile icon
littlepenguin
Comments
hotnewtop
Profile icon
realTronsi

why would you need to break out of if statements? Logically it makes no sense, so there is no ability to "break" out of an if statement. However if you want to end it early just use another if statement

Profile icon
RYANTADIPARTHI

you cannot break out of if stataments. Only loops allow you to break. Since they run forever, until something is satisfied. The if statements don't need anything. They get satisfied easily. Just remember only loops can use break and continue. If statements cannot.

Profile icon
CSharpIsGud

Well, not break per se. but you can do this with the goto-statement module

#Python 2.7.17 from goto import with_goto @with_goto def main(): if True: print("One.") goto .after print("Two!") label .after print("Hello, world!") main()

But please for god sake do not. You can do it more readable and easier by just not doing this

Profile icon
[deleted]

Well, if statements are made so that if the user input or something satisfies a certain condition. When you say 'break out of an if statement', it isn't correct. You can break out of an 'while' loop, as it continues over and over again repeatedly. An if statement doesn't really repeatedly ask you until you satisfy a certain condition; that's an if statement.
For example, if you want to say like if the user input is 2, print 4.


num = input("Type number")
if num == '2':
print('4')
print("Yes")


The statement 'print('4')' is in the if statement, so it occurs IF AND ONLY IF the user input is 2.If the user types 3 or something else, it won't print 4.
NOTE: Note that I wrote 'print('yes')' outside the if statement. So, irrespective of whether the user writes 2 or something else, 'yes' will be printed.
A while statement would keep on repeating until a certain condition is satisfied or is not satisfied.
Example:


num = input("Number: ")
while num == '2':
print("No")
num = input("Number")
print("OK")


In the above example, if the user enters 2, he will get 'no' printed on his screen and it will ask num again. If the user types anything else, he will break out of the loop and 'OK' will get printed on the screen.
Hope this helps!
Thanks!

Profile icon
CookieSnowOwl

I have no idea what ur talking about. Python? Javascript? What? Also why would you need to? Thanks. Please share a part of the code.

Profile icon
JasonLiu19

No, since if, elif, and else statements are not loops.