Tuesday, June 1, 2021

Python - Loops

A loop statement allows us to execute a statement or group of statements multiple times.

Types of loops:

Primarily there are two types of loops in Python

  • While loop
  • For loop

We will look into these one by one!

While loop:

The syntax of a while loop looks like this:

''' while condition:

    #Body of the loop '''

The block keeps executing until the condition is true/false

In while loops, the condition is checked first. If it evaluates to true, the body of the loop is executed, otherwise not! If the loop is entered, the process of condition check and execution is continued until the condition becomes false.

An Example:

i = 0

while i<5:

    print(“Sri”)

    i = i+1

(Above program will print Sri 5 times)

Note: if the condition never becomes false, the loop keeps getting executed.


For loop

A for loop is used to iterate through a sequence like list, tuple or string (iterables)

The syntax of a for loop looks like this:

l = [1, 7, 8]

for item in l:

print(item)

(Above program will print 1, 7 and 8)


Range function:

The range function in python is used to generate a sequence of numbers.We can also specify the start, stop and step-size as follows:

 range(start, stop, step_size)

step size is usually not used with range()

An example demonstrating range() function

for i in range(0, 7): #range(7) can also be used

print(i) #prints 0 to 6

For loop with else

An optional else can be used with a for loop if the code is to be executed when the loop exhausts.

Example:

l = [1, 7, 8]

for item in l:

print(item)

else:

print(“Done”) #This is printed when the loop exhausts!

Output:

1

7

8

Done


The break statement

‘break’ is used to come out of the loop when encountered. It instructs the program to – Exit the loop now

Example:

for i in range(0, 80):

print(i) #This will print 0, 1, 2 and 3

if i == 3:

break

The continue statement

‘continue’ is used to stop the current iteration of the loop and continue with the next one. It instructs the program to “skip this iteration”.

Example:

for i in range(4):

print(“printing”)

if i == 2: #if i is 2, the iteration is skipped

continue

print(i)

pass statement

pass is a null statement in python. It instructs to “Do nothing”.

Example:

l = [1, 7, 8]

for item in l:

pass #without pass, the program will throw an error

 

Practice:

Write a program to print the multiplication table of a given number using for loop.

num = int(input("Enter a number:\n"))
for i in range(1,11):
    n=num * i
    print(f"{num} * {i} : {n}")

Here, I used f string format.

Write a program to greet all the person names stored in a list l1 and which starts with S.

l1 = [“Harry”, “Sohan”, “Sachin”, “Rahul”]

l1 = ["Harry""Sohan""Sachin""Rahul"]
for name in l1:
    if name.startswith('S'):
        print("hello",name)

Write a program to find whether a given number is prime or not.

num=int(input("Enter a number:"))
prime=False
if num==1:
    prime=True
for i in range(2,num):

    if num%i==0:
        prime=True          
        break
    else:
        prime=False
        
if prime==True:
    print("The number is not prime")
else:
    print("The number is prime")

Write a program to find the sum of first n natural numbers using a while loop.

n=int(input("Enter a number:"))
sum=0
for i in range(1,n+1):
    sum+=i
print(f"Sum of 1st {n} numbers is: {sum}")

Write a program to calculate the factorial of a given number using for loop.

num=int(input("Enter a number:"))
t=num
fact=1
while num >0:
    fact*=num
    num-=1
print(f"factorial of {t} is : {fact}")


Write a program to print the following star pattern.

    *

  ***  

***** for n=3

TBD:

Write a program to print the following star pattern:

*

**

*** for n = 3

n=3
for i in range(1,n+1):
    print("*" * i)

or

n=3
for i in range(1,n+1):
    for j in range(1,i+1):
        print("*"end="")
    print("")

No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...