Python Programs
Python Programs
18) Write a python program to display the pattern using for loop
Department of Computer Science and Engineering, MES CET
1
1
2
19) Write a python program to find exponentiation of 'a' to power 'x' using for loop.
20) Write a python program to find the sum of a sequence of numbers between a lower bound and
upper bound.
21) Write a python program to find factorial using function.
22) Write a python program to reverse a number using function.
23) Write a python program to find the sum of digits of a number using function.
24) Write a python program to find the roots of a quadratic equation using function.
25) Write a python program to display the multiplication table of a given number.
26) Write a python program to check whether a given string is palindrome or not.
27) Write a python program to count the number of times each character appears in a string.
28) Write a python program to check for presence of a character in a string.
29) Write a python program to compare two strings.
30) Write a python program which accepts a string,splits it and outputs the list of words in uppercase.
31) Write a python program which accepts a list of numbers and outputs thier squares.
32) Write a python program to swap 2 numbers using tuples and function.
33) Write a python program to generate a list of random values using function.
34) Write a python program to find the median of a set of numbers using list.
35) Write a python program to convert hex to binary using dictionary.
36) Write a python program to generate a histogram of the letters in a string using dictionary.
37) Write a python program to copy contents of one file to another omitting any lines that begin with
#.
38) Write a python program to open and write your roll no an list of marks to a file using pickling.
39) Write a python program to find the factorial of a number using recursion.
I.
FAMILIARIZATION OF HARDWARE
move its controlling arrow on screen. The arrow showing the position of mouse on screen is
known as mouse pointer. Left button of mouse is used execute the operation associated with it.
Right button/Middle buttons are associated with special operations in different situations.
Some of the other Input Devices are enlisted below:
Joy Stick- It is a device used to control cursor on screen. Normally it is used in Games and
specially designed simulation software
Light Pen- It is a device used for drawing pictures and for directly controlling screen operations.
Microphone- It is a device used to accept audio inputs from the user.
Scanner- It is a device used to capture digital images of printed documents, graphics or other
printed media.
Touch Screens-It is a display device, which is touch-sensitive and allows user to interact with
the computer system by touching an area on the screen.
Web Camera- It is an easy to connect low resolution digital camera normally employed for
transfer of images on the web-based conferencing.
Output Devices
It is a device used to provide the processed data from the computer to the user. Monitor
(VDU/Screen) and printer are the most commonly used output devices. The usage of some of the
commonly used output devices is given below:
Monitor- A Monitor is an output device, very similar to the television screen. It displays the
information as it is typed and also displays the processed result or the output. It is available in
many forms cathode ray picture tube based display, liquid crystal based display(LCD), plasma
panel display, and touch panel display.
Printer -It is an output device to produce paper copy (hard copy) for a document, pictures etc.
The job of a printer is to put on paper what is seen on the monitor. Printers vary mainly in cost,
quality, speed and noise levels. Eg: Dot Matrix Printer, Inkjet / Deskjet / Bubblejet Printer, Laser
Printer.
Department of Computer Science and Engineering, MES CET
4
Plotter-Plotters are expensive output devices specially designed to produce outputs of diagrams,
illustrations and other graphics.
Printers
The printers are classified as under:
Impact Printers - These printers have a mechanism that touches the paper in order to create
an image. The Dot Matrix Printer is an example of this type.
Non-impact Printers - These printers do not touch the paper when creating an image.
Motherboard
The Motherboard houses the processor and other components of the computer.
Memory
The computers workspace where application instructions and data are held during
operation is called memory, also known as main memory, primary storage or RAM (Random
Access Memory). The capacity of a memory is important because this is where data and
programs are stored while they are active, thus bigger memory means bigger workspace.
Whatever data is held in the RAM is erased when the computer is reset or the power is turned
off.
The Random Access Memory (RAM)
It is a form of computer data storage. A random-access memory device allows data items
to be accessed (read or written) in almost the same amount of time irrespective of the physical
location of data inside the memory. In contrast, with other direct-access data storage media such
as hard disks, CD-Rws, DVD-Rws and the older drum memory, the time required to read and
write data items varies significantly depending on their physical locations on the recording
medium, due to mechanical limitations such as media rotation speeds and arm movement delays.
Today, random-access memory takes the form of integrated circuits. RAM is normally associated
with volatile types of memory (such as DRAM memory modules), where stored information is
lost if power is removed, although many efforts have been made to develop non-volatile RAM
Department of Computer Science and Engineering, MES CET
5
chips. The amount of memory available determines the kind of software that can be run and how
much data can be manipulated. The available RAM at present is 32 MB, 64 MB, 128 MB, 256
MB or more.
Read Only Memory (ROM)
Aside from the RAM, the computer also has a ROM (Read only memory) which is used
to store the boot program and other low-level information that enables the computer to start up
and to recognize its hardware parts.
It is a class of storage medium used in computers and other electronic devices. Data
stored in ROM can only be modified slowly, with difficulty, or not at all, so it is mainly used to
distribute firmware. The fact that such memory can never be changed is a large drawback; more
recently, ROM commonly refers to memory that is read-only in normal operation, while
reserving the fact of some possible way to change it.
Other types of non-volatile memory such as erasable programmable read only memory
(EPROM) and electrically erasable programmable read-only memory (EEPROM or Flash ROM)
are sometimes referred to, in an abbreviated way, as "read-only memory" (ROM); although these
types of memory can be erased and re-programmed multiple times, writing to this memory takes
longer and may require different procedures than reading the memory. When used in this less
precise way, "ROM" indicates a non-volatile memory which serves functions typically provided
by mask ROM, such as storage of program code and nonvolatile data.
Storage Devices
The hardware used to retain data for future use is called a storage device. These devices
may be found inside or outside the computer. There are different kinds of storage devices.
Among these are optical devices (CD-ROM, DVD), and magnetic devices (tapes, disks).
Examples of Storage Devices
Magnetic: Hard disk, Floppy disk, Zip disk, Jaz disk, tapes
Optical--CD-ROM, DVD (Digital Versatile Disk)
Department of Computer Science and Engineering, MES CET
6
II.
One of the best applications for people who have never used open-source before,
OpenOffice.org includes a word processor, spreadsheet, presentation creator, and database that
read and create Microsoft-compatible files. Unlike Office, it also comes with a drawing program
and a mathematical equation creator, and of course, it's free. Operating System: Windows, Linux,
OS X, others.
Open Source Tools: Operating System
4. Red Hat Replaces: Windows
Calling itself "the world's leading open source application platform," Red Hat offers both
desktop and server versions of Linux that are designed primarily for enterprise users. One-year
subscriptions which include basic support start at $349 for the server version and $80 for the
desktop version, or you can get a free, non-supported version that is nearly identical from
Fedora.
5. SUSE Replaces: Windows
Novell also targets large business users with it's SUSE version of Linux. Prices start at
$349 for the server version and $50 for the desktop version, and free versions are available from
openSUSE.
6 Ubuntu Replaces: Windows
Because it is so user friendly, Ubuntu is one of the most popular versions of Linux for
home users, particularly netbook users. Unlike Windows, Ubuntu (and the other versions of
Linux) includes most of the applications you'll need, so you don't have to purchase separate
software for word processing, spreadsheets, e-mail, video, music, etc.
With this tool, you can create a PDF file from any application that can print. It also
includes digital signature and encryption capabilities, but it lacks some of Acrobat's form
creating capabilities. Operating System: Windows.
Open Source Tools: Text Editor
8.gedit: Replaces WordPad
This is the default text editor for the Linux Gnome desktop. It supports syntax
highlighting, printing, a variety of plug-ins, multi-language spell check, tabbed for multiple files,
etc. This text editor also has search and replace functionality, undo and redo and tools for editing
programming code and working with markup (HTML for example), as well as other structured
languages. Additional features include automatically detecting and alerting you to the
modification of an open file by another application. Its well-known, popular, efficient, and its
limitations may be overcome with available plugins.
III.
LibreOffice is a free and open source office suite, developed by The Document
Foundation. It was forked fromOpenOffice.org in 2010, which was an open-sourced version of
the earlier StarOffice. The LibreOffice suite comprises programs for word processing, the
creation and editing of spreadsheets, slideshows, diagrams and drawings, working with
databases, and composing mathematical formulae.
LibreOffice uses the international ISO/IEC standard OpenDocument file format as its
native format to save documents for all of its applications (as do its OpenOffice.org
cousins Apache OpenOffice and NeoOffice). The OpenDocument file format is now also
supported by all major competing office suite applications (proprietary and open source).
LibreOffice is also compatible with other major office suites, including Microsoft Office,
through a variety of import/export filters. The file formats of Microsoft Office are well
supported, though some layout features and formatting attributes are handled differently in the
application or are not entirely supported in the filters. LibreOffice is available in 110
languages and for a variety of computing platforms, including Microsoft Windows, OS X (10.8
or newer), and Linux (including a LibreOffice Viewer for Android). It is the default office suite
of most popular Linux distributions.
Included applications
1) Writer:
It is
Word or WordPerfect. It has extensive WYSIWYG word processing capabilities, but can also be
used as a basic text editor.
2) Calc:
IV.
ls ld directory: A long list of directory, but instead of showing the directory contents, show
the directory's detailed information. For example, compare the output of the following two
commands:
ls -l /usr/bin
ls -ld /usr/bin
ls /usr/bin/d*: List all files whose names begin with the letter d in the /usr/bin directory.
File: Find out what kind of file it is. For example, file /bin/ls tells us that it is a Linux
executable file.
Cat:
Display the contents of a text file on the screen. For example: cat mp3files.txt would
uname -a : Prints system information to the screen (kernel version, machine type, etc.)
Other Utilities
clear : Clear the screen
echo : Display text in the screen. Mostly useful when writing shell scripts. For example: echo
Hello World
more : Display a file, or program output one page at a time.
Examples: more mp3files.txt
ls -la | more
less : An improved replacement for the more command. Allows you to scroll backwards as
well as forwards.
grep : Search for a pattern in a file or program output. For example, to find out which TCP
network port is used by the nfs service, you can do this: grep .nfs. /etc/services This looks for
any line that contains the string nfs in the file /etc/services and displays only those lines.
lpr :Print a file or program output. Examples:
lpr mp3files.txt - Print the mp3files.txt file
ls -la | lpr - Print the output of the ls -la command.
sort : Sort a file or program output. Example: sort mp3files.txt
su :Switch User. Allows you to switch to another user's account temporarily. The default
account to switch to is the root/superuser account. Examples:
su - Switch the root account
su - - Switch to root, and log in with root's environment
su larry - Switch to Larry's account
V.
Python Features
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed
below:
IT supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
IT supports automatic garbage collection.
Department of Computer Science and Engineering, MES CET
19
Description
It has a role similar to PATH. This variable
tells the Python interpreter where to locate
the module files imported into a program.
It should include the Python source library
directory and the directories containing
Python source code. PYTHONPATH is
PYTHONSTARTUP
every
time
you
start
the
PYTHONCASEOK
PYTHONHOME
embedded
in
the
PYTHONSTARTUP or PYTHONPATH
directories to make switching module
libraries easy.
Running Python
There are three different ways to start Python:
(1) Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line
interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
(2) Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application,
as in the following:
$python script.py # Unix/Linuxor
python% script.py # Unix/Linuxor C:>python script.py # Windows/DOS
(3) Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a
GUI application on your system that supports Python.
Unix: IDLE is the very first Unix IDE for Python.
Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI.
Basic Syntax
Department of Computer Science and Engineering, MES CET
21
The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages. Let us execute programs in different modes of
programming.
Interactive Mode Programming:
Invoking the interpreter without passing a script file as a parameter brings up the following
prompt:
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
>>> print "Hello, Python!";
If you are running new version of Python, then you need to use print statement with parenthesis
as in print ("Hello, Python!");. However in Python version 2.4.3, this
produces the following result:
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no longer
active. Let us write a simple Python program in a script. Python files have extension .py. Type
the following source code in a test.py file:
print "Hello, Python!";
We assume that you have Python interpreter set in PATH variable. Now, try to run this program
as follows:
$ python test.py
Department of Computer Science and Engineering, MES CET
22
exec
finally
for
from
global
if
import
in
is
lambda
Not
or
pass
print
raise
return
try
while
with
yield
Python provides no braces to indicate blocks of code for class and function definitions or
flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example:
if True:
print "True"
else:
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would
form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the end of the physical line are part of the comment and the Python interpreter ignores
them.
#!/usr/bin/python
# First comment
Department of Computer Science and Engineering, MES CET
24
Program
rad=input("enter radius")
area=3.14*rad*rad
print "area is ",area
Output
enter radius 2
area is 12.56
Program
length=input("enter length")
breadth=input("enter breadth")
area=length*breadth
perimeter=2*(length+breadth)
print "area is ",area
print "perimeter is ",perimeter
Output
enter length 10
enter breadth 5
area is 50
perimeter is 30
Program
num1=input("enter num1")
num2=input("enter num2")
temp=num1
num1=num2
num2=temp
print "num1 is ",num1,"num2 is ",num2
Output
enter num1 20
enter num2 10
num1 is 10 num2 is 20
Program
num1=input("enter num1")
num2=input("enter num2")
num1=num1+num2
num2=num1-num2
num1=num1-num2
print "num1 is ",num1,"num2 is ",num2
Output
enter num1 20
enter num2 10
num1 is 10 num2 is 20
faren=(1.8*celcius)+32
print "faren is ",faren
Output
enter celcius 10
faren is 50
years=input(enter no of years)
rate=input(enter interest rate)
SI=principal*years*rate/100
print "Simple Interest is ",SI
Output
enter principal 100
enter no of years 2
enter interest rate 10
simple interest is 20
a=nput("Enter a number")
b=input("Enter a number")
if a>b:
print "Largest is ",a
else:
print "Largest is ",b
or
a=input("Enter a number")
b=input("Enter a number")
print "Largest is ",max(a,b)
Output
Enter a number 2
Enter a number 4
Largest is 4
8) Stop
Program
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
Output
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14
10. Write a python program to find the whether the given number is even or not.
Algorithm
1) Start
2) Read a number to a variable num
3) If num%2==0 go to step 4 else go to step 5
4) Print number is even
5) Print number is odd
6) Stop
Program
Department of Computer Science and Engineering, MES CET
34
num=input(Enter a number:)
mod=num % 2
if mod > 0 :
print (This is not an even number.)
else :
print(This is an even number)
Output 1
Enter a number:43
43 is odd
Output 2
Enter a number:18
18 is even
11. Write a python program to find the whether the given number is positive or not.
Algorithm
1) Start
2) Read a number to a variable num
3) If num>0 go to step 4 else go to step 5
4) Print number is positive
5) Print number is negative
6) Stop
Program
Department of Computer Science and Engineering, MES CET
35
num=input(Enter a number:)
if num > 0 :
print (This is an positive number.)
else :
print(This is a negative number)
Output 1
Enter a number:43
43 is positive
Output 2
Enter a number:-18
-18 is negative
8) i=i+1
9) print largest
10) Stop
Program
count=input(Enter count:)
i=0
largest=0
while i<count:
num=input(enter number)
if num>largest:
largest=num
i=i+1
print largest is,largest
Output
Enter count 2
Enter number 43
Enter number 20
Largest is 43
8) print sum
9) Stop
Program
count=input(Enter count:)
i=0
sum=0
while i<count:
num=input(enter number)
sum+=num
i=i+1
print sum is,sum
Output
Enter count 4
Enter number 10
Enter number 20
Enter number 30
Enter number 40
sum is 100
15. Write a python program to find the factorial of a number.
Algorithm
1) Start
2) Read the no N
3) Set i=1 and fact=1
4) Repeat step 5 to step 6 until i=n else go to step 7
5) fact= fact*i
6) i=i+1
Department of Computer Science and Engineering, MES CET
39
7) Print fact
8) Stop
Program
num= input(Enter a number)
i=1
fact=1
while i<= num:
fact= fact *i
i=i+1
print factorial is,fact
Output
Enter a number 5
factorial is 120
Algorithm
1) Start
Department of Computer Science and Engineering, MES CET
41
18. Write a python program to display the pattern using for loop
1
2
Algorithm
1) Start
2) Read the no of lines to be displayed in n
3) Set i=1
4) Repeat step 5 to step 10 until i<n+1
5) set j=i
Department of Computer Science and Engineering, MES CET
43
Output
Enter number of lines 5
1
2
19. Write a python program to find exponentiation of 'a' to power 'x' using for loop.
Algorithm
1) Start
2) Read the base to the variable num and exponent to the variable exp
3) Set product=1,count=0
4) Repeat step 5 to step 6 until count<exp else go to step 7
5) product= product*num
6) count=count+1
7) Print product
8) Stop
Department of Computer Science and Engineering, MES CET
45
Program
num= input(Enter a number)
exp=input(enter the exponent)
product=1
for count in range(exponent):
product= product *num
print product is,product
Output
Enter a number 5
Enter the exponent 3
product is 125
20. Write a python program to find the sum of a sequence of numbers between a lower bound and
upper bound.
Algorithm
1) Start
2) Read 2 numbers to variables lowerbound and upperbound
3) Set sum=0 and count=1
4) Repeat step 5 to step 6 until lowerbound<count<upperbound+1 else go to step 7
5) sum=sum+count
6) count=count+1
7) Print sum
8) Stop
Program
Department of Computer Science and Engineering, MES CET
46
Algorithm
1) Start
2) Define the function factorial
A. Set the variable fact to
B. Set i=1
C. Repeat the step 5 until value of i=1, else go to step 7
D. Calculate fact for each value of i, fact=fact*i
E. Return the value of fact
3) Read the number to the variable num
4) Call the function factorial() to find the result
5) print the factorial
6) Stop
Department of Computer Science and Engineering, MES CET
47
Program
def factorial(n)
fact=1
for i in range(n,0,-1):
fact=fact*i
return fact
num=input(Enter the number)
print Factorial is , factorial(num)
Output
Enter the number: 5
Factorial is 20
Algorithm
1) Start
2) Define the function reverse() with a single parameter
1) Initialise the variable rev=0
2) while the given number greater than zero repeat the following steps otherwise go to
step 6
3) store the result of the operation n%10 in the variable k
4) Update the value of rev, rev=rev*10+k
5) n=n/10
6) return the value of rev
3) Read a number num from keyboard
4) Call the reverse function with num as argument.
Department of Computer Science and Engineering, MES CET
48
23. Write a python program to find the sum of digits of a number using function.
Algorithm
1) Start
2) Define the function add() with a single parameter
1) Initialise the variable sum=0
2) while the given number greater than zero repeat the following steps otherwise go to
step 6
3) store the result of the operation n%10 in the variable t
4) Update the value of add, sum=sum+t
5) n=n/10
6) print the value of sum
3) Read a number num from keyboard
4) Call the add function with num as argument.
5) Stop
Program
def add(num):
sum=0
while num!=0:
t=num%10
num=num/10
sum=sum+t
print sum
return
num=input(Enter number)
add(num)
Output
Department of Computer Science and Engineering, MES CET
50
elif d==0:
r=(-b)(2*a)
print the equal root is ,x
else:
print roots are imaginary
return
a=input(Enter coefficient1)
b=input(Enter coefficient2)
c=input(Enter coefficient3)
root(a,b,c)
Output
Enter coefficient1:1
Enter coefficient2: 4
Enter coefficient3:4
The equal roots are -2
while i<=high:
printmultiples(i,high)
i+=1
num=input("Enter the number")
printmultable(num)
Output
Enter the number 7
1
10
12
14
12
15
18
21
12
16
20
24
26
10
15
20
25
30
35
12
18
24
30
36
42
14
21
28
35
42
49
30. Write a python program to input a list ,compute its squares and output the list.
Algorithm
1) Start
2) Read a count n
3) Set list=[] and i=0
4) Repeat step 5 to step 7 until i<n else go to step 8
5) read a number n1
6) list.append(n1)
7) i=i+1
8) display the list
9) index=0
10) repeat steps 11 to 12 until index<len(list)
11) list[index]=list[index]**2
12) index=index+1
13) print list
14) Stop
Program
n=input("Enter count")
list=[]
i=0
while i<n:
n1=input("Enter number")
list.append(n1)
i=i+1
print list
index=0
Department of Computer Science and Engineering, MES CET
61
while index<len(list):
list[index]=list[index]**2
index=index+1
print list
Output
Enter count 4
Enter number 11
Enter number 12
Enter number 13
Enter number 14
[11, 12, 13, 14]
[121, 144, 169, 196]
31. Write a python program to input a string, split it into words and output the words in
uppercase.
Algorithm
1) Start
2) Read a string str
3) Set word=sentence.split()
4) set index=0
5) Repeat step 6 to step 7 until index<len(word) else go to step 8
6) word[index]=word[index].upper()
7) index=index+1
8) print word
9) Stop
Program
str=raw_input(enter a string:)
word=str.split()
index=0
while index<len(word):
word[index]=word[index].upper()
index=index+1
print word
Output
enter a string: this is a test string
['THIS', 'IS', 'A', 'TEST', 'STRING']
Algorithm
1) Start
2) Define a function randomlist with a parameter n
1. s=[0]*n
2.i=0
3.if i<n repeat step 4 else go to step 5
4.s[i]=random.random()
5.return s
3) Input a numbers n1
4) print randomlist(n1)
5) Stop
Program
import random
def randomlist(n):
s=[0]*n
for i in range(n):
s[i]=random.random()
return s
n1=input("Enter number")
print randomlist(n1)
Output
Enter number 5
[0.7408882554487076, 0.13198791210184502, 0.9726494665333163, 0.290343422938958,
0.29037413911533516]
34.Write a python program to find the median of a set of numbers using list.
Algorithm
1) Start
2) Read a count n
3) Set list=[] and i=0
4) Repeat step 5 to step 7 until i<n else go to step 8
5) read a number n1
6) list.append(n1)
7) i=i+1
8) display the list
9) sort the list
10) midpoint=len(list)/2
11) if len(list)%2==1 go to step 12 else go to step 13
12) print list[midpoint]
13) print (list[midpoint]+list[midpoint-1])/2
14) Stop
Program
n=input("Enter count")
list=[]
i=0
while i<n:
n1=input("Enter number")
list.append(n1)
i=i+1
print list
list.sort()
Department of Computer Science and Engineering, MES CET
66
midpoint=len(list)/2
print "Median is"
if len(list)%2==1:
print list[midpoint]
else:
print (list[midpoint]+list[midpoint-1])/2
Output
Enter count4
Enter number5
Enter number4
Enter number3
Enter number1
[5, 4, 3, 1]
Median is
3
Algorithm
1) Start
2) create a dictionary hextobinary with all mappings
3) define a function convert with 2 parameters number and ditcionary
1.binary=
2.for each digit in the number repeat step 6 else go to step 7
3.binary=table[digit]+binary
4.return binary
4) Read a hex value num
5) print convert(num,hextobinary)
6) Stop
Program
hextobinary={'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100','5':'0101','6':'0110','7':'0111','8':'1000
','9':'1001','A':'1010','B':'1011','C':'1100','D':'1101','E':'1110','F':'1111'}
def convert(number,table):
binary=""
for digit in number:
binary=table[digit]+binary
return binary
num=raw_input("Enter hex value")
print convert(num,hextobinary)
Output
Enter hex value 34A
101001000011
36.Write a python program to generate a histogram of the letters in a string using dictionary.
Algorithm
1) Start
2) read a string in str
3) create an empty dictionary lettercount
4) for each character in str repeat step 5 else go to step 6
5) lettercount[letter]=lettercount.get(letter,0)+1
6) letteritems=lettercount.items()
7) letteritems.sort()
8) print letteritems
9) Stop
Program
str=raw_input("Enter the string")
lettercount={}
for letter in str:
lettercount[letter]=lettercount.get(letter,0)+1
print lettercount
letteritems=lettercount.items()
letteritems.sort()
print letteritems
Output
Enter the string Mississippi
{'i': 4, ' ': 1, 's': 4, 'M': 1, 'p': 2}
[(' ', 1), ('M', 1), ('i', 4), ('p', 2), ('s', 4)]
37.Write a python program to copy contents of one file to another omitting any lines that begin with
#.
Algorithm
1) Start
2) create a function filterfile with 2 parameters oldfile and newfile
1.open the oldfile to pointer f1 in read mode
2.open the newfile to pointer f2 in write mode
3.repeat steps 4 to 7 below as long as the condition is true
4.text=f1.readline()
5.if text== exit from loop
6.if text[0]=='#' continue to next iteration in the loop
7.f2.write(text)
3) Read two file names oldfile and newfile as input
4) filterfile(oldfile,newfile)
5) Stop
Program
def filterfile(oldfile,newfile):
f1=open(oldfile,"r")
f2=open(newfile,"w")
while True:
text=f1.readline()
if text=="":
break
if text[0]=='#':
continue
f2.write(text)
Department of Computer Science and Engineering, MES CET
70
f1.close()
f2.close()
return
file1=raw_input("Enter file1")
file2=raw_input("Enter file2")
filterfile(file1,file2)
Output
a.txt
introduction to computing
#testing
python lab
#sample
b.txt
introduction to computing
python lab
38.Write a python program to open and write your roll no an list of marks to a file using pickling.
Algorithm
1) Start
2) read a filename as input
3) open the file in write mode
4) enter the roll no of the student to be written in file
5) pickle.dump(roll,f1)
6) Read a count n
7) Set list=[] and i=0
8) Repeat step 9 to step 11 until i<n else go to step 12
9) read a number n1
Department of Computer Science and Engineering, MES CET
71
10) list.append(n1)
11) i=i+1
12) pickle.dump(list,f1)
13) f=open(filename,"r")
14) x=pickle.load(f)
15) print x
16) y=pickle.load(f)
17) Stop
Program
import pickle
filename=raw_input("Enter filename")
f1=open(filename,"w")
roll=input("Enter input")
pickle.dump(roll,f1)
n=input("Enter count")
list=[]
i=0
while i<n:
n1=input("Enter number")
list.append(n1)
i=i+1
pickle.dump(list,f1)
f1.close()
f=open(filename,"r")
x=pickle.load(f)
print x
Department of Computer Science and Engineering, MES CET
72
y=pickle.load(f)
print y
Output
Enter filename a.txt
Enter input35
Enter count3
Enter number11
Enter number22
Enter number33
35
[11, 22, 33]
39.Write a python program to find the factorial of a number using recursion.
Algorithm
1) Start
2) create a function fact with one parameter
1.if n<=1 go to step 2 else go to step 3
2.return 1
3.return n*fact(n-1)
3) Read a number num
4) print fact(num)
5) Stop
Program
def fact(n):
if n<=1:
return 1
else:
Department of Computer Science and Engineering, MES CET
73
return n*fact(n-1)
num=input("Enter number")
print fact(num)
Output
Enter number5
120