Python relies heavily on indentation
# The code below prints 0-4, sees that the next for line is not indented, doesn't read it
for x in range(5):
print(x)
# there are other methods of breaking a python loop
for x in range(6):
print(x)
if x == 5:
# break the loop
break
Answer from Marker on Stack OverflowHow does python know when to stop the for loop? - Stack Overflow
Why does my for loop stop iterating after one time?
For Loop stops after first iteration
When to use a for loop and when to use a while loop?
Python relies heavily on indentation
# The code below prints 0-4, sees that the next for line is not indented, doesn't read it
for x in range(5):
print(x)
# there are other methods of breaking a python loop
for x in range(6):
print(x)
if x == 5:
# break the loop
break
well for x in range(5) means itll go up to 5 times(ya already knew that) but thats because it says "ok ill do this until x is equal to 5 while" keep in mind that x gets +1 bigger per itteration. try typing:
for x in range(25):
print(x)
now it will say 123456789 etc.
This is python 3 btw.
When I do this:
def thing(w):
for x in w:
a = []
if x == "f":
a.append(4)
elif x == "s":
a.append(9)
return a
print(thing("fssff"))it outputs [4]. Why doesn't it continue with iterating?
I’m relatively new to coding and for certain projects I always wonder whether I should use a for loop or a while loop. It seems like the results often don’t differ much. Could someone explain when to use which and what the differences are? Or does it really ‘not matter’?
I have a problem assigned in which it asks for the variable z for the given values of variables a, b and c.
The code is as follows:
mult = 0;
while (a < 10) {
mult = b * a;
if (mult > c) {
break;
}
a = a + 1;
}
z = a; a = 4, b = 5, c = 20
So I understood that z = 5 after going through it once so I input this answer and got it right. However, in its explanation it tells me that there's a second iteration where mult is assigned 25 (5*5), then the if branch executes and breaks the loop. Had I not been told this I would have had no idea I had to go through this loop a 2nd time and just assumed it went through it once.
So my question is how do you know how many iterations a loop goes through? I got the answer right but I did not go through it a second time, I just went through it once. So do I have to continue running through the loop over and over until the if statement executes? What if there were no break statement?? I am so confused on this iterations bit. Thank you in advance!!