0% found this document useful (0 votes)
2 views19 pages

Python Control Statements and Functions

The document provides a comprehensive overview of various programming concepts in Python, including control statements (if, else, loops), functions, string manipulation, data structures (lists, tuples, sets, dictionaries), regular expressions, modules, file handling, and exception handling. Each section includes example code snippets and their outputs to illustrate the functionality. The content serves as a practical guide for understanding and implementing basic Python programming techniques.

Uploaded by

rspbrowsing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Python Control Statements and Functions

The document provides a comprehensive overview of various programming concepts in Python, including control statements (if, else, loops), functions, string manipulation, data structures (lists, tuples, sets, dictionaries), regular expressions, modules, file handling, and exception handling. Each section includes example code snippets and their outputs to illustrate the functionality. The content serves as a practical guide for understanding and implementing basic Python programming techniques.

Uploaded by

rspbrowsing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Simple if Statement
print("Simple If Statement \n")
i=0
if(i<20):
print ("i = ",i)
print("Done")
2. Simple if... ELSE Statement
print ("\n IF ... ELSE STATEMENT ")
a=int(input("Enter A value "))
b=int(input("Enter B value "))
if(a>b):
print("The value",a ," is a biggest value")
else:
print("The value",b ," is a biggest value")
print("Done")
3. IF… ELSEIF STATEMENT
print ("The If... Elseif Statement\n")
a=int(input("Enter the A value :"))
b=int(input("Enter the B value :"))
c=int(input("Enter the C value :"))
if(a>b):
print ("The biggest value is ",a)
elif(b>c):
print ("The biggest value is ",b)
else:
print ("The biggest value is ",c)
print("\n Done")

4. FLOW CONTROL - WHILE LOOP STATEMENT


print("While loop control statement\n ")
i=1
n=10
sum=0
while(i<=n):
sum=sum+i
i=i+1
print ("The sum of ",n,"natural number is",sum)
avg=float(sum)/n
print("the average of ",n," natural number is ",avg)
print("Done")

5. FLOW CONTROL –FOR LOOP STATEMENT


print(" For loop statement")
print ("print from the even number using for loop statement\n")
n=int(input(" Enter the N value :"))
for i in range(0,n,2):
print ("i = ", i)
print("Done")

[Link] CONTROL STATEMENT - BREAK


print("Demonstate the Break statement\n")
i=1
while(i<=10):
print(i, end=" ")
if(i==5):
break
i=i+1
print("\nDone")

[Link] CONTROL STATEMENT – CONTINUE


print("Demonstate the Continue statement\n")
for i in range (1,11):
if(i==5):
continue
print(i,end=" ")
print("\nDone")
[Link] PROGRAM
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")

[Link] MANIPULATION
#STRING MANIPULATION PROGRAM
a=input("Enter first string :")
b=input("Enter second string :" )
res=a*4
print("\nusing * operator")
print("~~~~~~~~~~~~~~~~~~")
print(res)
print("\nusing + operator")
print("~~~~~~~~~~~~~~~~~~")
res1= a+b
print(res1)
print(" \nbuilt in string manipulaion")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
str1="E"
str2=89
str3="computer science"
out1=ord(str1)
out2=chr(str2)
out3=len(str3)
print("\nThis str() function is used for returning string representation of an object")
print(str(65))
print("\n The ord() function used converting character into integer")
print(out1)
print("\n The chr() function used converting integer into character")
print(out2)
print("\n The length of the string is ",out3)
print ("\n slicing the substring of string is : ",str3[2:7])

OUTPUT
1. Simple If Statement
i= 0
Done
2. IF ... ELSE STATEMENT
Enter A value 40
Enter B value 23
The value 40 is a biggest value
Done
3. The If... Elseif Statement
Enter the A value : 30
Enter the B value : 50
Enter the C value : 45
The biggest value is 50
Done

4. While loop control statement


