For Loop in Python

For Loop in Python

ยท

2 min read

What is For Loop in Python?

A for loop is used for iterating over a sequence (that list, a tuple, a dictionary, or sets).

Example

mylist = ["a","b","c"]
for x in mylist
    print(x)

In for loops we use some special in-built functions.

Range()-it is used to generate a sequence of numbers. the signature of range function is:

Range Syntax

range(start,end,step)

start: the starting integer of the sequence. end: generate numbers up to but not including this number. step: the increment between each number generated. default is 1.

Example

We can iterate over ranges using the for-in loop.

for num in range(1,11,2):
    print(num)  
#1
#3
#5
#7
#9

Example

We can iterate over ranges using the for-in loop.

for num in range(1,11):
    print(num) 
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10

Example

If we want to run a loop N times we can use range() and for-in loop.

n=10
for x in range(1,n+1):
    print(x) 

Example

We can iterate through a character in a string as well.

my_name='prahlad'
for char in my_name:
    print(char)
#p
#r
#a
#h
#l
#a
#d

Example

We can also iterate through each element of a list, sets, and tuples. we can iterate over all the key-value pairs in a dictionary using the items() method:

my_dict={'name'='john'}
for key,values in my_dict.items():
    print{f'{key}-{value}'}  

Example

Prime Numbers or Not

num=113
is_prime=True
for i in range(2,num//2):
    if num%i==0:
        is_prime=False
        break 

Example

str='hello World'
index=-1
for i in range(0,len(str)):
    if str[i]=='W':
       index=i
       break     

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!

ย