not sure why the output is 1 1, instead of 1123? - python-3.x

I took a quiz, the output for this following code is 1 1 instead of 1 1 2 3. And the explanitaion for this answer is that when the code encounter the break(when it reach 2) ,then loops stop.
I understand that the loops stop when it reach 2, but since print() has the same indentation as if() statement, I thought they are excuted seperately,
(but both still under for loop). So when number reaches 2, even if the loop stops, it will still execute the print(), for it is still under for loops. Hence, the result is the 1 1 2 3. And no matter what if() statement is, the result is the same.
numbers = [1, 1, 2, 3]
for number in numbers:
if number % 2 == 0:
break
print(number)

No, the commands are interpreted in order. When the if condition becomes true, the break exits the for loop before the print can execute. The first two loops the break is skipped since 1 % 2 == 0 is false, but 2 % 2 == 0 is true exiting the loop before getting to 3 which would also be true and print... if the loop hadn't already exited.

When the break statement executes the execution pointer goes to the next statement outside the loop, not the statement after the if block containing the break statement, so the print function is not called once break is executed as the execution is then outside the loop.

Related

is it an infinite looping?(Python 3)

I'm doing a quiz on sololearn and I'm confused, it says I have to loop from 5 to 1 when I use hint I get this code and when I run the code it becomes infinite loop instead of looping from 5 to 1
is it an infinite looping?
x = 5
while x > 0:
print(x)
x -= 1
Python is sensitive to the indenting of code. In order for your decrement statement to fall within the loop it must be indented to fall under the print statement.

When breaking out of a nested loop, how do I make it so that the inner loop isn't ignored in Python?

In a nested loop, after breaking out of the inner loop and going to the top loop it skips the parameters of the inner loop. Why and how can I fix this?
for i in range(5):
for j in range(5):
if i == j:
print('Same Number')
break
This code only prints 'Same Number' once. When 1 = 1. I'm not sure why j never changes but i does.
The way you have it written right now, the inner loop will always break on the first iteration (when i = 0). This is why you are only seeing it print once, the outer loop is looping 5 times, however the inner loop only ever gets through the first iteration before hitting break.
See below, the break line should be nested inside the if statement so it only breaks from the inner loop when the two numbers match.
for i in range(5):
for j in range(5):
if i == j:
print('Same Number')
break

Misaligned Sting summation

I was trying to find the sum of all the positive numbers in a python string,
b=[1,2,3,4,5,-1,-2,-3,-4,6].
I used While loop and break to stop the loop. The loop is stop as soon the index is getting '-1'.
b=[1,2,3,4,5,-1,-2,-3,-4,6]
total=0
i=0
f=0
while i<len(b) and b[i]>0:
total=total+b[i]
i=i+1
while i<len(b) and b[i]<0:
i+=1
break
print(total)
Can someone provide alternative ideas of how to solve this issue ? I am getting 15 as output but I am expecting 21. Thank you for the help.
how about just that:
sum(n for n in b if n > 0)
the generator expression in the sum selects the positive values only.
Your whole problem is simply the break statement. You don't really need it as the loop will exit alone when the condition is not met.
What happens right now, is that your inner loop skips the first negative number - -1 - but then breaks immediately. So at this point in time i = 6 and we're back in the outer loop. So now b[i] = -2 and the outer loop exits.
So, bottom line, remove the break statement and the inner loop will exit alone, just when you want it to, and you will magically get 21 as athe output.
A side note: This is a messy solution for a simple problem with built-in options to handle, as hiro's answer shows.
Still, going with your line of thought, there is no need to get your hands dirty with maintaining indices with while loops. A for-loop is just what you need - iterate through each element, and just add a check if it is positive:
b=[1, 2, 3, 4, 5, -1, -2, -3, -4, 6]
total = 0
for num in b:
if num > 0:
total += num

Why is for else allowed in python

I don't understand why this is allowed in python?
>>> for i in []:
... print(i)
... else:
... print('here')
...
here
should this not have else without if syntax error? The else operates every time too (if the for has iterated or not) so its not connected.
>>> for i in 1,2,3:
... print(i)
... else:
... print('here')
...
1
2
3
here
From the docs
* The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.*
So this is useful if you are doing a for loop but do not know if the element will be found in the loop/ returned true in the loop. So you can add a break statement to exit the loop if the element is found/true, or execute another command if it is not found/true. For example in your loop:
for i in []:
print(i)
else:
print('here')
Output
here
In this case, i was not found in your for loop. However you did not execute a break statement after the for loop. Because of that, the compiler then goes to the else statement to executes the line(s) there since the for loop did not break.
In the second example you have:
for i in 1,2,3:
print(i)
else:
print('here')
Output
1
2
3
here
The for loop did not encounter a break statement, so after the for loop is completed it will then execute the else clause. However it you were to use:
for i in 1,2,3:
print(i)
break
else:
print('here')
Output :
1
else is executed if we don't break from for.
This can be useful in situation and can help us by saving us from the effort of making flags.
Example:
if we want to execute some code if we don't break from for loop, then normally we would have to do
flag = 0
for i in [1,2,3]:
if condition:
flag = 1
break
if flag == 0:
do stuff
we can instead do
for i in [1,2,3]:
if condition:
break
else:
do stuff
You can think about it that: When the break statement is executed in the loop, the code inside the loop following the break statement will be ignored and the loop is finished
if the break statement is not executed, the code following the else statement will be executed after the loop is finished
Mateen Ulhaq and Lance Helsten gave a good example in here Why does python use 'else' after for and while loops?
for i in mylist:
if i == theflag:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.")
and
flagfound = False
for i in mylist:
if i == theflag:
flagfound = True
break
process(i)
if not flagfound:
raise ValueError("List argument missing terminal flag.")
I often use else statement to mark the last turn in for/while loop

Recursive function calls inside else block

How does a recursive function call work? Here is the code snippet that I'm trying to understand.
def some_func(num):
if num == 3:
print (num)
else:
num += 1
some_func(num)
print('final')
some_func(0)
Output:
3
final
final
final
I thought after it hits the if condition for num == 3, it only executes the print statement inside the if block and exits, but it goes ahead to execute the print('final') statement thrice. Why?
I believe the other 3 'finals' are for 0, 1 and 2 respectively. When 3 got printed finally, the function is returned to its parent(2) which then proceeded to print "final" and then returned to its parent(1). It's repeated until it's finally returned to the call when num == 0.

Resources