The sum of 10 natural number is 55
the average of 10 natural number is 5.5
Done
5. For loop statement
print from the even number using for loop statement
Enter the N value : 20
i= 0
i= 2
i= 4
i= 6
i= 8
i = 10
i = 12
i = 14
i = 16
i = 18
Done

6. BREAK STATEMT
Demonstate the Break statement
12345
Done

7. CONTINUE STATEMENT
Demonstate the Continue statement
1 2 3 4 6 7 8 9 10
Done
[Link] PROGRAM
Enter a number: 27
7 is not a prime number.

Enter a number: 60
60 is not a prime number.
[Link] MANIPULATION
Enter first string : python
Enter second string : programming

using * operator
~~~~~~~~~~~~
python python python python

using + operator
~~~~~~~~~~~~
python programming

built in string manipulaion


~~~~~~~~~~~~~~~~~~~~

This str() function is used for returning string representation of an object 65

The ord() function used converting character into integer 69

The chr() function used converting integer into character Y

The length of the string is 16

slicing the substring of string is : mpute


LIST PROGRAM
print("List program ")
list1=['cs',"GOOD",34,67.89]
list2=["WELL",'@@',89,56.78]
print(" \n list1 data : ", list1)
print(" \n list2 data : ", list2)
print("\n list out the perticular index of list1 is")
print(list1[1:3])
print("\n * operator of list is ")
print(list2*3)
print("\n combine the two list of data")
print(list1+ list2)
a=[12,34,56,23]
[Link](100)
print ("\n the append of list is :",a)
print("The sum of list value is : ",sum(a))
print("The count of list value of 34 is : ",[Link](34))
print("The Length of list is :",len(a))
print("The Maximum value of list is : ",max(a))
print("The minimum value of list is : ",min(a))
[Link](reverse=True)
print("The reverse value is ",a)

OUTPUT

List program
list1 data : ['cs', 'GOOD', 34, 67.89]

list2 data : ['WELL', '@@', 89, 56.78]

list out the perticular index of list1 is


['GOOD', 34]

* operator of list is
['WELL', '@@', 89, 56.78, 'WELL', '@@', 89, 56.78, 'WELL', '@@', 89, 56.78]

combine the two list of data


['cs', 'GOOD', 34, 67.89, 'WELL', '@@', 89, 56.78]

the append of list is : [12, 34, 56, 23, 100]


The sum of list value is : 225
The count of list value of 34 is : 1
The Length of list is 5
The Maximum value of list is : 100
The minimum value of list is : 12
The reverse value is [100, 56, 34, 23, 12]
TUPLE PROGRAM
print(" TUPLE program ")
TUP1=('PYTHON',"WELCOME",55,89.34,77)
TUP2=("CS",'&&',25,67.34)
print(" \n TUPLE1 data : ", TUP1)
print(" \n TUPLE2 data : ", TUP2)
print("\n list out the perticular index of TUPLE1 is")
print(TUP1[2:4])
print("\n * operator of Tuple is ")
print(TUP2*3)
print("\n combine the two tuple of data")
print(TUP1+TUP2)
a=(5,67,23,89)
print("The sum of Tuple value is : ",sum(a))
print("The count of Tuple value of 23 is : ",[Link](23))
print("The Length of Tuple is :",len(a))
print("The Maximum value of tuple is : ",max(a))
print("The minimum value of tuple is : ",min(a))

OUTPUT

TUPLE program

TUPLE1 data : ('PYTHON', 'WELCOME', 55, 89.34, 77)

TUPLE2 data : ('CS', '&&', 25, 67.34)

list out the perticular index of TUPLE1 is : (55, 89.34)

* operator of Tuple is

('CS', '&&', 25, 67.34, 'CS', '&&', 25, 67.34, 'CS', '&&', 25, 67.34)

combine the two tuple of data

('PYTHON', 'WELCOME', 55, 89.34, 77, 'CS', '&&', 25, 67.34)

The sum of Tuple value is : 184


