0% found this document useful (0 votes)
4 views

Module 3 part1

Uploaded by

Ram Deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 3 part1

Uploaded by

Ram Deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Module No.

Loops and Regular Expressions

Creating Loops with while and for, Different versions of Loops, Nested
Loops, Loop Control Statements, Loop Modification with break,
continue and pass, Regular Expressions.

01-07-2024 Dr. V.Srilakshmi 1


Loops in Python

Python has two primitive loops


1. While
2. for

01-07-2024 Dr. V.Srilakshmi 2


The while Loop
Syntax:
while test_expression:
Body of while

• while loop executes a block of statements repeatedly till a given a


condition is true. when the condition becomes false, it terminates the
body of the loop.
• In Python, the body of the while loop is determined through
indentation.
01-07-2024 Dr. V.Srilakshmi 3
Loop to print numbers from 1 to 10
i = 1
# Use a while loop to print numbers from 1 to 10
while i <= 10:
print(i)
i=i+1 Output:
1
2
3
4
5
6
7
8
9
10

01-07-2024 Dr. V.Srilakshmi 4


• Write a python program to print all odd numbers from 1 to n

i=1

n=int(input("enter n value"))

while i<=n:

print(i)
i=i+2

print("end of loop")

01-07-2024 Dr. V.Srilakshmi 5


Write a Python program to calculate the sum of the digits of a number

num = int(input("Enter a number: "))


sum = 0
while num > 0:
digit = num % 10 # Extract the last digit
sum=sum+digit
num= num//10 # Remove the last digit from the number
print("Sum of digits:", sum)

Output:
Enter a number: 127
Sum of digits: 10
01-07-2024 Dr. V.Srilakshmi 6
Write a Python program to check if a number is a palindrome or not

num = int(input("Enter a number: ")) Note:


original_num = num A palindromic number is a number that remains the
reversed_num = 0 same when its digits are reversed.
Ex: 121, 1331, 5555, 12321
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
# Check if the original number is equal to the reversed number
if original_num == reversed_num:
print("The number is a palindrome.") Output:
Enter a number: 1331
else:
The number is a palindrome.
print("The number is not a palindrome.")
Enter a number: 1234The number
is not a palindrome.
01-07-2024 Dr. V.Srilakshmi 7
Python Program to Check Armstrong number
An Armstrong number is a number
that is equal to the sum of its n=int(input())
s = n
individual digits each raised to the
power of the number of digits. d= len(str(n)) 153
sum = 0 The given number 153 is Armstrong number
For example, one of the smallest while n != 0:
Armstrong numbers is 153: r = n % 10
•The number has 3 digits. sum= sum+(r**d)
•The sum of each digit raised to n = n//10
the power of 3 is: 1^3 + 5^3 + 3^3
= 1 + 125 + 27 = 153.
if s == sum:
print("The given number", s, "is Armstrong
number")
else:
print("The given number", s, "is not Armstrong
number")
01-07-2024 Dr. V.Srilakshmi 8
Using else statement with while loops:
• The else clause is only executed when your while condition
becomes false.
• If you break out of the loop, or if an exception is raised, it won’t
be executed.
Syntax:
while condition:
# execute these statements
else:
# execute these statement

01-07-2024 Dr. V.Srilakshmi 9


• Example:
i=1

while i<=10:

print(“VIT”)

i++

else:

print("using else in while")

print("testing")

print("end of loop")

01-07-2024 Dr. V.Srilakshmi 10


for loop
• A for loop is used for iterating over a sequence(list, tuple, string)
• for loop can execute a set of statements(Body), once for each item in a list

Syntax of for Loop


for variable in sequence:
Body of for

• Here, variable takes the value of the item inside the sequence on each iteration.
• Loop continues until it reach the last item in the sequence.
01-07-2024 Dr. V.Srilakshmi 11
# Program to find the sum of all numbers stored in a list#

numbers = [6, 5, 3, 8]
sum = 0
for i in numbers:
sum = sum+i
print("The sum is", sum)
Output:
The sum is 22

01-07-2024 Dr. V.Srilakshmi 12


Ex: Program to count the vowels in a list

text = “University"
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print("Vowel count:", vowel_count)

Output:
Vowel count: 4

01-07-2024 Dr. V.Srilakshmi 13


range() function
• It generates a sequence of numbers.
• range(10) will generate numbers from 0 to 9 (10 numbers).
• We can also define the start, stop and step size as range(start,stop,step
size)
• step size defaults to 1 if not provided.
• list() function output all the items in the range.

print(list(range(10))) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


print(list(range(2, 8))) # Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 20, 3))) # Output: [2, 5, 8, 11, 14, 17]

01-07-2024 Dr. V.Srilakshmi 14


# Python Program find even and odd numbers in between 1 to n
n=int(input("enter number"))

# Initialize empty lists to store even and odd numbers


even_numbers = []
odd_numbers = []

# Iterate through the list and categorize the numbers


for num in range(1,n):
if num % 2 == 0:
even_numbers.append(num) Output:
else: enter number 6
odd_numbers.append(num) Even numbers: [2, 4]
Odd numbers: [1, 3, 5]
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)

01-07-2024 Dr. V.Srilakshmi 15


Write a python program to print numbers from n to 1
n=int(input("enter n value"))
for i in range(n,0,-1):
print(i)

01-07-2024 Dr. V.Srilakshmi 16


Print the multiplication table for a given number
Enter an integer
num = int(input("Enter an integer")) 5
for i in range(1, 11): 5x1=5
5 x 2 = 10
product = num * i 5 x 3 = 15
print(num, "x“, i, "=“,product) 5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

01-07-2024 Dr. V.Srilakshmi 17


Python program to display numbers up to a given value
n that are divisible by both 3 and 7

n = int(input("Enter the value of n: "))

for num in range(1, n + 1):


if num % 3 == 0 and num % 7 == 0:
print(num)

01-07-2024 Dr. V.Srilakshmi 18


Python Program to Check Prime Number
• A positive integer greater than 1 which does not have other factors except 1 and the
number itself is called a prime number.
• The numbers 2, 3, 5, 7, etc. are prime numbers as they do not have any other factors.

num = 152
if num > 1: 152 is not a prime number
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

01-07-2024 Dr. V.Srilakshmi 19


Using else Statement with For Loop
Python supports to have an else statement associated with a loop
statement
•If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
Syntax:

for iterating_var in sequence:


statements(s)
else:
stements(s)

01-07-2024 Dr. V.Srilakshmi 20


Write a python program to check whether given no is prime or not
n=int(input("enter any no"))
for i in range(2,n):
if(n%i==0):
print(n,"is not prime")
break
else:
print(n,"is prime")

01-07-2024 Dr. V.Srilakshmi 21


Python break and continue
• In Python, break and continue statements can alter the flow of a loop.
Python break statement:
•The break statement is used to exit a loop prematurely when a certain condition is
met.
•When break is encountered inside a loop, the loop is terminated, and the program
continues with the next statement after the loop.

01-07-2024 Dr. V.Srilakshmi 22


Python break
Example-1:
Example-2:
for i in range(1,11): for val in "VIT-AP":
if i == 4: if val == "A":
break break
print(i) print(val)
print("It display values before",i)

Output:
Output: V
1 I
2 T
3 -
It display values before 4

01-07-2024 Dr. V.Srilakshmi 23


Python continue statement
•The continue statement is used to skip the current iteration of a loop and move to the
next iteration, without executing the remaining code in the loop for the current
iteration.
•It's useful when you want to skip certain iterations based on a condition but continue
the loop overall

01-07-2024 Dr. V.Srilakshmi 24


Python continue statement
Example-2:
Example-1:
for val in "VIT-AP":
for i in range(1,11): if val == "A":
if i == 4: continue
continue print(val)
1 print(i)
2
3 V
5 I
6 T
7 -
8 P
9
10
01-07-2024 Dr. V.Srilakshmi 25
Python pass statement
• The pass statement is a null operation; nothing happens when it
executes.
• It indicates no operation (NOP).
• So, we use the pass statement to construct a body that does nothing.
• Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
give an error. So, we use the pass statement to construct a body that does nothing.

• Ex: sequence = {‘a', ‘b', ‘c'}


for val in sequence:
pass
print ("good bye")
01-07-2024 Dr. V.Srilakshmi 26
Python Nested Loops
• Nested loops mean loops inside a loop.
• For example, while loop inside the for loop, for loop inside the for loop, etc.

Python Nested Loops Syntax:


Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop Example:
x = [1, 2] 14
y = [4, 5] 15
24
25
for i in x:
for j in y:
print(i, j)

01-07-2024 Dr. V.Srilakshmi 27


Right Half Pyramid Pattern

n=int(input("enter n"))
for i in range(1, n+1):
for j in range(1, i + 1):
print(j,end=" ")
print()

01-07-2024 Dr. V.Srilakshmi 28


Right Half Pyramid star pattern

n=int(input("enter n"))
for i in range(1, n+1):
for j in range(1, i + 1):
print(“*”,end=" ")
print()

01-07-2024 Dr. V.Srilakshmi 29


Inverted Right Half Pyramid star pattern

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

01-07-2024 Dr. V.Srilakshmi 30


n=5
x=0
for i in range(1, n+1):
for j in range(1, i + 1):
x=x+1
print(x, end=" ")
print()

01-07-2024 Dr. V.Srilakshmi 31


Full Pyramid Pattern in python

n = 5
for i in range(1, n+1):
for j in range(n - i):
print(' ', end='')
for k in range(2*i - 1):
print('*', end='')
print()

01-07-2024 Dr. V.Srilakshmi 32


Number Pyramid Pattern Program In Python

n = 5
for i in range(1, n+1):
for j in range(n - i):
print(' ', end='')
for k in range(2*i - 1):
print(k+1, end='')
print()

01-07-2024 Dr. V.Srilakshmi 33


Reverse Number Pyramid Pattern Program In Python

size = 5
for i in range(size): # print spaces
for j in range(i):
print(" ", end="") # print numbers
for k in range(2 * (size - i) - 1):
print(k+1, end="")
print()

01-07-2024 Dr. V.Srilakshmi 34


Python program to determine whether a given number is a
perfect number or not

• A perfect number is a positive integer that is equal to the sum of its proper
divisors (excluding itself).
• For example, 6 is a perfect number in Python because 6 is divisible by 1, 2,
3, and 6.
• So, the sum of these values are 1+2+3 = 6 (Remember, we have to exclude
the number itself. That’s why we haven’t added 6 here).
• Some of the perfect numbers are 6, 28, 496, etc.

01-07-2024 Dr. V.Srilakshmi 35


Python program to determine whether a given number is a perfect
number or not
num = int(input("Enter a number: "))
sum_of_divisors = 0 Output:
Enter a number: 6
for i in range(1, num):
6 is a perfect number.
if num % i == 0:
sum_of_divisors += i Enter a number: 10
10 is not a perfect number.
if sum_of_divisors == num:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect
number.")

01-07-2024 Dr. V.Srilakshmi 36


Python program to print following pattern

n = 5
for i in range(n+1): 54321
for j in range(n-i,0,-1):
print(j,end=' ')
4321
print() 321
21
1

01-07-2024 Dr. V.Srilakshmi 37


Python program to print following pattern

n = 5
alpha = 65
for i in range(n+1):
A
# print spaces ABC
for j in range(n - i): ABCDE
print(" ", end="")
ABCDEFG
ABCDEFGHI
# print alphabets
for k in range(2 * i -1):
print(chr(alpha + k), end="")
print()

01-07-2024 Dr. V.Srilakshmi 38


Python program to sort list without using built-in methods(Bubble sort)

a = [64, 34, 25, 12, 22, 11, 9]


n = len(a)
for i in range(n):
for j in range(0, n - i - 1):
if a[j] > a[j + 1]:
t=a[j]
a[j] = a[j+1]
a[j+1]=t

print("Sorted array:",a)
Sorted array: [9, 11, 12, 22, 25, 34, 64]

01-07-2024 Dr. V.Srilakshmi 39


Regular Expressions

01-07-2024 Dr. V.Srilakshmi 40


Write a Python program that matches a string that has
an a followed by zero or more b's.

import re

txt = "abacus"
patterns= 'ab*'

if(re.search(patterns,txt)):
print("Found a match!")
Found a match!
else:
print('Not matched!')

01-07-2024 Dr. V.Srilakshmi 41


Write a Python program to find sequences of lowercase letters
joined by an underscore.

import re

text = "aba_cus"
patterns = '[a-z]_[a-z]'
if re.search(patterns, text):
print('Found a match!')
else:
print('Not matched!')

01-07-2024 Dr. V.Srilakshmi 42


Write a Python program that matches a string that has an 'a' followed by anything
ending in 'b'.

import re

text = "abaub"
patterns = 'a.*b$'
if re.search(patterns, text):
print('Found a match!')
else:
Found a match!
print('Not matched!')

01-07-2024 Dr. V.Srilakshmi 43


Write a Python program that matches a word containing 'z'.

import re

text = "The quick brown fox jumps over the lazy dog."
patterns = '\wz'
if re.search(patterns, text):
print('Found a match!')
else:
print('Not matched!')

01-07-2024 Dr. V.Srilakshmi 44


Write a Python program to extract year, month and date from an URL.

import re

url=
"https://www.washingtonpost.com/news/wp/2016/09/02/odell/"

d=re.findall('/(\d{4})/(\d{1,2})/(\d{1,2})/', url)
[('2016', '09', '02')]
print(d)

01-07-2024 Dr. V.Srilakshmi 45


Validating Mobile number

import re

mobile = "9502734525"
pattern = "[789]\d{9}$"
if re.search(pattern, mobile):
print("Valid mobile:")
else:
print("Invalid mobile!")

01-07-2024 Dr. V.Srilakshmi 46


Validating Email Addresses

import re

email = "[email protected]"
pattern = "^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$"
if re.search(pattern, email):
print("Valid email address:")
else:
print("Invalid email address!!")

01-07-2024 Dr. V.Srilakshmi 47


To check for a number at the end of a string.
patterns ='.*[0-9]$’

Construct a regex that matches abc followed by zero to many digits (0-9).
abc\d*

Construct a regex that matches both gray and grey.


gr[ae]y

Construct a regex that matches br followed by any single character except for a new line and then 3.
br.3

Construct a regex that matches a word that starts with an uppercase letter followed by at least one
lowercase letter, like “Apple”, “Banana”, or “Carrot”.
[A-Z][a-z]+
01-07-2024 Dr. V.Srilakshmi 48
Construct a regex that matches eight word characters (letter, digit, or underscore).
\w{8}

Construct a regex that matches one or more lowercase letters (a-z) followed by a space character and
then two to four digits.
[a-z]+\s\d{2,4}

Construct a regex that captures strings that have two digits followed by a period and then four letters
from a to z.
\d{2}\.[a-z]{4}

FIND OUT ALL OF THE WORDS, WHICH START WITH A CONSONANT


'\b[^aeiou0-9 ]\w+'

01-07-2024 Dr. V.Srilakshmi 49


FIND OUT ALL OF THE WORDS, WHICH START WITH A VOWEL.

import re

txt = “The rain in Spain"


x = re.findall(r"\b[aeiou]\w+", txt)
print(x)

01-07-2024 Dr. V.Srilakshmi 50

You might also like