Creating a loop that doesn’t end can cause your program, or worse, your environment, to crash or stop responding if not handled properly. In Codecademy, if you create an infinite loop it will likely crash your browser tab and force you to refresh the page to get it working again.
I’m still struggling to understand the difference between ‘while/else’ and ‘while/if’ constructions.
It says that the else’ block will execute anytime the loop condition is evaluated to ‘False’. But isn’t this the same as when the ‘if’ statement isn’t true, the underlying code of the ‘else’ statement will execute?
So, I understand that when you create an ‘if’ statement with an underlying command and then an ‘else’ one with another command, the ‘else’ will execute if the ‘if’ condition is violated.
How is this different to the ‘while/else’ construction, whereby the ‘else’ code will execute when the ‘while’ loop condition is evaluated to ‘False’?
import random
count = 1
while count<=3:
i = random.randint(1,10)
print i
if i == 5 or i==6:
#print("5,6 loss")
#break
return "5,6 loss"
count+=1
else:
print("yes")
Hello all,
I have a question, why can’t I use return instead of print+break? it is giving me an error
File “python”, line 9
SyntaxError: ‘return’ outside function
The error message holds the key. Your code is glitching because return is supposed to be used inside a function, which your code does not appear to be.
so here’s the thing += sort of means you add the latter number to the first every time you execute the loop. So as an example, if in a loop it says while < 10 and then later it says something += 1 it means that that something will keep adding one until it reaches 10. ( Feel free to correct if you see it as incorrect partying_face:)
There is no one ‘command’ but a combination of statements and control flow.
The import statement brings in the random module.
The while statement (a conditional loop) tracks the count value which is hardcoded with a literal 3 as the limiting value.
The random.randint() expression in the assignment statement generates a new random integer each time it is called. It may be different from the previous, but it may be the same. With random we don’t know except that it will be in the range we specify (the 10 is included).
So the loop iterates three times and the random.randint() method is called three times, hence, the three numbers.