The count of Tuple value of 23 is : 1
The Length of Tuple is : 4
The Maximum value of tuple is : 89
The minimum value of tuple is : 5
SET PROGRAM
print("Set Program \n")
set1={1,2,3,4,5}
print(set1)
odd={1,3,5,7,9}
even={2,4,6,8,10}
print("The ODD value is :", odd)
print("The Even value is : ",even)
[Link](11)
[Link](13)
[Link](15)
print("The added value of set is : ",odd)
print("Remove the element from set is : ")
[Link](5)
print(odd)
print("The discard the element is :")
[Link](7)
print(odd)
print("For loop using set is ")
for e in odd :
print(e)
print("The Condition using set is\n ")
if 6 is even:
print("The 6 is present in even set")
else:
print("the 6 is not present in even set ")
print("\nThe clear the set function using set is")
[Link]()
print(odd)
OUTPUT
Set Program
{1, 2, 3, 4, 5}
The ODD value is : {1, 3, 5, 7, 9}
The Even value is : {2, 4, 6, 8, 10}
The added value of set is : {1, 3, 5, 7, 9, 11, 13, 15}
Remove the element from set is : {1, 3, 7, 9, 11, 13, 15}
The discard the element is : {1, 3, 9, 11, 13, 15}
Form loop using set is
1
3
9
11
13
15
The Condition using set is

The 6 is not present in even set

The clear the set function using set is


set()
DICTIONARY PROGRAM
print("Dictionary program ")
dict1={'name':'AKILA','age':18,'class':"IIcs"}
print("dict1['name'] : ",dict1['name'])
print("dict1['age'] : ",dict1['age'])
print("dict1['class'] : ",dict1['class'])
dict1['age']=19
dict1['dept']="computer science"
print("Changing the data value of perticular item is : ",dict1['age'])
print("The append the item of value is ",dict1['dept'])
dict2={'name':'maha','age':17,'class':"IIphy"}
print("length of dict1 is : %d"%len(dict1))
print("length of dict2 is : %d"%len(dict2))

OUTPUT:

Dictionary program
dict1['name'] : AKILA
dict1['age'] : 18
dict1['class'] : IIcs
Changing the data value of perticular item is : 19
The append the item of value is computer science
length of dict1 is : 4
length of dict2 is : 3
REGULAR EXPRESSION PROGRAM
import re
txt="the rain in spain"
x=[Link]("^the.*spain$",txt)
if x:
print("yes,we have a match")
else:
print("no match")
a=[Link]("[arn]",txt)
print(a)

if a:
print("yes,there is at least one match")
else:
print("NO match")
print([Link]("welcome to all"))
string="The python program is very easiest program"
pattern="[Link]"
match=[Link](pattern,string)
if match:
print("match found")
else:
print("match not found")

string="""hello,my number is 944868316 and my brother number is 7448683025"""


regex="\d+"
match=[Link](regex,string)
print(match)
regex="\d"
m=[Link](regex,string)
print(m)
regex="\w+"
match=[Link](regex,string)
print(match)
regex="\w

OUTPUT

yes,we have a match


['r', 'a', 'n', 'n', 'a', 'n']
yes,there is at least one match
welcome\ to\ all
match found
['944868316', '7448683025']
['9', '4', '4', '8', '6', '8', '3', '1', '6', '7', '4', '4', '8', '6', '8', '3', '0', '2', '5']
['hello', 'my', 'number', 'is', '944868316', 'and', 'my', 'brother', 'number', 'is', '7448683025']
['h', 'e', 'l', 'l', 'o', 'm', 'y', 'n', 'u', 'm', 'b', 'e', 'r', 'i', 's', '9', '4', '4', '8', '6', '8', '3', '1', '6', 'a', 'n', 'd', 'm',
'y', 'b', 'r', 'o', 't', 'h', 'e', 'r', 'n', 'u', 'm', 'b', 'e', 'r', 'i', 's', '7', '4', '4', '8', '6', '8', '3', '0', '2', '5']
['on ', 'th sep 2023 at 10.30']
['sh', 'k,', 'oy oh ', 'oy,', 'om', ' h', 'r', '']
['k', 'l', ',', 'om', ' h', 'r', '']
sn*ject has n*er booked already
PROGRAM USING MODULES IN PYTHON.

# Importing modules
import math
import random

# Using math module


radius = 5
area = [Link] * [Link](radius, 2)
sqrt_value = [Link](49)

print("Area of the circle:", area)


print("Square root of 25:", sqrt_value)

# Using random module


random_number = [Link](1,10)
random_choice = [Link](['apple', 'banana', 'orange'])

print("Random number:", random_number)


print("Random choice:", random_choice)

OUTPUT

Area of the circle : 78.53981633974483


Square root of 49 : 7.0
Random number 1
Random choice : orange
PROGRAM FOR FILE HANDLING IN PYTHON

# Writing to a file
file_name = "[Link]"
data = "Hello, World!"

# Open the file in write mode


file = open(file_name, "w")

# Write the data to the file


[Link](data)

# Close the file


[Link]()

# Reading from a file


# Open the file in read mode
file = open(file_name, "r")

# Read the content of the file


content = [Link]()

# Close the file


[Link]()

# Output the content


print("Content of the file:")
print(content)

OUTPUT:
Content of the file:
Hello, World!
EXCEPTION HANDLING IN PYTHON
class Error(Exception):
pass
class ToosmallError(Error):
pass
class ToolargeError(Error):
pass
num=10
while True:
try:
ch=int(input("Enter the number : \t"))
if ch<10:
raise ToosmallError
elif ch>10:
raise ToolargeError
break
except ToosmallError:
print("you entered too small number ,please try again")
except ToolargeError:
print("you entered too Large number ,please try again")
print("you Entered correct number")

OUTPUT
Enter the number : 9
you entered too small number ,please try again
Enter the number : 11
you entered too Large number ,please try again
Enter the number : 10
you Entered correct number
CONSTRUCTOR PROGRAM
import time
class car():
def init (self,name,age):
[Link]=name
[Link]=age
def print_details(self):
print("my car is a" , [Link], "it is", [Link],"years
old")
def print_starting_up(self):
print("starting.... ")
[Link](1)
print("vroom,vroom")
def turn_off_engine(self):
turn_off=input("turn off engine or not....Y or N ?")
if (turnoff_lower)=="y":
print("Engine is turning off")
quit()
else:
print("car is still runing")

car1=car("swiftdezire",3)

car1.print_details()
car1.print_starting_up()
car1.turn_off_engine()

OUTPUT

my car is a swiftdezire it is 3 years old


starting....
vroom,vroom
turn off engine or not ... Y or N ?
Yes. .. "Engine is turning off"
No. .. "Car is still running"
FUNCTION OVERLOADING
# Function Overloading
def vehicle_details():
print("Bus Details")
print("~~~~~~~~~~~~")
print("the name of the vehicle is bus")
print("the price of the vehicle is 800000")
print("The Color of the vehicle is Yellow")
print("\n")
vehicle_details()
def vehicle_details(name):
print("Car Details")
print("~~~~~~~~~~~~")
print("the name of the vehicle name is ",name)
print("the price of the vehicle is 400000")
print("The Color of the vehicle is Blue")
print("\n")
vehicle_details('XYLO')
def vehicle_details(name,color):
print("Bike Details")
print("~~~~~~~~~~~~")
print("the name of the vehicle name is ",name)
print("the price of the vehicle is 100000")
print("The Color of the vehicle is ",color)
vehicle_details('Susiki”,"Red")
OUTPUT:

Bus Details
~~~~~~~~~~~~
the name of the vehicle is bus
the price of the vehicle is 800000
The Color of the vehicle is Yellow

Car Details
~~~~~~~~~~~~
the name of the vehicle name is XYLO
the price of the vehicle is 400000
The Color of the vehicle is Blue

Bike Details
~~~~~~~~~~~~
the name of the vehicle name is Susiki
the price of the vehicle is 100000
The Color of the vehicle is Red

You might also like