For Loops
'''
Loops in Python:
Sometimes we want to execute a group of statements a certain number of times. This can be done using loops.
Loops are used to execute a block of code repeatedly, either a fixed number of time.
Based on this, loops are further classified into following types; for loop, while loop, nested loop.
'''
'''
For-loop:
A for-loop in Python is used for iterating over sequences such as lists, tuples, strings, dictionaries, and even ranges. It simplifies respective tasks and enhances the code efficiency.
'''
name = "Sindhu"
for i in name:
print(i)
#output = S
# i
# n
# d
# h
# u
#Here "i" denotes every character of the string "Sindhu"
name1 = "Shilpa"
for i in name1:
print(i)
if(i == "p"):
print("This is special")
#output = S
# h
# i
# l
# p
# This is special
# a
colors = ["Black", "White", "Blue"]
for color in colors:
print(color)
for i in color:
print(i)
#output = Black
# B
# l
# a
# c
# k
# White
# W
# h
# i
# t
# e
# Blue
# B
# l
# u
# e
'''
Range():
In Python, range is a in-built function used to generate a sequence of numbers. It's commonly used for looping a specific number of times, especially in for loops.
Basic Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
'''
for k in range(5):
print(k)
#output = 0
# 1
# 2
# 3
# 4
print(k + 1)
#output = 1
# 2
# 3
# 4
# 5
for k in range(1, 9):
print(k)
#output = 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
print(k +1)
#output = 2-9 printed vertically
#If it was (k +2), the output would be 3-10 printed vertically.
#for k in range(1 , 5001):
# print(k)
#output = 1-5000 printed vertically
#For a range(n), Python considers it as (0, n) by-default.
#For a range(1, n), Python considers it as (1, (n-1)).
for k in range(1, 12, 2):
print(k)
#output = 1
# 3
# 5
# 7
# 9
# 11
'''
Let's break down the three parameters of range(x, y, z)- or more formally range(start, stop, step).
1.start(the first parameter: x)
a. This is where the range begins.
b. This is inclusive i.e. range starts from this number.
c. If we leave this out, Python by-default assumes it starts from 0.
Example:
range(2, 12, 2) - Starts from 2
2.stop(the second parameter: y)
a. This is where the range stops, but it is exclusive i.e. it goes up, but does not include this number.
Example:
range(2, 12, 2) - Goes up to 10(not 12)
3.step(the third parameter: z)
a. This tells Python how much to move forward(or backward) after each step.
b. Default is 1.
c. Can be negative to count backwards.
Example(positive step):
range(2, 12, 2) output = 2, 4, 6, 8, 10
Example(negative step)
range(10, 2, -2) output = 10, 8, 6, 4
'''
for k in range(2, 12, 3):
print(k)
#output = 2
# 5
# 8
# 11
Comments
Post a Comment