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

Lab Manual Updated

Uploaded by

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

Lab Manual Updated

Uploaded by

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

Bharati Navale

Smt. Kashibai Vidyapeeth's


CollegeCollege of Engineering
of Engineering, Vadgaon Pune-
Lavale Pune-412115
41.
Department of Computer Engineering

Lab Manual Programming and Problem Solving


for Semester-I

NAME OF THE STUDENT:...................................................

ROLL NO:........................................................................

BRANCH:.........................................................................

SECTION:.........................................................................

YEAR:..............................................................................

SEMESTER: .....................................................................


Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.
PPS LAB Objectives:
Understand the basic concept of Python Programming, and its different modules that include
conditional and looping expressions, Arrays, Strings, Functions, and Structures.
Acquire knowledge aboutthe basic concept of writing aprogram.
Role of constants, variables, identifiers, operators, type conversion and other building blocks of
Python Language.
Use of conditional expressions and looping statements to solve problems associated with conditions
and repetitions.
Role of Functions involving the idea of modularity.
Programming using Python tool in Linux.

Purpose of the Labs:


We believe that people learn some things best by doing them. The labs for PPS provide
time to do computer science under the direction of an instructor who will be serving as a
facilitator during the lab session. This means that the instructor will not solve your
problems or show you how to complete the activities. The instructor may provide helpful
hints, ask additional questions, ask you to explain a solution, ask how you obtained a
solution, or facilitate discussions about observations, experiments, results, discoveries, and
other topics that arise.
Some lab activities will ask you to develop solutions to problems, program solutions in
Alice or Python, and test the programs. Other activities will involve using programs we
give you to illustrate important concepts in Computer Science. You will be required to make
observations, form and test hypotheses, and use the results of your testing to change aspects
of your programs.
The lab session format will provide opportunities for discussing your observations,
experiments, discoveries, and solutions to problems. Discussions may take place with your
lab partner, your instructor, or other lab groups. The lab materials you hand in to your
instructor will provide the opportunity to communicate in writing about the computer
science being done.

Goals we will make progress towards:


• Understanding that computer science is a way of thinking or asking questions rather than
just a set of facts about technology.
• Formulating, analyzing, and solving problems using the concept of an algorithm. This
includes the ability to solve problems with a sense of imagination and creativity.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


• Communicating effectively in both oral and written form.
• Understanding what computer science is, what its connections are to other subjects, and
what are some of its important questions.
• Having fun !!!
Student responsibilities:
You are responsible for preparing for the labs (reading the materials in the first portion of each lab),
attending the lab sessions, completing the lab assignments (which may require time outside of the
lab sessions), and handing in required materials on time. In particular:
Lab reports consist of one Lab Worksheet for each team of two students. All information and
answers requested during the lab will be filled in on the Worksheet; additional responses and
program printouts must be attached to the back of the lab, in the order requested. All lab team
members are responsible for the lab, and the grade earned by the lab will be assigned to all team
members.

LAB PREPARATION:

The remainder of this lab manual contains some helpful information on the software and hardware
systems you will be using this semester. This lab manual should be at your side whenever you are
logged in and doing work for this course, either in a lab or for a homework assignment or for any
other reason.

Software Tool Installation:


Python is pre-installed on most Unix systems, including Linux and MAC OS X.
But for in Windows Operating Systems , user can download from the
https://www.python.org/downloads/
from the above link download latest version of python IDE and install, recent version is
3.4.1 but mostly we can see pre-installed version 2.7.7 only.

The Python Ecosystem


The Python programming environment has two
broad subject areas:
• The language itself
• The extension packages
We can further subdivide the extension packages
into:
• The standard library of packages

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


• The Python ecosystem of yet more extension packages,

Fig. Python Ecosystem

Anaconda Installation:

Follow following steps carefully,

• Step 1 — Retrieve the Latest Version of Anaconda


https://www.anaconda.com/distribution/
• Step 2 — Download the Anaconda
$cd /tmp
$curl -O https://repo.anaconda.com/archive/Anaconda3-2019.03-Linux-x86_64.sh
• Step 3 — Verify the Data Integrity of the Installer
$sha256sum Anaconda3-2019.03-Linux-x86_64.sh
• Step 4 — Run the Anaconda Script
$bash Anaconda3-2019.03-Linux-x86_64.sh

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


You’ll receive the some output to review the license agreement by pressing ENTER until you reach
the end.
• Step 5 — Activate Installation
$conda list
• Step 6 — Set Up Anaconda Environments
$conda create --name my_env python=3
• Step7 - Activate the new environment like so:
$conda activate my_env
• Step8 - Launch Anaconda
$anaconda-navigator

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.01

Title:

To calculate salary of an employee given his basic pay (take as input from user). Calculate 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 salary payable after deductions.

Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To Calculate salary payable of employee

Outcomes:
1. Students will be able to demonstrate calculations of employee salary.

2. Students will be able to demonstrate different Operator & formulas.

3. Students will be able to demonstrate different Operations on Available data of employee salary.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:
Python Basics:
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van
Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its
notable use of significant whitespace.
What is Basic salary?
Basic salary is the base income of an individual. It is a fixed part of one's compensation package.
A basic salary depends on the employee’s designation and also the industry in which the employee
works.
Basic salary is the amount paid to an employee before any extras are added or taken off, such as
reductions because of salary sacrifice schemes or an increase due to overtime or a bonus.
Allowances, such as internet for home-based workers or contributions to phone usage, would also
be added to the basic salary.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Gross salary:
Gross salary is the amount calculated by adding up one's basic salary and allowances, before
deduction of taxes and other deductions. It includes bonuses, over-time pay, holiday pay, and other
differentials.
Gross Salary = Basic Salary + HRA + Other Allowances

Allowances:
An allowance is an amount received by the employee for meeting service requirements. Allowances
are provided in addition to the basic salary and vary from company to company. Some common
types of allowances are shown below:

• HRA or House Rent Allowance: It is an amount paid out to employees by companies for
expenses related to rented accommodation.
• Leave Travel Allowance (LTA): LTA is the amount provided by the company to cover
domestic travel expenses of an employee. It does not include the expenses for food,
accommodation, etc. during the travel.
• Conveyance Allowance: This allowance is provided to employees to meet travel expenses
from residence to work.
• Dearness Allowance: DA is a living allowance paid to employees to tackle the effects of
inflation. It is applicable to government employees, public sector employees, and pensioners
only.
• Other such allowances are the special allowance, medical allowance, incentives, etc.

HRA:
HRA received is not fully exempt from tax. HRA that you can claim is the lowest of the following:

• The total amount received as the HRA from the employer in the financial year.
• Actual rent paid in the year – 10% of the basic salary in the year.
• 50% of the annual basic salary if staying in a metro city or 40% of the annual basic salary if
staying in a non-metro city.
Sample Example:
Python program to get employee wages and number of days worked from user and find Basic
Pay, DA, HRA, PF and Net Pay.
(Note HRA, DA and PF are 10%,5%and 12% of basicpay respectively.)
Sample Input 1:
300
30
Sample Output 1:
Basic Pay:3000

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


DA: 150
HRA:300
PF:360
Net Pay: 3090

Solution:
days=float(input("Enter No Days Present:"))
wages=float(input("Enter wages per Day:"))
basic=wages*days;
HRA=basic*0.1;
DA=basic*0.05;
PF=basic*0.12;
netsalary=basic+HRA+DA-PF;
print("\nBasic:%lf \nHRA:%lf \nDA:%lf \nPF:%lf \nNet Salary:%lf" %
(basic,HRA,DA,PF,netsalary));

Calculate Gross Salary Python Program

This python program is using if else statement to compute the gross salary from basic salary input.

Here we have two different logic's to compute gross salary. so we are using if and else statements.

# function computes the gross salary from basic salary.

def calcualte_gross_salary(basic_salary):
hra = 0;
da = 0;
# salary is less than 2500, hra and da is calculated using this logic, otherwise else logic.
if (basic_salary < 2500):
hra = (basic_salary * 10) / 100;
da = (basic_salary * 90) / 100;
else:
hra = 1000;
da = (basic_salary * 95) / 100;

return (basic_salary + hra + da);

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


if __name__ == "__main__":
# Type casting from input string into float value.
basic_salary = float(input("Enter basic salary: "));
gross_salary = calcualte_gross_salary(basic_salary);
print("Gross Salary is: %f" % gross_salary);

Output:

$ python gross_salary.py

Enter basic salary: 3400


Gross Salary is: 7630.000000
$ python gross_salary.py
Enter basic salary: 2000
Gross Salary is: 4000.000000

Conclusion:

Thus, we have successfully understood concept of salary calculation formulas and performed salary
calculation in python.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.02

Title:

To accept N numbers from user. Compute and display maximum in list, minimum in list,
sum and average of numbers.

Objective:

Understand basic concepts of python programming language and try to solve list concepts related
programs.

Problem Statement:

To Find maximum and minimum number, sum,average from given list.

Outcomes:

1. Students will be able to understand basic concept of list in python.

2. Students will be able to demonstrate different Operator & formulas on given list.

3. Students will be able to demonstrate different types of list examples easily.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

What is list?
Python offers a range of compound datatypes often referred to as sequences. List is one of the most
frequently used and very versatile datatype used in Python.

How to create a list?


In Python programming, a list is created by placing all the items (elements) inside a square bracket

[ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Syntax:

# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?


There are various ways in which we can access the elements of a list.

List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
my_list = ['p','r','o','b','e']

# Output: p

print(my_list[0])

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing

# my_list[4.0]

# Nested List

n_list = ["Happy", [2,0,1,5]]

# Nested indexing

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


# Output: a

print(n_list[0][1])

# Output: 5print(n_list[1][3])

Fig: List Indexing

In this experiment, we will learn how to find the maximum and minimum number in a python list.
Python list can hold items of any data types. All items are separated by a comma and placed inside a
square bracket. We can access any item by using its index. The index starts at 0. The index for the
first element is 0, the index of the second element is 1 etc.

Here will show you how to find the maximum and minimum number in a list using a loop. All the
numbers will be entered by the user. The user will enter the list items one by one and our program
will read them.

First, we will ask the user to enter the total number count. Then using a for loop, we will read each
number and append them to the list. Finally, again using one more for loop, we will calculate the
maximum and minimum number and print out the result. Let’s take a look into the following sample
program first.

Explanation :
1. Create one empty list my_list. We are using one empty square bracket to create the empty list.
This is a list without any items.

2. Get the total number of elements the user is going to enter and save it in the count variable. This
is required because we will ask the user to enter each number one by one. If the value of count is 4,
the user will have to enter four numbers to add to the list.

3. Using a for loop, get the numbers and append it to the list my_list. For appending a number,

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


append method is used. This method takes the value we are adding as the parameter. For reading the
value, we are using the input method. This method will read the value from the user. The return
value of this method is of string type. Wrapping it as int() will convert the entered value to an
integer.
4. Print the list to the user.

5. Create two variables to hold the minimum and maximum number. We are assigning the first
element of the list to both of these variables first. We will update these variables on the next step.
On this step, we are assuming that the minimum and maximum value of the list is equal to the first
element of the list. We will compare this value with all other elements of the list one by one and
update them if required.

6. Run one for loop on the list again. For each number, check if it is less than the minimum number.
If yes, assign the minimum value holding variable to this number. Similarly, update the maximum
value if the number is more than the current maximum.

7. After the list is completed reading, print out both maximum and minimum numbers.

Algorithm:
1.Create an empty list named l
2.Read the value of n
3.Read the elements of the list until n
4.Assign l[0] as maxno
5.If l[i]>maxno then set maxno=l[i]
6.Increment i by 1
7.Repeat steps 5-6 until i<n
8.Print the value of maximum number
Program:
l=[]
n=int(input("enter the upper limit"))
for i in range(0,n):
a=int(input("enter the numbers"))
l.append(a)
maxno=l[0]
for i in range(0,len(l)):
if l[i]>maxno:
maxno=l[i]
print("The maximum number is %d"%maxno)

Conclusion: Thus, we have studied and performed operation on list in python.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


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

Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To calculate percentage,aggregate of given five subjects in python.

Outcomes:

1. Students will be able to understand basic concept of percentage calculation in python.

2. Students will be able to demonstrate different Operator & formulas for grade and sum.

3. Students will be able to demonstrate different Operations by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

In this assignment user has to enter five different marks for five subjects. Next, it will find the Total,
average, and Percentage of those Five Subjects. For this, we are using the arithmetic operator to
perform arithmetic operations.

Problem Description
The program takes in the marks of 5 subjects and displays the grade.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Problem Solution

1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.

Following flowchart will show basic idea about sum,average calculation in python , same logic we
can apply fow percentage calculation.

Fig: Flowchart for underating average, sum calculation.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Program/Source Code

Here is source code of the Python Program to take in the marks of 5 subjects and display the grade.
The program output is also shown below.

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")

Conclusion: Thus, we have performed how to calculate percentage and grade, average in python.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.04

Title:

To check whether input number is Armstrong number or not. An Armstrong number is an integer
with three digits such that the sum of the cubes of its digits is equal to the number itself.
Ex. 371.

Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To proove that given number is armstrong number in python.


Outcomes:

1. Students will be able to understand basic concept of Armstrong number logic.

2. Students will be able to demonstrate different integer number for identifying armstrong number.

3. Students will be able to demonstrate different Operations on any integer by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:
To understand this example, you should have the knowledge of following python programming
concept with basic topics:

• Python if...else Statement


• Python while Loop

What are if...else statement in Python?


Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else statement is used in Python for decision making.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Python if Statement Syntax
if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.

If the text expression is False, the statement(s) is not executed.


In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Example: Python if Statement

# If the number is positive, we print an appropriate message


num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number
itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.

Source Code: Check Armstrong number (for 3 digits)


# Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Here, we ask the user for a number and check if it is an Armstrong number.

We need to calculate the sum of cube of each digit. So, we initialize the sum to 0 and obtain each
digit number by using the modulus operator %. Remainder of a number when it is divide by 10 is
the last digit of that number. We take the cubes using exponent operator.

Finally, we compare the sum with the original number and conclude that it is Armstrong number if
they are equal.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Approach :
1. Read an input number using input() or raw_input().
2. Check whether the value entered is an integer or not.
3. Check input_num is greater than 0.
4. Initialize a variable named arm_num to 0.
5. Find remainder of the input number by using the mod (%) operator to get each digit in
the number.
6. Now cube each digit and add it to arm_num.
7. Floor Divide the number by 10.
8. Repeat steps 5. 6. 7 until the input_num is not greater than 0.
9. If input_num is equal to arm_num, print number is ARMSTRONG.
10. When input_num is not equals to arm_num, the number is NOT an Armstrong
number.

Sample Example:
input_num = (input("Enter any number: "))
digit_len = len(str(input_num))try:
arm_num = 0
val = int(input_num)
while val > 0:
reminder = val % 10
arm_num += reminder ** digit_len
val //= 10if int(input_num) == arm_num:
print(input_num, 'is an ARMSTRONG number')
else:
print(input_num, 'is NOT an armstrong number')except ValueError:
print("That's not a valid number, Try Again !")

Conclusion:

Thus, we have studied and performed armstrong number concept in python successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.05

Title:

To accept the number and Compute a) square root of number, b) Square of number, c) Cube of
number d) check for prime, d) factorial of number e) prime factors
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform number different operation on given number in python.

Outcomes:

1. Students will be able to understand basic concept of number operations logic.

2. Students will be able to demonstrate different integer number for identifying number operations.

3. Students will be able to demonstrate different Operations on any integer by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:
To understand this experiment, you should have the knowledge of following Python programming
topics:
Python Input, Output and Import
Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output
operations respectively. Let us see the output section first.
Python Output Using print() function

We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given below.
print('This sentence is output to the screen')
# Output: This sentence is output to the screen

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


a=5
print('The value of a is', a)
# Output: The value of a is 5
Python Data Types
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.

Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.
For example:
>>> 2+35

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.

Python math function | sqrt()

sqrt() function is an inbuilt function in Python programming language that returns the square root
of any number.
yntax:
math.sqrt(x)

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Parameter:
x is any number such that x>=0

Returns:
It returns the square root of the number passed in the parameter.
Example:

# Python3 program to demonstrate the


# sqrt() method
# import the math module
import math
# print the square root of 0
print(math.sqrt(0))
# print the square root of 4
print(math.sqrt(4))
# print the square root of 3.5
print(math.sqrt(3.5))

Square of a Number

In this article, we will show you, How to write a Python Program to Calculate Square of a Number
using Arithmetic Operators, and Functions with example.
allows the user to enter any numerical value. Next, it will finds the square of that number using
Arithmetic Operator.
Example:
# Python Program to Calculate Square of a Number
number = float(input(" Please Enter any numeric Value : "))
square = number * number
print("The Square of a Given Number {0} = {1}".format(number, square))

Cube of a Number
we will show you, How to write a Python Program to Calculate Cube of a Number using Arithmetic
Operators, and Functions with example.
Example:
# Python Program to Calculate Cube of a Number
number = float(input(" Please Enter any numeric Value : "))
cube = number * number * number
print("The Cube of a Given Number {0} = {1}".format(number, cube))

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Prime Number:
A positive integer greater than 1 which has no other factors except 1 and the number itself is called
a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not
prime (it is composite) since, 2 x 3 = 6.
Given a positive integer N. The task is to write a Python program to check if the number is prime or
not.
Definition: A prime number is a natural number greater than 1 that has no positive divisors other
than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.
Examples :
nput: n = 11
Output: true

Input: n = 15
Output: false

Input: n = 1
Output: false

The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a
for loop and for every number check if it divides N. If we find any number that divides, we return
false. If we did not find any number between 2 and N/2 which divides N then it means that N is
prime and we will return True.
Below is the Python program to check if a number is prime:

# Python program to check if


# given number is prime or not

num = 11
# If given number is greater than 1
if num > 1:

# Iterate from 2 to n / 2
for i in range(2, num//2):

# If num is divisible by any number between


# 2 and n / 2, it is not prime
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")

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Factorial Number:

The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for
negative numbers and the factorial of zero is one, 0! = 1.

factorial() in Python
Not many people know, but python offers a direct function that can compute the factorial of a
number without writing the whole code for computing factorial.
Naive method to compute factorial
# Python code to demonstrate naive method
# to compute factorial
n = 23
fact = 1

for i in range(1,n+1):
fact = fact * i

print ("The factorial of 23 is : ",end="")


print (fact)

Using math.factorial()
This method is defined in “math” module of python. Because it has C type internal implementation,
it is fast.
math.factorial(x)
Parameters :
x : The number whose factorial has to be computed.
Return value :
Returns the factorial of desired number.
Exceptions :
Raises Value error if number is negative or non-integral.

# Python code to demonstrate math.factorial()


import math

print ("The factorial of 23 is : ", end="")


print (math.factorial(23))

Conclusion: Thus , in this experiment we have studied and performed mathematical operation on
given number.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.06

Title:

To input binary number from user and convert it into decimal number.
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform number conversion in python.


Outcomes:

1. Students will be able to understand basic concept of number conversion.

2. Students will be able to demonstrate different integer number for identifying number operations.

3. Students will be able to demonstrate different Operations on any integer by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:
The number systems refer to the number of symbols or characters used to represent any numerical
value. The number system that you typically use every day is called decimal. In the decimal system,
you use ten different symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. With these ten symbols, you can
represent any quantity. Binary, hexadecimal, and octal refer to different number systems.

When you run out of symbols, you go to the next digit placement. In the decimal system, to
represent one higher than 9, you use 10 meaning one unit of ten and zero units of one. However, it
is different in other number systems. For example, when you consider a binary system which only
uses two symbols: 0 and 1, when you run out of symbols, you need to go to the next digit
placement. So this is how you will count in binary: 0, 1, 10, 11, 100, 101 and so on.

Let's check out some of the number systems in more detail in the next sections.

Convert to Binary Number


Binary integers are the number represented with base two. Which means in the binary number

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


system, there are only two symbols used to represent numbers: 0 and 1. When you count up from
zero in binary, you run out of symbols more quickly: 0, 1, ???

Furthermore, there are no more symbols left. You do not go to the digit 2 because 2 doesn't exist in
binary. Instead, you use a special combination of 1s and 0s. In a binary system, 1000 is equal to 8 in
decimal. In binary, you use powers of two, which means 8 is basically: (1(2^3)) + (0(2^2)) +
(0(2^1)) + (0(2^0))= 8. The position of the 1 and 0 defines the power to which 2 is to be raised to.

Let's see this with a more complex example to make it clear:

Binary Number = 1001111


Decimal value = (1*(2^6)) + (0*(2^5)) + (0*(2^4)) + (1*(2^3)) + (1*(2^2)) + (1*(2^1)) + (1*(2^0))
= 79

In Python, you can simply use the bin() function to convert from a decimal value to its
corresponding binary value.

And similarly, the int() function to convert a binary to its decimal value. The int() function
takes as second argument the base of the number to be converted, which is 2 in case of binary
numbers.
Convert Binary to Decimal in Python
To convert binary to decimal number in python, you have to ask from user to enter a number in
binary number system to convert that number into decimal number system as shown in the program
given here.
Approach:

The idea is to extract the digits of given binary number starting from right most digit and keep a
variable dec_value. At the time of extracting digits from the binary number, multiply the digit with
the proper base (Power of 2) and add it to the variable dec_value. At the end, the variable dec_value
will store the required decimal number.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


For Example:
If the binary number is 111.
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7

Below diagram explains how to convert ( 1010 ) to equivalent decimal value:

Python Programming Code to Convert Binary to Decimal


Following python program ask from user to enter binary number to convert it into decimal number:
# Python Program - Convert Binary to Decimal

print("Enter 'x' for exit.")


binary = input("Enter number in Binary Format: ")
if binary == 'x':
exit();
else:
decimal = int(binary, 2);

print(binary,"in Decimal =",decimal)

Here is the sample run of the above Python program shows how to convert binary number to
decimal number:

b_num = list(input("Input a binary number: "))


value = 0

for i in range(len(b_num)):
digit = b_num.pop()
if digit == '1':
value = value + pow(2, i)
print("The decimal value of the number is", value)

Conclusion: Thus in this experiment we have studied and performed number conversion in python
successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.07

Title:

To accept a number from user and print digits of number in a reverse order.
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform number in reverse order as per user input in python.


Outcomes:

1. Students will be able to understand basic concept of number reverse order logic.

2. Students will be able to demonstrate different integer number for identifying number operations.

3. Students will be able to demonstrate different Operations on any integer by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

In this assignment we are going to perform program to reverse a number in python allows the user
to enter any positive integer and then, that number is assigned to variable Number.

Next, Condition in the While loop will make sure that, the given number is greater than 0
From the above example, User Entered value: Number = 1456 and Reverse = 0
First Iteration
Reminder = Number %10
Reminder = 1456%10 = 6
Reverse = Reverse *10 + Reminder
Reverse = 0 * 10 + 6 = 0 + 6 = 6
Number = Number //10
Number = 1456 //10 = 145

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Second Iteration
From the first Iteration the values of both Number and Reverse has been changed as: Number = 145
and Reverse = 6
Reminder = Number % 10
Reminder = 145 % 10 = 5
Reverse = Reverse *10+ Reminder = 6 * 10 + 5
Reverse = 60 + 5 = 65
Number = Number //10 = 145 //10
Number = 14
Third Iteration

From the Second Iteration of Python reverse a Number program, the values of both Number and
Reverse has been changed as: Number = 14 and Reverse = 65

Reminder = Number %10

Reminder = 14%10 = 4

Reverse = Reverse *10+ Reminder = 65 * 10 + 4

Reverse = 650 + 4 = 654

Number = Number //10 = 14//10

Number = 1

Fourth Iteration

From the Second Iteration the values of both Number and Reverse has been changed as: Number =
1 and Reverse = 654

Reminder = Number %10

Reminder = 1 %10 = 1

Reverse = Reverse *10+ Reminder = 654 * 10 + 1

Reverse = 6540 + 1 = 6541

Number = Number //10 = 1//10

Number = 0

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Here, For the next iteration Number = 0 so, the while loop condition will fail

Problem Solution

1. Take the value of the integer and store in a variable.


2. Using a while loop, get each digit of the number and store the reversed number in another
variable.
3. Print the reverse of the number.
4. Exit.
Program/Source Code
Here is the source code of the Python Program to reverse a given number.
n=int(input("Enter number: "))

rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)

Program Explanation

1. User must first enter the value and store it in a variable n.


2. The while loop is used and the last digit of the number is obtained by using the modulus operator.
3. The last digit is then stored at the one’s place, second last at the ten’s place and so on.
4. The last digit is then removed by truly dividing the number with 10.
5. This loop terminates when the value of the number is 0.
6. The reverse of the number is then printed.
Runtime Test Cases
Case 1:

Enter number: 124


Reverse of the number: 421

Case 2:
Enter number: 4538
Reverse of the number: 8354

Python Program to Reverse a Number Using Functions

This program to reverse a number in python allows the user to enter any positive integer and then,
we are going to reverse a number using Python Functions

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Source Code:

# Python Program to Reverse a Number using Functions


def Reverse_Integer(Number):
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
return Reverse
Number = int(input("Please Enter any Number: "))
Reverse = Reverse_Integer(Number)
print("\n Reverse of entered number is = %d" %Reverse)

Conclusion: Thus in this experiment we have studied and performed reverse number conversion in
python successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.08

Title:

To accept list of N integers and partition list into two sub lists even and odd numbers.
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform odd and even from two different list in python.


Outcomes:

1. Students will be able to understand basic concept of even odd logic.

2. Students will be able to demonstrate list operations.

3. Students will be able to demonstrate different Operations on any integer by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below.

•Python Numbers

Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python. We can use the type() function to know which
class a variable or a value belongs to and the isinstance() function to check if an object belongs to a
particular class.

>>>a = 5

print(a, "is of type", type(a))

>>>a = 2.0

print(a, "is of type", type(a))

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


>>>a = 1+2j

print(a, "is complex number?", isinstance(1+2j,complex))

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as
characters between quotes, lists are defined by having values between square brackets [ ].

Lists are great to use when you want to work with many related values. They enable you to keep
data together that belongs together, condense your code, and perform the same methods and
operations on multiple values at once.
When thinking about Python lists and other data structures that are types of collections, it is useful
to consider all the different collections you have on your computer: your assortment of files, your
song playlists, your browser bookmarks, your emails, the collection of videos you can access on a
streaming service, and more.
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.

Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets

[ ].

>>> a = [1, 2.2, 'python']

We can use the slicing operator [ ] to extract an item or a range of itemsfrom a list.

Index starts form 0 in Python.

Example

a = [5,10,15,20,25,30,35,40]

# a[2] = ?

print("a[2] = ", a[2])

# a[0:3] = ?

print("a[0:3] = ", a[0:3])

# a[5:] =

print("a[5:] = ", a[5:])

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Given a list of numbers, write a Python program to count Even and Odd numbers in a List.

Example:

Input: list1 = [2, 7, 5, 64, 14]


Output: Even = 3, odd = 2

Input: list2 = [12, 14, 95, 3]


Output: Even = 2, odd = 2

Example 1: count Even and Odd numbers from given list using for loop
Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check
even numbers. If the condition satisfies, then increase even count else increase odd count.
Problem Solution

1. Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to check if the
element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a different one.
5. Display the elements in both the lists.
6. Exit.
Program Explanation

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop and store it in a list.
3. Another for loop is used to traverse through the elements of the list.
4. The if statement checks if the element is even or odd and appends them to separate lists.
5. Both the lists are printed.
Runtime Test Cases
Case 1:
Enter number of elements:5
Enter element:67
Enter element:43
Enter element:44
Enter element:22
Enter element:455
The even list [44, 22]
The odd list [67, 43, 455]

Case 2:
Enter number of elements:3
Enter element:23
Enter element:44

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Enter element:99
The even list [44]
The odd list [23, 99]

Program/Source Code
a=[]

n=int(input("Enter number of elements:"))


for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)

Conclusion:
Thus, in this experiment we have studied and performed operations on list successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.09

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
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform String operation in python.


Outcomes:

1. Students will be able to understand basic concept of string in python.

2. Students will be able to demonstrate different operations on string.

3. Students will be able to demonstrate different Operations on any string by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

A string is a list of characters in order. A character is anything you can type on the keyboard in one
keystroke, like a letter, a number, or a backslash. Strings can have spaces: "hello world". An empty
string is a string that has 0 characters.

A string is a list of characters in order.

A character is anything you can type on the keyboard in one keystroke,


like a letter, a number, or a backslash.

Strings can have spaces: "hello world".

An empty string is a string that has 0 characters.

Python strings are immutable

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Python recognize as strings everything that is delimited by quotation marks
(" " or ' ').

String Manipulation

To manipulate strings, we can use some of Pythons built-in methods.

word = "Hello World"

>>> print word


Hello World

Accessing

Use [ ] to access characters in a string

word = "Hello World"

letter=word[0]

>>> print letter


H

Length

word = "Hello World"

>>> len(word)
11

Finding

word = "Hello World"

>>> print word.count('l') # count how many times l is in the string


3

>>> print word.find("H") # find the word H in the string


0

>>> print word.index("World") # find the letters World in the string


6

Count

s = "Count, the number of spaces"

>>> print s.count(' ')


8

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


Slicing

Use [ # : # ] to get set of letter

Keep in mind that python, as many other languages, starts to count from 0!!

word = "Hello World"

print word[0] #get one char of the word


print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character

word = "Hello World"

word[start:end] # items start through end-1


word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list

Split Strings

word = "Hello World"

>>> word.split(' ') # Split on whitespace


['Hello', 'World']

Startswith / Endswith

word = "hello world"

>>> word.startswith("H")
True

>>> word.endswith("d")
True

>>> word.endswith("w")
False

Changing Upper and Lower Case Strings

string = "Hello World"

>>> print string.upper()

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


HELLO WORLD

>>> print string.lower()


hello world

>>> print string.title()


Hello World

>>> print string.capitalize()


Hello world

>>> print string.swapcase()


hELLO wORLD

Reverse words in a given string

Example: Let the input string be “i like this program very much”. The function should change the
string to “much very program this like i”
Input: hello

Output: olleh

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement fields
which gets replaced.
We can use positional arguments or keyword arguments to specify the order.
The format() method can have optional format specifications. They are separated from field
name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given
space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or
displayed in the exponent format. There are a ton of formatting you can use.

Conclusion:
Thus, in this experiment we have studied and performed string operation successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


ASSIGNMENT. NO.10

Title:

To copy contents of one file to other. While copying a) all full stops are to be replaced with commas
b) lower case are to be replaced with upper case c) upper case are to be replaced with lower case.
Objective:

Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.

Problem Statement:

To perform file handling operations in python.


Outcomes:

1. Students will be able to understand basic concept of file handling in python.

2. Students will be able to demonstrate file operations.

3. Students will be able to demonstrate different Operations on any igiven file by using own logic.

Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more

Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python


Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.

Theory:

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.
What is a file?

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

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


2. Read or write (perform operation)
3. Close the file

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

How to open 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

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


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.
How to close a file Using Python?

When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using Python 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 operationsf.close()

This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try: f = open("test.txt",encoding = 'utf-8') # perform file operationsfinally: f.close()

How to write to File Using Python?

In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.

We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This
method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n")
f.write("contains three lines\n")

his program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.
We must include the newline characters ourselves to distinguish different lines.
How to read files in Python?

To read a file in Python, we must open the file in reading mode.


There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of the
file.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


>>> f = open("test.txt",'r',encoding = 'utf-8')

>>> f.read(4) # read the first 4 data

'This'

>>> f.read(4) # read the next 4 data

' is '

>>> f.read() # read in the rest till end of file

'my first file\nThis file\ncontains three lines\n'

>>> f.read() # further reading returns empty sting

''

We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get
empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell()
method returns our current position (in number of bytes).
>>> f.tell() # get the current file position

56

>>> f.seek(0) # bring file cursor to initial position

>>> print(f.read()) # read the entire file

This is my first file

This file

contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:

... print(line, end = '')

...This is my first file

This file

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.


contains three lines

The lines in file itself has a newline character '\n'.


Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file. This method reads a file
till the newline, including the newline character.
>>> f.readline()

'This is my first file\n'

>>> f.readline()

'This file\n'

>>> f.readline()

'contains three lines\n'

>>> f.readline()

''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.
>>> f.readlines()

['This is my first file\n', 'This file\n', 'contains three lines\n']

Conclusion:

Thus, in this experiment we have studied file handling in python successfully.

Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.

You might also like