1.
Programs using elementary data items, lists, dictionaries and tuples
# use of list, tuple, set and
# dictionary
# Lists
l = []
# Adding Element into list
l.append(5)
l.append(10)
print("Adding 5 and 10 in list", l)
# Popping Elements from list
l.pop()
print("Popped one element from list", l)
print()
# Set
s = set()
# Adding element into set
s.add(5)
s.add(10)
print("Adding 5 and 10 in set", s)
# Removing element from set
s.remove(5)
print("Removing 5 from set", s)
print()
# Tuple
t = tuple(l)
# Tuples are immutable
print("Tuple", t)
print()
# Dictionary
d = {}
# Adding the key value pair
d[5] = "Five"
d[10] = "Ten"
print("Dictionary", d)
# Removing key-value pair
del d[10]
print("Dictionary", d)
OUTPUT:
Adding 5 and 10 in list [5, 10]
Popped one element from list [5]
Adding 5 and 10 in set {10, 5}
Removing 5 from set {10}
Tuple (5,)
Dictionary {5: 'Five', 10: 'Ten'}
Dictionary {5: 'Five'}
2. Programs using conditional branches
i) if statement
ii) if else statement
iii) if – elif – else statement
if statement
name=input("Enter Name:")
if name=="MASC":
print("WELCOME MASC")
print("WELCOME GUEST!!!")
Output:
Enter Name: AAA
WELCOME GUEST!!!
if else statement
name = input('Enter Name : ')
if name == 'MASC':
print('Hello MASC! Good Morning')
else:
print('Hello Guest! Good Morning')
Output:
True
Enter Name: MASC
Hello MASC! Good Morning
False
Enter Name: AAA
Hello Guest! Good Morning
if – elif – else statement
brand=input("Enter Your Favourite Brand:")
if brand=="RC":
print("It is childrens brand")
elif brand=="KF":
print("It is not that much kick")
elif brand=="FO":
print("Buy one get Free One")
else :
print("Other Brands are not recommended")
Output
Enter Your Favourite Brand:RC
It is childrens brand
3. Programs using loops
i) while loop ii) for loop
i) While loop
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
Output
Enter number:10
The sum of first 10 nubers is :55
ii) for loop
s=input("Enter some String: ")
i=0
for x in s :
print("The character present at ",i,"index is :",x)
i=i+1
Output
Enter some String: Karthikeya
The character present at 0 index is : K
The character present at 1 index is : a
The character present at 2 index is : r
The character present at 3 index is : t
The character present at 4 index is : h
The character present at 5 index is : i
The character present at 6 index is : k
The character present at 7 index is : e
The character present at 8 index is : y
The character present at 9 index is : a
4. Programs using functions
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Output
Microsoft Windows [Version 10.0.19045.3448]
(c) Microsoft Corporation. All rights reserved.
C:\Users\SRINI>d:
D:\>cd python
D:\python>python 4.py
Enter a number: 5
The factorial of 5 is 120
D:\python>
5. Programs using exception handling
# Program to handle multiple errors with one
# except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output
Microsoft Windows [Version 10.0.19045.3448]
(c) Microsoft Corporation. All rights reserved.
C:\Users\SRINI>d:
D:\>cd python
D:\python>python 5.py
ZeroDivisionError Occurred and Handled
D:\python>
6. Programs using inheritance
# A Python program to demonstrate inheritance
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Person(object):
# Constructor
def init (self, name):
self.name = name
# To get name
def getName(self):
return self.name
# To check if this person is an employee
def isEmployee(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
# Driver code
emp = Person("AAAAA") # An Object of Person
print(emp.getName(), emp.isEmployee())
emp = Employee("BBBBB") # An Object of Employee
print(emp.getName(), emp.isEmployee())
Output
Setting environment for using Microsoft Visual Studio 2005 x86 tools.
C:\Program Files\Microsoft Visual Studio 8\VC>d:
D:\>cd python
D:\python>python 6.py
AAAAA False
BBBBB True
D:\python>
7. Programs using polymorphism
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output
Microsoft Windows [Version 10.0.19045.3448]
(c) Microsoft Corporation. All rights reserved.
C:\Users\SRINI>d:
D:\>cd python
D:\python>python 7.py
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
D:\python>
8. Programs to implement file operations.
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def append_file(filename, text):
try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if name == ' main ':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output
Microsoft Windows [Version 10.0.19045.3448]
(c) Microsoft Corporation. All rights reserved.
C:\Users\SRINI>d:
D:\>cd python
D:\python>python 8.py
File example.txt created successfully.
Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.
D:\python>
9. Programs using modules.
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))
# using pi function contained in math module
print(math.pi)
# 2 radians = 114.59 degrees
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
# Tangent of 0.23 radians
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random
# printing random integer between 0 and 5
print(random.randint(0, 5))
# print random floating point number between 0 and 1
print(random.random())
# random number between 0 and 100
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))
Output
D:\python>python 9.py
5.0
3.141592653589793
114.59155902616465
1.0471975511965976
0.9092974268256817
0.8775825618903728
0.2341433623514653
24
5
0.01569535332319849
1.5046276625493515
1
1696128504.3859644
1970-01-06
D:\python>
10. Programs for creating dynamic and interactive web pages using forms.
<!DOCTYPE html>
<html lang="en">
<head><title>MASC</title>
</head>
<body>
<h1>Enter Your Name</h1>
<input id="name" type="text">
<button type="button" onclick="EnterName()">Submit</button>
<p style="color:green" id="demo"></p>
<script>
function EnterName() {
let x = document.getElementById("name").value;
document.getElementById("demo").innerHTML ="Welcome to " + x;
}
</script>
</body>
</html>
OUTPUT