Link Search Menu Expand Document

Loops and Statements in Python

What are the Loops?

As the name suggests, loop means to repeat something. More precisely, in programming, it means to repeat a set of instructions or a piece of code to meet certain conditions. After reaching a specified condition, the program looks to perform a relevant task assigned to such a condition.

Moreover, loops prove useful to repeat a set of programming instructions or perform a specific operation up to the required number of times. Also, loops make a complex program relatively easy to develop and comprehend. Loops reduce the code by bringing together similar instructions to form a set of them.

In python, there are two types of loops, which are known as for and while loops. The developers use the loops in various forms to get the desired outputs for their programs.

Loops in Python

For Loop

While writing a “for” loop, the programmers define a loop index and its range. The “for” loop checks the provided condition or range in every iteration. On meeting the condition, the process performs the required operation. After operating, the loop updates the condition and verifies again to move further. This method repeats itself until it has achieved the loop’s breaking condition.

Example

An example of using For loops in python is the following:

#A program to find sum of numbers
#List of numbers
Num_array = [3,2,1,10,55,8,9,7,21]
sum=0
#using for loop
for i in Num_array:
  sum=sum+i
print(“The sum of the given numbers is”, sum)

The above code gives the sum of all the numbers in Num_array. Loop updates the index i after every iteration. The process continues until the length of the array and stops after adding the last number. Finally, the print statement displays the sum of all.

The sum of the given numbers is 116

While Loop

A while loop statement executes a target statement repeatedly as long as a specific condition is true in the Python programming language.

In the Python programming language, the syntax of a while loop is:

while expression:
   statement(s)

Statement(s) might be a single statement or a group of statements in this context. Any expression can be used as the condition, and any non-zero value is considered valid. In comparison, the condition is true—the loop iterates.

When the condition meets, program control is transferred to the line immediately following the loop.

In Python, any statements following a programming construct indented by the same number of character spaces are part of a single block of code. Thus, Python’s way of grouping statements is indentation.

The critical feature of the while loop, in this case, is that the loop may never execute. Therefore, the condition is tested, and the result is false. Then, the loop body gets skipped, and the first statement following the while loop executes.

count = 0
while (count < 5):
print 'The count is:', count
count = count + 1

print "Its Running"

  Output:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4

Infinite Loop

If a condition never becomes FALSE, a loop becomes infinite. When utilizing while loops, the user must exercise caution because this condition may never resolve to a FALSE value. As a result, a never-ending cycle creates. An infinite loop is a name given to such a loop.

An infinite loop could be beneficial in client/server programming, where the server must operate continually so that client applications can interconnect with it as needed.

Nested While Loop

The body of the while loop consists of multiple statements. For example, and these statements may be another while loop, If statement, If-Else statement, For Loop statement, or any other acceptable Python statement.

Pattern using Nested While Loop

In the following example, a while loop statement is contained within another while loop. It’s similar to a while in while loop, which is a nested while loop. The user prints a start pattern using this stacked while loop.

i=1
while i < 11:
    j = 0
    while j < i:
        print('*',end='')
        j=j+1
    print()
    i=i+1

Output:

*
**
***
****
*****
******
*******
********
*********
**********

While Loop with Break

The Python Break statement can be used within a looping statement to break the loop even before the condition becomes False.

We have a while loop statement in the following example. The while loop includes a conditional break expression that executes when I equal 7. The user also has a break statement within this if-statement. The while loop breaks using this break statement.

i = 1
while i <= 100 :
    print(i)
    if i == 7 :
        break
    i += 1

Output:

1
2
3
4
5
6
7

Statements in Python

The statement is merely an instruction that the programmers write in the code. In python, there are many kinds of statements, such as assignment statements and conditional statements.

Assignment Statements

The assignment statements are the ones with “=” in them. This sign assigns the values to the specified variables. It is also often used with the arithmetic operators to perform the operation and then assign the variable’s value.

Example

Use of assignment statement through a simple example is as follow:

#Assignment statement in Python
message = “Hello World!”
v = 123
print(message)
print(v)

The output of the above code is as follows.

Hello World!
123

The assignment statement assigns the desired data to variables. This does not give an output until printed.

Conditional Statements

The conditional statements are frequently used in python. For example, the conventional if and else statements with mathematical expressions. The programmers often use them to simplify the problem. Furthermore, conditional statements and loops, together, solve complex problems and find an optimal solution.

Example

A simple example of using conditional statements in python is the following:

#code for using if statement
a= 567
b=234
if b > a:
   print("b is greater than a")
elif a == b:
   print("a and b are equal")
else:
   print("a is greater than b")

This piece of code gives the following output as a result:

a is greater than b

Nested if and else are also applicable in python. For Example:

#code for using nested loop
x = 512
if x > 0:
  print("It is positive number,")
  if (x % 2)==0:
    print("and also an even number!")
  else:
    print("and also an odd number!.")

The output of the above program is:

It is a positive number,
and also an even number!

Using these loops and statements an efficient program is created to solve complex problems.

Using else Statement with While Loop

Python allows the user to associate an else statement with a loop expression.

When the else statement is used in conjunction with a while loop, it performs when the condition turns false.

The following example shows using an else statement in conjunction with a while statement to print a number if it is less than 5. Otherwise, the else statement executes.

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

Output

is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Single Statement Suites

Suppose the while clause is merely one statement. It can be written on the same line as the while heading, as with the if statement syntax.

The syntax and example of a one-line while clause is below.

#!/usr/bin/python

flag = 1
while (flag): print 'Given flag is infinite true!'
print "Hello World!"

It is best not to try the preceding example because it enters an indefinite loop and requires you to hit CTRL+C to quit.

Other useful articles:


Back to top

© , Learn Python 101 — All Rights Reserved - Terms of Use - Privacy Policy