What happens if we cause an infinite loop?

Question

What happens if we cause an infinite loop?

Answer

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.

1 Like

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?

i get the while else structure:

while condition:
   print("do something")
else:
  print("i am executed when condition of while becomes false")

what do you mean by while/if? You have something in your head, but didn’t share this concept with us

Apologies! I meant ‘if/else’.

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’?

Aren’t they pretty much the same thing?

the while loop could run mutiple times before the while condition becomes false, the if condition only runs once.

5 Likes

Thanks! I understand it now

I couldn’t get the concept of count += 1 here.
When I am removing it, it is generating random varying no. of numbers.

Please clarify

Would you please supply a link to the exercise you are discussing?

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.

1 Like