DEV Community

Cover image for Python Basics 6: Loops part 2
Irfan Faisal
Irfan Faisal

Posted on • Updated on

Python Basics 6: Loops part 2

Hello everyone! This is our 2nd part of python loop series.
Part 1 is here:
https://dev.to/coderanger08/python-loops-1-5dho

In this week, we'll discuss more about while and for loop, break and pass statements, range function and many more. Let's get started.

Infinite Loop:

An infinite loop is a scenario when a loop runs indefinitely because the condition is always true(while) or the sequence never ends(for). Infinite loop will run forever when the terminating condition has never been met.

count=5
while count>=1:
    print(count)
    count+=1
Enter fullscreen mode Exit fullscreen mode

This while loop is an infinite loop. Think why?

Technically, an infinite loop is a bug(error). You can stop infinite loop manually by terminating the program or using break statement.
However, sometimes infinite loop can be useful in many ways.

  1. Web servers and background services use infinite loops to continuously listen for and handle requests.
  2. Infinite loops in game keep the game running, updating the game state, and rendering frames until the player exits.
  3. Command Line Interfaces (CLIs) use infinite loops to repeatedly prompt the user for input until they choose to exit.

Break Statement

To stop an infinite loop or an usual loop, you can use the break statement.

count=1
while count>=1:
    print(count)
    count+=1
    if count==5:
        break #this will stop the loop here

>>1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Continue Statement

Continue is a little different way to stop a loop. By using continue, you can stop or skip the loop only for that iteration. The loop will start to run again from next iteration.

flowers=["lily","orchid","rose","jasmine"]
for element in flowers:
   if element=="rose":
       continue #it won't print rose
   print(element)

>>
lily
orchid
jasmine
Enter fullscreen mode Exit fullscreen mode

Pass Statement

If we want to write the codes in a (if/else statement, loop block) later, it'll show an error because of empty block. In that case, we can use pass statement. It'll pass that instructions and move on to the next part.

  • Pass statement is a null statement.
  • Interpreter does not ignore a pass statement
  • Empty code is not allowed in loops, function definitions, class definitions or in if statements. To avoid error we use pass statement.

Ex:

Nums=[1,2,3,4,5]
For val in nums:
    Pass    #it will pass the iteration and won't execute anything
#other lines of the code 

Enter fullscreen mode Exit fullscreen mode

Else Statement in a loop:
Unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed.

count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("The while loop completed without a break.")
Enter fullscreen mode Exit fullscreen mode
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
else:
    print("The for loop completed without a break.")

Enter fullscreen mode Exit fullscreen mode

If a break statement is executed inside the for loop then the "else" part is skipped. Note that the "else" part is executed even if there is a continue statement.

count = 0
while count < 5:
    print(count)
    count += 1
    if count == 3:
        break
else:
    print("This will not be printed because the loop was broken.")

Enter fullscreen mode Exit fullscreen mode

Here, the else block is not executed because the while loop is terminated by a break statement when count is 3.

Range Function

Syntax: range(start, stop, step)

  • Range() generates the integer numbers between a given start integer to a stop integer.
  • A start integer is a starting number of the sequence. By default, it starts with 0 if not specified.
  • A stop argument is an upper limit. Range() function generates numbers up to this number but not including this number.
  • Start number is included but stop number is excluded.
  • The step is a difference between each number in the result. The default value of the step is 1 if not specified.
  • All the arguments (start, stop, step) must be integers.

Ex: range(1,6) => [1,2,3,4,5] {it generates a sequence of integers from 1 to 5, but not 6}

Note: print(range(1,6)) will not print any numbers.

#printing 1 to 5
For num in range(1,6,1):
    Print(num,end=",")
>>1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode
#printing 5 to 1 backwards:
For num in range(1,6,-1):
    Print(num, end=",")
>>5
4
3
2
1
Enter fullscreen mode Exit fullscreen mode

Nested Loop

Nested Loop is a loop that is contained within another loop. The "inner loop" runs completely for each iteration of the "outer loop".

rows=int(input())

for i in range(rows+1):#outer loop
  for j in range(i):#inner loop
    print(i,end=' ')
  print()
>>
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Enter fullscreen mode Exit fullscreen mode

With this, I will wrap up python loop. I hope this series on 'Loop' helped you to have a quick overview or brush up your knowledge about this topic.
Here are 3 problems for you to solve on python loops. Solve these problems and share your solution in the comments. Happy coding!

Problems

  1. Write a Python program to check if the given string is a palindrome.(Palindrome is a word or sequence that reads the same forward and backward)

  2. Write a Python program to check if the number is prime or not.(A prime number is a number which is only divisible by 1 and itself)

  3. Display a Fibonacci sequence up to 10 terms. The Fibonacci Sequence is a series of numbers where the next number is found by adding up the two numbers before it. The first two numbers are 0 and 1.

Your task is to write a python program of a Fibonacci sequence of first 10 terms.
(Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

Top comments (0)