Range Function In Python Python Range Function With Example

20 Examples of for loop and while loop in python tutorial

Loops in python

Loops are used in computer programming to repeatedly run a block of code.
A loop can be used, for instance, to repeat a message 100 times. It’s only a simple illustration; loops may be used to accomplish much more.
Python has two different kinds of loops:

  • while loop
  • for loop

 

For loop in Python

A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object. The general syntax of a for loop is:

 

Basic for loop:

A range is a collection of numbers that fall within two numerical intervals.

for i in range(5):
print(i)
output
0
1
2
3
4

2. For loop with a list:

fruits = [‘apple’, ‘banana’, ‘mango’]
for fruit in fruits:
print(fruit)
output:
apple
banana
mango

3, For loop with a string:

for char in “hello”:
print(char)
Output:
h
e
l
l
o

4.For loop with a tuple:

numbers = (1, 2, 3)
for number in numbers:
print(number)
Output:
1
2
3

5.For loop with a dictionary:

ages = {‘Alice’: 22, ‘Bob’: 27, ‘Eve’: 19}
for name, age in ages.items():
print(f'{name} is {age} years old’)
Output:
Alice is 22 years old
Bob is 27 years old
Eve is 19 years old

6.For loop with a nested list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for col in row:
print(col)
output
1
2
3
4
5
6
7
8
9

7. For loop with a break statement:

for i in range(5):
if i == 3:
break
print(i)

output:
0
1
2

8, For loop with a continue statement:

for i in range(5):
if i == 3:
continue
print(i)

output
0
1
2
4

9.For loop with a range and step:

for i in range(10, 0, -2):
print(i)

output
10
8
6
4
2

10. For loop with an else clause:

numbers = [1, 3, 5, 7]
for num in numbers:
if num % 2 == 0:
print(f'{num} is even’)
break
else:
print(‘No even numbers found’)

11. For loop with enumerate and a list:

fruits = [‘apple’, ‘banana’, ‘mango’]
for index, fruit in enumerate(fruits):
print(f'{index}: {fruit}’)

output

0: apple
1: banana
2: mango

12, For loop with multiple iterators:

numbers = [1, 2, 3]
colors = [‘red’, ‘green’, ‘blue’]
for number, color in zip(numbers, colors):
print(f'{number} is {color}’)

Output:
1 is red
2 is green
3 is blue

13. For loop that iterates over a reversed list:

fruits = [‘apple’, ‘banana’, ‘mango’]
for fruit in reversed(fruits):
print(fruit)

output:

mango
banana
apple

14. For loop that iterates over a sorted list:

fruits = [‘apple’, ‘banana’, ‘mango’]
for fruit in sorted(fruits):
print(fruit)
output
apple
banana
mango

15. For loop that iterates over a list in chunks:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(0, len(numbers), 3):
chunk = numbers[i:i+3]
print(chunk)
output
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

16.For loop that iterates over a list and removes elements:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i, number in enumerate(numbers):
if number % 2 == 0:
numbers.pop(i)
print(numbers)
output
[1, 3, 5, 7, 9]

17. For loop that iterates over a list and replaces elements:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i, number in enumerate(numbers):
if number % 2 == 0:
numbers[i] = ‘even’
else:
numbers[i] = ‘odd’
print(numbers)
output
[‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’, ‘even’]
18. For loop that iterates over a list and inserts elements:
numbers = [1, 2, 3, 4, 5]
for i, number in enumerate(numbers):
numbers.insert(i+1, number+5)
print(numbers)
output

 

Python While loop

A block of code is regarded to consist of all the statements that are followed by the same number of character spaces following a programming construct. The way that Python groups statements is by indentation. When a while loop is run, expr is first tested in a boolean context, and if it returns true, the body of the loop is run. The expression is then verified again, and if it is still true, the body is run once again. This process is repeated until the expression is no longer true.

•While loop execute a set a statement as long as test statement is true.
•A relevant variable has to be declared at the beginning of the loop

 

while loop flow chart python

While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements

 

Example of While Loop

Python While Loop

# Python program to illustrate
# while loop
num = 0
while (num < 3):
num = num + 1
print(“vista academy”)

Output

vista academy
vista academy
vista academy

Single statement while block

count = 0
while (count < 5): count += 1; print(“Vista Academy”)

Output
Vista Academy

Vista Academy

Vista Academy

Vista Academy

Vista Academy

 

Example of using the break statement in while loops

To terminate a while loop prematurely in Python, use the break command.

n = 1
while n < 5:
print(“Hello”)
n = n+1
if n == 3:
break

output
Hello
Hello

 

Example of using the continue statement in while loops

n = 1

while n < 5:
if n == 2:
n = n+1
continue
print("Hello")
n = n+1

Output
Hello
Hello
Hello

The continue statement in Python may be used to end the current iteration of the while loop and begin the next one.

 

Using if-elif-else statements inside while loop

z = 0

while z < 3:
if z == 0:
print(“z is”,z)
z += 1
elif z == 1:
print(“z is”,z)
z += 1
else:
print(“z is”,z)
z += 1

output


z is 0
z is 1
z is 3

Adding elements to a list using while loop

List = []
i = 0

while len(List) < 4 :
List.append(i)
i += 1
print(List)

output
[0,1,2,3]

 

Python while loop to print a number series

n = 10

while n <= 100:
print(n ,end = “,”)
n = n+10

OUTPUT
10.20.30.40.50.60.70.80.90,100

 

Counting the number of vowels in a string


def count_vowels(s):
s = s.lower()
vowels = ‘aeiou’
count = 0
i = 0
while i < len(s):
if s[i] in vowels:
count += 1
i += 1
return count

print(count_vowels(‘hello’)) # Output: 2
print(count_vowels(‘aeiou’)) # Output: 5
print(count_vowels(‘abcdefghijklmnopqrstuvwxyz’)) # Output: 5

 

10 common NumPy functions that are useful for data analysis: 10 common use cases for SQL in data analytics 10 commonly used Matplotlib commands for data analytics 10 different between SQL and No SQL 10 important of data analytics for society 10 steps that show how data analytics is changing the banking industry: 10 steps to learn SQL for Data Analytics 10 steps to start career in data science 10 WAYS AGRICULTURE IS TRANSFORMED BY DATA ANALYTICS 10 ways data analytics can be used in addressing climate change: