Home  >  Article  >  Backend Development  >  Python Loops 2

Python Loops 2

WBOY
WBOYOriginal
2024-08-12 18:32:13542browse

Python Loops 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

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

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

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 

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.")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
else:
    print("The for loop completed without a break.")

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.")

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
#printing 5 to 1 backwards:
For num in range(1,6,-1):
    Print(num, end=",")
>>5
4
3
2
1

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

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)

The above is the detailed content of Python Loops 2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn