You are on page 1of 27

Assignment No.

1
Title: To calculate salary of an employee given his basic pay (take as input from user).
Calculate gross salary of employee. Let HRA be 10 % of basic pay and TA be 5% of basic
pay. Let employee pay professional tax as 2% of total salary. Calculate net salary payable
after deductions.

Problem Description:

The program takes as input salary of an employee given his basic pay from user and
Calculate net salary of employee using HRA, TA, and TAX.

Theory:

Python is an interpreted high-level general-purpose programming language. Its design


philosophy emphasizes code readability with its use of significant indentation. Its
language constructs as well as its object-oriented approach aim to help programmers write
clear, logical code for small and large-scale projects. This langauge is created by Guido
Van Rossom and first released in 1991.

Operators:

Operators are the constructs which can manipulate the value of operands. Consider the
expression 4 + 5 = 9, Here 4 and 5 are operands and + is called operator.

Python’s Arithmetic Operators:-


Python’s Input function:-

Developers often have a need to interact with users, either to get data or to provide some sort
of result.

 Python provides us with inbuilt function to read the input from the keyboard.

 input ( prompt )

input ( ) : This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether user entered a string or
a number or list.

If the input provided is not correct then either syntax error or exception is raised by
python.

# Python program showing# A use of input()

val = input("Enter your value: ")

print(val)

Algorithm:

1. Start.
2. Accept the input as basic salary.
3. calculate hra = basic_pay*10/100
4. calculate ta = basic_pay*5/100
5. calculate salary = basic_pay + hra + ta
6. calculate professional_tax = salary*2/100
7. calculate net salary = salary - professional_tax
8. print net salary
9. Stop.
Flowchart:

Conclusion:-

Questions:-

1. Explain different data types supported by python.


2. What is Problem? List down steps in problem solving.
3. What is operator? Explain different types of operator.
4. What is Algorithm? Explain its characteristics.
Assignment No. 02
Title: To accept N numbers from user. Compute and display maximum in list,
minimum in list, sum and average of numbers.

Problem Description:

The program accept N input numbers from user and perform following operation on list
compute and display maximum number in list, minimum number in list, sum and average
of numbers.

Theory:

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may contain Data
Types like Integers, Strings, as well as Objects. Lists are also very useful for implementing
stacks and queues. Lists are mutable, and hence, they can be altered even after their
creation.
In Python, list is a type of container in Data Structures, which is used to store multiple
data at the same time. Unlike Sets, the lists in Python are ordered and have a definite
count. The elements in a list are indexed according to a definite sequence and the
indexing of a list is done with 0 being the first index. Each element in the list has its
definite place in the list, which allows duplicating of elements in the list, with each
element having its own distinct place and credibility.
Creating a List:

Lists in Python can be created by just placing the sequence inside the square brackets [].
Unlike Sets, list doesn’t need a built-in function for creation of list. A list may contain
duplicate values with their distinct positions and hence, multiple distinct or duplicate
values can be passed as a sequence at the time of list creation.

# Python program to demonstrate #


Creation of List

# Creating a List List


= [] print("Blank List:
") print(List)

Output:
Blank List:[]
# Creating a List with #
mixed type of values

# (Having numbers and strings)

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

print("\nList with the use of Mixed Values: ")print(List)

Output:

List with the use of Mixed Values:

[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

Adding Elements to a List

Elements can be added to the List by using built-in append() function. Only one
element at a time can be added to the list by using append() method, for addition of
multiple elements with the append() method, loops are used. Tuples can also be added
to the List with the use of append method because tuples are immutable. Unlike
Sets, Lists can also be added to the existing list with the use of append() method.
append() method only works for addition of elements at the end of the List, for
addition of element at the desired position, insert() method is used. Unlike
append() which takes only one argument, insert() method requires two
arguments(position, value).Other than append() and insert() methods, there’s one
more method for Addition of elements, extend(), this method is used to add multiple
elements at the same time at the end of the list.

Built-in functions with List


max() - return maximum element of given list
min() - return minimum element of given list
sum() - Sums up the numbers in the list

COMPUTE AND DISPLAY AVERAGE OF NUMBERS


Average - Average is the sum of elements divided by the number of elements.

Algorithm:
Step 1: Start.
Step 2: Read the number of element in the list.
Step 3: Read the number n until loop in range num.
Step 4: Append the all element in list.
Step 5: Calculate sum (sm=sum(lst)).
Step 6: Calculate average avg=sm/num.
Step 7: Print Maximum element in the list value max(lst).
Step 8: Print Minimum element in the list value min(lst).
Step 9: Print Sum of elements in given list is sum(lst).
Step 10: Print Average of elements in given list is avg.
Step 11: Stop.

Flowchart:

Conclusion:-

Questions:-

1. What is identifier? List Rules to define identifier.


2. Explain selection/ conditional statements in Python.
3. Explain while loop with flow chart.
4. Explain for loop with example.
Assignment No. 03
Title: To accept student’s five courses marks and compute his/her result. Student is
passing if he/she scores marks equal to and above 40 in each course. If student scores
aggregate greater than 75%, then the grade is distinction. If aggregate is 60>= and <75 then
the grade if first division. If aggregate is 50>= and <60, then the grade is second division.
If aggregate is 40>= and <50, then the grade is third division.

Problem Description:

The program is to accept student’s five courses marks and compute his/her result. Student is
passing if he/she scores marks equal to and above 40 in each course. If student scores
aggregate greater than 75%, then the grade is distinction. If aggregate is 60>= and <75 then
the grade if first division. If aggregate is 50>= and <60, then the grade is second division. If
aggregate is 40>= and <50, then the grade is third division.

Theory:

Decision Making in Python

There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the
next block of code.
Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:

 if statement
 if..else statements
 nested if statements
 if-elif ladder

1. if statement

if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is
true then a block of statement is executed otherwise not.
Syntax:

if condition:

# Statements
to execute if#
Condition is
true

Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements below it
otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:

if
condit
ion:
state
ment1
statement2

# Here if the condition is true, if block


# will consider only
Flowchart:
statement1 to be inside# its
block.

Example:

# python program to illustrate If statement i = 10

if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
Output:
I am Not in if

As the condition present in the if statement is false. So, the block below the if statement is
not executed.

2. if- else

The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.

Syntax:

if (condition):
# Executes
this block
if#
condition
is true
else: Chart:
Flow

# Executes
this block
if#
condition
is false
Example:

# python program to illustrate If else statement #!/usr/bin/python

i = 20;
if (i < 15):
print ("i is smaller than 15") print ("i'm in if Block")
else:
print ("i is greater than 15") print ("i'm in else Block")
print ("i'm not in if and not in else Block")

Output:

i is
greate
r than
15i'm
The block of code following the else statement is executed as the condition present in the
ifin else is false after call the statement which is not in block(without spaces).
statement
Block
3. nested-if
i'm not in if and not in else Block
A nested if is if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement. Yes, Python allows us to nest if statements
within if statements. i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1):
# Executes when
condition1 is trueif
(condition2):
# Executes when
condition2 is true# if
Block is end here
# if Block is end here
Flow chart:

Example:

# python program to illustrate nested If statement #!/usr/bin/python


i = 10
if (i == 10):
# First if statement if (i < 15):
print ("i is smaller than 15") # Nested - if statement
# Will only be executed if statement above # it is true
if (i < 12):
print ("i is smaller than 12 too") else:
print ("i is greater than 15")

Output:
i is smaller than 15
i is smaller than 12 too
4. if-elif-else ladder

Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed.

Syntax:

if (condition):
statement
elif (condition):
statement
.
.
else:
statement

Flow Chart:
Example:

# Python program to illustrate if-elif-else ladder #!/usr/bin/python

i = 20
if (i == 10):
print ("i is 10") elif (i == 15):
print ("i is 15") elif (i == 20):
print ("i is 20") else:
print ("i is not present")

Output:
i is 20

Algorithm:

Step 1: Start.
Step 2: Read the marks of five subjects.
Step 3: If any subject marks are less than 40 Step 4: Print grade is Fail.
Step 5: Calculate total marks Step 6: Calculate aggregate marks
Step 7: Print aggregate marks of subject
Step 8: If average greater than 75%, then the grade is distinction. Step 9: Print grade is
Distinction
Step 10: elif aggregate is 60>= and <75 then the grade is first division. Step 11: Print grade is
first division.
Step 12: elif aggregate is 50>= and <60, then the grade is second division. Step 13: Print
grade is second division.
Step 14: elif aggregate is 40>= and <50, then the grade is third division. Step 15: Print grade
is third division.
Step 16: Stop
Flowchart:

if (sub < 40)

Print grade is Fail.

Calculate total marks

Calculate aggregate marks

Print aggregate
marks of subject

if (avg >= 75) Print grade is


Distinction
Conclusion:-

Questions:-

1. Write a program to check whether given no is positive or negative.


2. Write a program to check whether given no is even or odd.
3. What is concept of infinite loop? Explain with example.
4. What is use of range function in python?
Assignment No. 04
Title: To accept a number from user and print digits of number in a reverse
order

Problem Description:

The program is to accept a number (e. g. Integer) and with separating the digit of
number will reverse the original number and display the reversed number.

Theory:

Here we read a number from user and reverse that number using some arithmetic
operations like mod (%) and floor division (//) to find each digit and build the
reverse of it.
The following python program reverses a given multi-digit number. In this
example, we simply print the digits in reverse order without removing zeros. For
redundant example, if the input number is "1000", the reversed
number displayed will be "0001" instead of "1".

Algorithm:

START
1. Read an input number using input() or raw_input().
2. Check whether the value entered is integer or not.
3. Check integer is greater than 0
4. Initialize a variable named reverse to 0
5. Find remainder of the input number by using mod (%) operator
6. Now multiply reverse with 10 and add remainder to it
7. Floor Divide input number with 10
8. At some point input number will become 0
9. Repeat steps 5, 6, 7 until input number is not greater than zero
10. Print the variable reverse.
STOP
Flowchart:

Conclusion:-

Questions:
1. Explain input function in detail.
2. Explain print function in detail.
3. Explain how while loop works.
4. Explain advantages of Iterative structure.
Assignment No. 05
Title: Write a python program that accepts a string from user and perform
following string operations- i. Calculate length of string ii. String reversal iii.
Equality check of two strings iii. Check palindrome ii. Check substring

Theory:

Strings in Python
Python string is the collection of the characters surrounded by single
quotes, double quotes, or triple quotes. The computer does not understand
the characters; internally, it stores manipulated character as the combination
of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we
can say that Python strings are also called the collection of Unicode
characters.
In Python, strings can be created by enclosing the character or the
sequence of characters in the quotes. Python allows us to use single quotes,
double quotes, or triple quotes to create the string.

We can access a string using indexing. In a string each character is assigned


with a unique index value which starts from 0. A string can be written in both single
quotes and double quotes. Example : 'Hello World'
"Hello World"

Program:
print(“Hello”)
print(‘Hello’)

Output:
Hello
Hello

Program
A=”Hello”
print(A)

Output
Hello

Program
A=”””Hello,
How are you,
Happy new year”””
print(a)

Output
Hello,
How are you,
Happy new year
Python allows negative indexing as well.
Example : -1, -3, -5.
Where -1 refers to the last index, -2 refers to second last index and so on.
Printing here can be done by placing the string in single or double quotes after print.

print("Hello World")

Concatenation
A string in python is immutable i.e. it can not be changed once defined. But
concatenation is still possible

Program

s=’Hello World’
s=s+”Example”
print(s)

Output

Hello WorldExample

Using Join() method also we can concatenate string

Program

var1=”Hello”
var2=”World”
print(“”.join([var1,var2]))

Output
HelloWorld

Program
var1=”Hello”
var2=”World”
var3=“”.join([var1,var2])
print(var3)

Output
Hello World

Repetition
This is a unique property of strings in Python programming language. When a string
is multiplied with an integer, the characters of string are multiplied the same
number of times.

Syntax : string * integer


Program
s=”k”
s=s*5
print(s)

Output:
Kkkkk

Slicing
Slicing is done in Python to select or display the desired number of characters in a
string. It is done with the help of symbol ':'

Syntax : String[ index: ]

Program
S=”HelloWorld”
S=S[2:]
print(S)

Output:
llo World

All the characters from and after second index is selected

Program
S=”Hello World”
S=S[1:8]
Print(S)

output
ello Wo

Characters between index number 1 and 8 are selected


Length of a string can be calculated using the len function.
Syntax : len("string")
len("Hello World")
It will return 11.

Deleting / updating from a String:

In Python, Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not
supported

Program

String1=”Hello, I’m a coder”


print(“Initial String:”)
print(String1)

String1[2]=’p’
Print(“\nUpdating character at 2nd Index:”)
Print(String1)
Output:
Initial String:
Hello, I'm a coder
Traceback (most recent call last):
File "e:\VLAB\python\programs\a.py", line 51, in
String1[2] = 'p'
TypeError: 'str' object does not support item assignment

Conclusion:

Questions:
1. What is string?
2. Which operations can be perform on string? Explain in detail.
3. What is Slicing?
4. How strings can be defined in python?
Assignment No. 6
Title: Create class EMPLOYEE for storing details (Name, Designation,
gender, Date of Joining and Salary). Define function members to compute a)
total number of employees in an organization b) count of male and female
employee c) Employee with salary more than 10,000 d) Employee with
designation “Asst. Manager”.

Problem Description:

Program is to create a class named as Employee with some details as Name, Designation,
Gender, Date of Joining and Salary. Next program defines function members which
compute total number of employees in an organization, count of male and female employee,
employee with salary more than 10,000 and employee with designation “Asst. Manager”.

Theory:

Class: A Class is like an object constructor, or a "blueprint" for creating objects.


A class is a code template for creating objects. Objects have member variables
and have behavior associated with them. In python a class is created by the
keyword class.
Example: Create a class named MyClass, with a property named x:

class MyClass: x = 5

Object: An object is created using the constructor of the class. This object will
then be called the instance of the class.
Syntax: Instance =class(arguments)
Example: Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)
The init () Function:
To understand the meaning of classes we have to understand the built-in
init () function.
All classes have a function called init (), which is always executed when the
class is being initiated.
Use the init () function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Example: Create a class named Person, use the init () function to assign
values forname and age:
class Person:
def init (self, name, age):
self.name =
name self.age
= age

p1 = Person("John", 36)
print(p1.na
me)
print(p1.age
)

Object Methods:
Objects can also contain methods. Methods in objects are functions that belong to
the object.
Create a method in the Person class:
Example: Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def init (self, name, age):
self.name =
name self.age
= age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John",
36) p1.myfunc()

The self-parameter:
The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class. It does not have to be named self,
you can call it whatever you like, but it has to be the first parameter of any
function in the class:
Example: Use the words mysillyobject and abc instead of self:

class Person:
def init (mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36) p1.myfunc()

Algorithm:
START
Step 1: Create a class Employee with attributes Name,
Designation, gender, Date of Joining and Salary
Step 2: Define variables and assign values
Step 3: Define init () function and assign values to object
properties. Step 4: Define method functions with required conditions
Step 5: Define main ()
function Step 6: Enter your
choice
Step 7: Display / Print required results using print () function.
STOP

Flowchart:

Conclusion:

Questions:
1. What is class? Explain in detail.
2. What is object? How to create object.
3. What is data abstraction & encapsulation?
4. What is Polymorphism? Explain in detail.
Assignment No.7

Title: Write a program to count total characters in file, total words in file, total lines
in file and frequency of given word in file.
Theory:
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk). Since, random
access memory (RAM) is volatile which loses its data when computer is turned off,
we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are
done, it needs to be closed, so that resources that are tied with the file are freed. Hence,
in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

Opening a file
Python has a built-in function open () to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory

>>> f = open("C:/Python33/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to
read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in
text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from
the file. On the other hand, binary mode returns bytes and this is the mode to be used
when dealing with non-text files like image or exe files.
Python File Modes
'r' Open a file for reading. (default)

w' Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation
fails.

'a' Open for appending at the end of the file without truncating it. Creates
a new file if it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

Closing a File
When we are done with operations to the file, we need to properly close it. Closing a
file will free up the resources that were tied with the file and is done using the
close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not
rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')

# perform file operations f.close()

Split the string into a list containing the words by using split function (i.e.
string.split()) in python with delimiter space.

string_name.split(separator) method is used to split the string by specified


separator(delimiter) into the list. If delimiter is not provided then white
space isa separator.
For example:

Code : str='This is my
book'str.split()
Output: ['This', 'is', 'my', 'book']
Algorithm:

Step 1: Start
Step 2: Declare and Initialize in variables lines, words and chars Step 3: Input
as a file name
Step 4: Open the file
Step 5: Read each line from the file to count the words.
Step 6: Split each line in to words and spaces and also count them Step 7: Print the
number of lines, spaces, characters and words.
Step 8: Stop

Flowchart:

Conclusion:

Questions:-
1. Explain types of files.
2. How to open & Close file.
3. How to read & write file.
4. What is file path.

You might also like