can we use break statement in if-else statement in python - python

I am trying to use break statement in below code snippet, but i am getting an error "break is outside loop".
what I am trying to do here is when m1=n2, i want to display that matrix multiplication is possible and when m1 !=n2, i want to display the message saying multiplication is not possible and program should stop after displaying the message. any suggestions as to how can i do it.
code snippet is as below -
if (n1 == m2):
print ("matrix multiplication is possible")
else:
print ("matrix multiplication is not possible")
... where should i put break statement here?

break and continue should be used in the loop body. You can use return in functions to terminate it or exit() to stop running the code.

Break is only used for loops such as: while, do while, switch
If you want to end your if statements from executing, you can use return;
By adding return; all else if statements after it won't execute. It's similar to break but not the same :)
Like this;
def myFunction(n1,m2):
if n1 == m2:
print ("matrix multiplication is possible")
else:
print ("matrix multiplication is not possible")
return None #Not really needed, since functions return None by default
myFunction(2,2)

Related

Pass 'continue' from inside a function to the outer loop in Python

I hope i can express myself accordingly, as I'm quite new to programming and I'm sure the answer is quite simple but I can't get there... :)
So I have a 'for' loop that executes some functions. Each function has an 'if' statement in it and only does something, if the conditions allow so.
What I want is the loop to reset, as soon as a function's 'if' statement is satisfied.
Edit: I messed up the function :( thx for your answers so far ^^
An example of what i wish would work:
def do_something():
if something == True:
do_some_stuff
return continue
while i < 999:
do_something()
do_something2()
do_something3()
The 'return continue' is the part that doesn't work as I wish and I can't find a solution for that (maybe I don't know what exactly to google for)
You can have 'do_something' return a boolean
def do_something():
if something is True:
do_some_stuff
return True
return False
while i < 999:
if do_something():
continue
do_something2()
do_something3()
There's no function, so there's nothing to return. You can however break out of the while loop once the condition something is met like so:
while i < 999:
if something == True:
do_some_stuff
break

Is there a conditional that runs if an if statement does not activate within a loop?

Making a simple program that swaps the location of numbers in a loop until they are in ascending order. I want the program to end when the if conditional is never activated within a instance of the for loop. Is there a shorter way to do this without the use of a while true/false or like?
while tf == True:
for i in range(lisLen-1):
tf=False
if listy[i]>listy[i+1]:
tf=True
swap(listy, i, i+1)
Get rid of the variable, and use break instead. Then you can use the else: clause to test this. That clause runs if the loop ended normally instead of with break.
while True:
for i in range(lisLen-1):
if listy[i]>listy[i+1]:
swap(listy, i, i+1)
break
else:
break

Python loop not working as intended

After selecting 2 as my choice on the menu, when I input 1 as the option, the program prints "Thanks for using.....Goodbye" and then loops back to the menu instead of stopping. I cannot figure out what the cause is, since I tried numerous times to fix it but failed. Please advise me what to do. Thanks
code: http://pastebin.com/kc0Jk9qY
Sorry I couldn't implement the code in this comment, was becoming a hassle.
All your code if in a while n!=1: loop. Set n=1 when you want to quit and that's it. So just change your code to the following and it will stop:
elif endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1
break will only terminate the innermost loop, so need to make sure all the outer ones get terminated as well.
EDIT
Changed code is:
if choice==2:
while error2:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1
What you have supplied looks correct. That break will break you out of the while error2 loop. So the problem must lie after that. I expect that if choice==2 is within another loop, and you are not breaking out of that.
OK, this is it. Your error2 value is uneccessary. Simply start an infinite loop and break out on valid responses. I would consider doing this in your other loops too.
if choice==2:
while True:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
break
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
n=1
break

Using a while loop as a wait in python

I have done this in C/C++ before where I have a while loop that acts as a wait holding the program up until the condition is broken. In Python I am trying to do the same with while(GPIO.input(24) != 0): and its says that it is expecting an indent. Is there anyway to get the script to hang on this statement until the condition is broken?
Do note that an empty while loop will tend to hog resources, so if you don't mind decreasing the time resolution, you can include a sleep statement:
while (GPIO.input(24) != 0):
time.sleep(0.1)
That uses less CPU cycles, while still checking the condition with reasonable frequency.
In Python, you need to use the pass statement whenever you want an empty block.
while (GPIO.input(24) != 0):
pass
Add a pass, as such:
while(GPIO.input(24) != 0):
pass
You might also consider a different approach:
while True:
if GPIO.input(24) == 0: break
Whichever you think is more readable.
In python you can't leave the colon : hanging so you must use a pass to complete the empty block. Another way to use a while in this way
while True:
if GPIO.input(24) == 0:
break

Invalid syntax on if-else statement

Can someone explain why I am getting an invalid syntax error from Python's interpreter while formulating this simple if/else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. else is highlighted by the interpreter. What's wrong?
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax
Python does not allow empty blocks, unlike many other languages (since it doesn't use braces to indicate a block). The pass keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0:
print('3 greater then 0')
else:
pass
Or an empty method:
def doNothing():
pass
That's because your else part is empty and also not properly indented with the if.
if 3 > 0:
print "voila"
else:
pass
In python pass is equivalent to {} used in other languages like C.
The else block needs to be at the same indent level as the if:
if 3 > 0:
print('3 greater then 0')
else:
print('3 less than or equal to 0')
The keyword else has to be indented with respect to the if statement respectively
e.g.
a = 2
if a == 2:
print "a=%d", % a
else:
print "mismatched"
The problem is indent only.
You are using IDLE. When you press enter after first print statement indent of else is same as print by default, which is not OK. You need to go to start of else sentence and press back once. Check in attached image what I mean.
it is a obvious mistake we do, when we press enter after the if statement it will come into that intendation,try by keeping the else statement as straight with the if statement.it is a common typographical error
Else needs to be vertically aligned. Identation is playing a key role in Python. I was getting the same syntax error while using else. Make sure you indent your code properly

Categories