Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
1K views

Python Programs

list of programs using python

Uploaded by

Aswathy G Menon
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Python Programs

list of programs using python

Uploaded by

Aswathy G Menon
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 74

Computer Science Workshop Manual

PYTHON LAB CYCLE


I.Familiarization of Hardware
II.Familiarisation of os and open source tools

III.Familiarization of libre office


IV. Familiarization of linux commands
V. Familiarization of python interpreter operating modes
VI. Python Programs
1) Write a python program to find the sum of 2 numbers.
2) Write a python program to find the area of a circle.
3) Write a python program to find the area and perimeter of a rectangle.
4) Write a python program to swap 2 numbers using temporary variable.

5) Write a python program to swap 2 numbers without using temporary variable.


6) Write a python program to convert celcius to farenheit.
7) Write a python program to calculate simple interest.
8) Write a python program to check whether the given number is divisible by 2 or 3.
9) Write a python program to find the largest of 2 numbers.
10) Write a python program to find the largest of 3 numbers.
11) Write a python program to find whether the given number is even or not.
12) Write a python program to find whether the given number is positive or negative.
13) Write a python program to find the largest of n numbers.
14) Write a python program to find the sum of n numbers.
15) Write a python program to find the factorial of a number.
16) Write a python program to display fibonacci series.
17) Write a python program to display the pattern using for loop
*
*

18) Write a python program to display the pattern using for loop
Department of Computer Science and Engineering, MES CET
1

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


2

Computer Science Workshop Manual

AIM: To familiarise the hardware components of a computer


Computer Hardware
The term computer hardware refers to the physical components of a computer, namely
Keyboard, Monitor, Mouse, and Printer, including the digital circuitry. Computer hardware is an
integral part embedded in all modern day auto-mobiles, microwave ovens, electrocardiograph
machines, compact disc players, and other devices. The hardware of a computer is not changed
frequently, in contrast with software and data. The present computers are much advanced in
terms of processing speed and have an efficient memory structure.
Personal Computers
A personal computer, very commonly known as the PC or the home computer, refers to a
microcomputer whose price, size, and capabilities make it suitable for personal usage. They are
normally single-microprocessors, single user systems designed for general-purpose applications.
They have sufficiently large amount of internal memory to store programs and documents. A
computer, indeed, is a machine that can perform a number of tasks for us. It can accept and store
data, process it and produces the output. For performing these functions, computer systems
consist of Input devices, a Central Processing Unit (CPU) and Output Devices.
Input Devices
The foremost task of a computer is to accept data. An input device is used to accomplish
this task. An input device is used to enter the data and instructions into the computer.
Advancement in the computer technology has resulted in a variety of input devices being
available in the market. Keyboard and mouse are the most commonly used input devices.
Keyboard: Keyboard is the most popular input device that allows users to type alphabets,
numbers, and operators, and also to control the cursor on the screen.
Mouse: Mouse is a pointing device that allows user to point to a specific position on the screen.
It has two or three buttons on top for selecting/executing different operations. Pressing buttons of
mouse is known as clicking of mouse. The mouse is placed on flat surface and moved around to
Department of Computer Science and Engineering, MES CET
3

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

Rewritable CDs and DVDs

II.

FAMILIARISATION OF OS AND OPEN SOURCE TOOLS

Department of Computer Science and Engineering, MES CET


7

Computer Science Workshop Manual

AIM: To familiarise operating system and different open source tools


Open source tools is a phrase used to mean a program or tool -- that performs a very
specific task, in which the source code is openly published for use and/or modification from its
original design, free of charge. Open source tools are typically created as a collaborative effort in
which programmers improve upon the code and share the changes within the community. It is
usually available at no charge under a license defined by the Open Source Initiative.
Open source tools may be viable alternatives to popular closed-source applications and
some open source tools offers features or performance benefits that surpass their commercial
counter-parts. The phrase open source tools is synonymous with open source utility and similar
to open source applications.
Open Source Tools: Browsers
1. Chrome Replaces: Internet Explorer
The big advantage Google's browser offers over the one from Microsoft is speed. It's fast
to start up, fast to load pages, and fast to run Web apps. Unlike other browsers, it uses a
combination Web address/search bar and simplifies the browsing experience in other ways as
well. Operating System: Windows, Linux, OS X.
2. Firefox
While not as fast as Chrome, Firefox offer faster performance than Internet Explorer, as
well as excellent security features. It includes a lot of personalization features and more than
6,000 add-ons so that you can make your browser work the way you want it to. Operating
System: Windows, Linux, OS X.

Open Source Tools: Office Productivity


3. OpenOffice.org Replaces: Microsoft Office
Department of Computer Science and Engineering, MES CET
8

Computer Science Workshop Manual

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.

Open Source Tools: PDF Tools


7. PDFCreator Replaces: Adobe Acrobat
Department of Computer Science and Engineering, MES CET
9

Computer Science Workshop Manual

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.

FAMILIARIZATION OF LIBRE OFFICE

AIM: To familiarise with LibreOffice


Department of Computer Science and Engineering, MES CET
10

Computer Science Workshop Manual

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

a word processor with similar functionality and file support to Microsoft

Word or WordPerfect. It has extensive WYSIWYG word processing capabilities, but can also be
used as a basic text editor.

2) Calc:

Department of Computer Science and Engineering, MES CET


11

Computer Science Workshop Manual

It is a spreadsheet program, similar to Microsoft Excel or Lotus 1-2-3. It has a number of


unique features, including a system which automatically defines series of graphs, based on
information available to the user.
3) Impress:
It is a presentation program resembling Microsoft PowerPoint. Presentations can be exported
as SWF files, allowing them to be viewed on any computer with Adobe Flash installed.
4) Draw:
It is a vector graphics editor and diagramming tool similar to Microsoft Visio and comparable
in features to early versions of CorelDRAW. It provides connectors between shapes, which are
available in a range of line styles and facilitate building drawings such as flowcharts. It also
includes features similar to desktop publishing software such as Scribus and Microsoft Publisher.
5) Math:
It is an application designed for creating and editing mathematical formulae. The application
uses a variant of XML for creating formulas, as defined in the OpenDocument specification.
These formulas can be incorporated into other documents in the LibreOffice suite, such as those
created by Writer or Calc, by embedding the formulas into the document.
6) Base:
It is a database management program, similar to Microsoft Access. LibreOffice Base allows
the creation and management of databases, preparation of forms and reports that provide end
users easy access to data. Like Access, it can be used to create small embedded databases that are
stored with the document files (using Java-based HSQLDB as its storage engine), and for more
demanding tasks it can also be used as a front-end for various database systems.

IV.

FAMILIARIZATION OF LINUX COMMANDS

Department of Computer Science and Engineering, MES CET


12

Computer Science Workshop Manual

AIM: To familiarise linux commands


pwd : Print Working Directory. Shows the current location in the directory tree.
Cd: Change Directory. When typed all by itself, it returns you to your home directory.
cd directory: Change into the specified directory name. Example: cd /usr/src/linux
cd ~: ~ is an alias for your home directory. It can be used as a shortcut to your home, or
other directories relative to your home.
cd .. : Move up one directory. For example, if you are in /home/vic and you type cd .., you will
end up in /home.
cd -: Return to previous directory. An easy way to get back to your previous location!
Ls: List all files in the current directory, in column format.
ls directory : List the files in the specified directory. Example: ls /var/log
ls l: List files in long format, one file per line. This also shows you additional info about the
file, such as ownership, permissions, date, and size.
ls a: List all files, including hidden files. Hidden files are those files that begin with a .,
e.g. The bash_history file in your home directory.

Department of Computer Science and Engineering, MES CET


13

Computer Science Workshop Manual

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

display the file we created in the previous section.


Head: Display the first few lines of a text file. Example: head /etc/services
Tail: Display the last few lines of a text file. Example: tail /etc/services
tail f: Display the last few lines of a text file, and then output appended data as the file grows
(very useful for following log files!).
Example: tail -f /var/log/messages
cp: Copies a file from one location to another. Example: cp mp3files.txt /tmp (copies the
mp3files.txt file to the /tmp directory)
rv: Moves a file to a new location, or renames it. For example: mv mp3files.txt /tmp(copy the
file to /tmp, and delete it from the original location)
Department of Computer Science and Engineering, MES CET
14

Computer Science Workshop Manual

rm: Delete a file. Example: rm /tmp/mp3files.txt


mkdir: Make Directory. Example: mkdir /tmp/myfiles/
rmdir: Remove Directory. Example: rmdir /tmp/myfiles/
Informational Commands
ps: Lists currently running process (programs).
w: Show who is logged on and what they are doing.
id :Print your user-id and group id's
df : Report filesystem disk space usage (Disk Free is how I remember it)
du : Disk Usage in a particular directory. du -s provides a summary for the current directory.
top : Displays CPU processes in a full-screen GUI. A great way to see the activity on your
computer in real-time. Type Q to quit.
free : Displays amount of free and used memory in the system.
cat /proc/cpuinfo : Displays information about your CPU.
cat /proc/meminfo :Display lots of information about current memory usage.
Department of Computer Science and Engineering, MES CET
15

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


16

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


17

Computer Science Workshop Manual

V.

FAMILIARIZATION OF PYTHON INTERPRETER OPERATING MODES

AIM: To familiarize python interpreter operating modes


Python
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
History
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands. Python is
derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
Unix shell, and other scripting languages. Python is copyrighted. Like Perl, Python source code
is now available under the GNU General Public License (GPL). Python is now maintained by a
core development team at the institute, although Guido van Rossum still holds a vital role in
directing its progress.

Department of Computer Science and Engineering, MES CET


18

Computer Science Workshop Manual

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

Computer Science Workshop Manual


It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python is available on a wide variety of platforms including Linux and Mac OS X. Let's
understand how to set up our Python environment.
Local Environment Setup
Open a terminal window and type "python" to find out if it is already installed and which
version is installed. Python has also been ported to the Java and .NET virtual machines
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python: http://www.python.org/. You can download Python
documentation from www.python.org/doc/. The documentation is available in HTML, PDF, and
PostScript formats.
Python Environment Variables
Here are important environment variables, which can be recognized by Python:
Variable
PYTHONPATH

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

sometimes preset by the Python installer.


It contains the path of an initialization file
containing Python source code. It is
executed

every

time

you

start

the

interpreter. It is named as .pythonrc.py in


Unix and it contains commands that load
utilities or modify PYTHONPATH.
Department of Computer Science and Engineering, MES CET
20

Computer Science Workshop Manual

PYTHONCASEOK

It is used in Windows to instruct Python to


find the first case-insensitive match in an
import statement. Set this variable to any

PYTHONHOME

value to activate it.


It is an alternative module search path. It is
usually

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

This produces the following result:


Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module, or other
object. An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
Here are naming conventions for Python identifiers:
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Python Keywords
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
And
Assert
Break
Class
Continue
def
del
elif
else
except
Lines and Indentation

exec
finally
for
from
global
if
import
in
is
lambda

Not
or
pass
print
raise
return
try
while
with
yield

Department of Computer Science and Engineering, MES CET


23

Computer Science Workshop Manual

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

Computer Science Workshop Manual

VI. PYTHON PROGRAMS


1.Write a python program to find the sum of 2 numbers.
Algorithm
1) Start
2) Read the Value of A and B.
3) SUM = A+B.
4) Display SUM.
5) Stop.
Program
Department of Computer Science and Engineering, MES CET
25

Computer Science Workshop Manual

num1=input("enter first number")


num2=input("enter second number")
num3=num1+num2
print "sum is \t",num3
Output
Enter first number 3
Enter second number 5
sum is 8

2.Write a python program to find the area of a circle.


Algorithm
1) Start
2) Input the the value of radius R
3) Let PI=3.14
4) Calculate area=PI*R*R
5) Print area
6) End

Department of Computer Science and Engineering, MES CET


26

Computer Science Workshop Manual

Program
rad=input("enter radius")
area=3.14*rad*rad
print "area is ",area
Output
enter radius 2
area is 12.56

3. Write a python program to find the area and perimeter of a rectangle.


Algorithm
1) Start
2) Accept the length and breadth of rectangle
3) area=length*breadth
4) display area
5) perimeter=2 * (Length + Breadth)
6) display perimeter
7) stop
Department of Computer Science and Engineering, MES CET
27

Computer Science Workshop Manual

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

4. Write a python program to swap 2 numbers using temporary variable.


Algorithm
1) Start
2) Accept two numbers
3) temp=a
4) a=b
5) b=temp
6) display a and b
7) stop
Department of Computer Science and Engineering, MES CET
28

Computer Science Workshop Manual

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

5. Write a python program to swap 2 numbers without using temporary variable.


Algorithm
1. Start
2. Accept two numbers a and b
3. a=a+b
4. b=a-b
5. a=a-b
6. display a and b
7. stop
Department of Computer Science and Engineering, MES CET
29

Computer Science Workshop Manual

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

6.Write a python program to convert celcius to farenheit.


Algorithm
1. Start
2. Accept temperature in celcius
3. farenheit=(celcius*1.8)+32
4. display farenheit
5. stop
Program
celcius=input("enter celcius")
Department of Computer Science and Engineering, MES CET
30

Computer Science Workshop Manual

faren=(1.8*celcius)+32
print "faren is ",faren
Output
enter celcius 10
faren is 50

7. Write a python program to calculate simple interest.


Algorithm
1) Start
2) Accept principal,number of years,rate of interest
3) simpleinterest =principal*numberofyears*rateofinterest
4) display simpleinterest
5) stop
Program
principal=input("enter principal")
Department of Computer Science and Engineering, MES CET
31

Computer Science Workshop Manual

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

8. Write a python program to find the largest of 2 numbers.


Algorithm
1) Start
2) Input 2 values from user. Let it a and b
3) If a>b go to step 4 else go to step 5
4) Print a is largest
5) Print b is largest
6) Stop
Program
Department of Computer Science and Engineering, MES CET
32

Computer Science Workshop Manual

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

9. Write a python program to find the largest of three numbers


Algorithm
1) Start
2) Read three numbers A, B, C
3) Compare A with B
4) If A is larger compare it with C
5) If A is larger than C then A is the largest otherwise C is the largest.
6) If A is smaller than or equal to B in the first step then B is compared with C.
7) If B is larger than C then B is the largest number otherwise C is the largest number.
Department of Computer Science and Engineering, MES CET
33

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

12.Write a python program to check whether a given number is divisible by 2 or 3


Algorithm
1) Start
2) Read a number to a variable num
3) If num%2==0 and num%3==0 go to step 4 else go to step 5
4) Print number is divisible by 2 and 3
5) If num%2==0 go to step 6 else go to step 7
6) Print number is divisible by 2
7) If num%3==0 go to step 8 else go to step 9
Department of Computer Science and Engineering, MES CET
36

Computer Science Workshop Manual

8) Print number is divisible by 3


9) Print number is divisible by 2 and 3
10) Stop
Program
num=input(Enter a number:)
if num%2==0 and num%3==0 :
print number is divisible by 2 and 3
elif num%2==0 :
print number is divisible by 2
elif num%3==0 :
print number is divisible by 3
else:
print number is not divisible by 2 or 3
Output
Enter a number:43
43 is not divisible by 2 or 3
13. Write a python program to find the largest of n numbers.
Algorithm
1) Start
2) Read count of numbers to the variable count
3) i=0,largest=0
4) If i<count ,repeat steps 5 to 8 else go to step 9
5) Read first number to the variable num
6) If num>largest go to step 7 else go to step 8
7) largest=num
Department of Computer Science and Engineering, MES CET
37

Computer Science Workshop Manual

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

14. Write a python program to find the sum of n numbers.


Algorithm
1) Start
2) Read count of numbers to the variable count
3) i=0,sum=0
4) If i<count ,repeat steps 5 to 7 else go to step 8
5) Read first number to the variable num
6) sum=sum+num
7) i=i+1
Department of Computer Science and Engineering, MES CET
38

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

16. Write a python program to display fibonacci series.


Algorithm
1) Start
2) Input no.of terms from user.Let it be n
3) a=0, b=1,i=0
4) Print a,b
5) Repeat the steps till i<n
6) c=a+b
7) Assign the value of b to a
Department of Computer Science and Engineering, MES CET
40

Computer Science Workshop Manual

8) Assign the value of c to b


9) Increment I value by 1
10) print c
11) Stop
Program
n=input("Enter no. of terms")
a=0
b=1
i=0
print a
print b
while i<n:
c=a+b
a=b
b=c
i++
print c
Output
Enter no. of terms 5
0112358
17. Write a python program to display the pattern using for loop
*
*

Algorithm
1) Start
Department of Computer Science and Engineering, MES CET
41

Computer Science Workshop Manual

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
6) Repeat steps 7 to 8 until j>0 else go to step 9
7) print *
8) j=j-1
9) print newline
10) i=i+1
11) Stop
Program
num= input(Enter no of lines)
for i in range(1, num + 1):
for j in range(i, 0, -1):
print *,
print ""
Output
Enter number of lines 5
*
*

Department of Computer Science and Engineering, MES CET


42

Computer Science Workshop Manual

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

Computer Science Workshop Manual

6) Repeat steps 7 to 8 until j>0 else go to step 9


7) print j
8) j=j-1
9) print newline
10) i=i+1
11) Stop
Program
num= input(Enter no of lines)
for i in range(1, num + 1):
for j in range(i, 0, -1):
print j,
print ""

Output
Enter number of lines 5
1
2

Department of Computer Science and Engineering, MES CET


44

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

lower= input(Enter lower bound)


upper= input(Enter upper bound)
sum=0
for count in range(lower,upper+1):
sum=sum+count
print sum is,sum
Output
Enter lower bound 1
Enter upper bound 5
sum is 15

21. Write a python program to find factorial using function.

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

Computer Science Workshop Manual

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

22. Write a python program to reverse a number using function.

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

Computer Science Workshop Manual

5) Print the reversed number


6) Stop
Program
def reverse(n):
rev=0
while n>0:
k=n%10
rev=rev*10+k
n=n/10
return rev
num=input("Enter the number")
revno=reverse(num)
print "The reversed number is ",revno
Output
Enter the number: 123
The reversed number is 321

Department of Computer Science and Engineering, MES CET


49

Computer Science Workshop Manual

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

Computer Science Workshop Manual

Enter the number: 123


6

Department of Computer Science and Engineering, MES CET


51

Computer Science Workshop Manual

24. Write a python program to find the roots of a quadratic equation.


Algorithm
1) Start
2) Define the function root() with parameters a,b,c
1) Initialise the variable d=0
2) d=(b*b)-(4*a*c)
3) if d>0 go to step 6 else go to step 7
4) x=(-b+math.sqrt(d))/2*a
5) y=(-b+math.sqrt(d))/2*a
6) print x,y
7) if d==0 go to step 8 else go to step 10
8) r=(-b)(2*a)
9) print the equal root is ,x
10) print roots are imaginary
3) Read a,b,c coefficents from keyboard
4) Call the root function with a,b,c as arguments.
5) Stop
Program
import math
def root(a,b,c):
d=0
d=(b*b)-(4*a*c)
if d>0:
x=(-b+math.sqrt(d))/2*a
y=(-b+math.sqrt(d))/2*a
print solutions are, x,y
Department of Computer Science and Engineering, MES CET
52

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


53

Computer Science Workshop Manual

25.Write a python program to print multiplication table of a given number.


Algorithm
1. Start
2. Define function printmultiples with two parameters n and high
1. Initialise i=1
2. While i less than or equal to high repeat the following steps otherwise go to step 5
3. print the product of i and n
4. Increment i by one
5. Print a new line
2. Define the function printmultable() with parameter high
1. Initialise the variable i=1
2. While the value of i less than or equal to high, repeat the following steps
3. Call the function printmultiplies(i,high)
4. i=i+1
3. Input the number num from keyboard.
4. Call the function printmultable() with the num as argument
5. Stop
Program
def printmultiples(n,high):
i=1
while i<=high:
print i*n,'\t',
i=i+1
print
def printmultable(high):
i=1
Department of Computer Science and Engineering, MES CET
54

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


55

Computer Science Workshop Manual

26. Write a python program to check whether a string is palindrome or not.


Algorithm
1) Start
2) Read a string str
3) Set index=0 and flag=0
4) Repeat step 5 to step 7 until index<len(str) else go to step 8
5) if str[index]!=str[-1-index] go to step 6 else go to step 7
6) flag=1
7) index=index+1
8) if flag Print string is not palindrome else go to step 9
9) print string is palindrome
10) Stop
Program
n=raw_input("Enter the String:")
index=0
flag=0
while index<len(n):
if n[index]!=n[-1-index]:
flag=1
break
index+=1
if (flag):
print "It is not a Palindrome"
else:
print "It is a Palindrome"
Output
Department of Computer Science and Engineering, MES CET
56

Computer Science Workshop Manual

Enter the String:malayalam


It is a Palindrome

Department of Computer Science and Engineering, MES CET


57

Computer Science Workshop Manual

27. Write a python program to find the index of a character in a string.


Algorithm
1) Start
2) Read a string str and a character ch
3) Set index=0
4) Repeat step 5 to step 7 until index<len(str) else go to step 8
5) if str[index]==ch go to step 6 else go to step 7
6) print character found at position index
7) index=index+1
8) print character is not present in the string
9) Stop
Program
str1=raw_input("Enter string")
ch=raw_input("Enter character to be searched")
index=0
while index<len(str1):
if str1[index]==ch:
print ch,"found at position",index
break
index=index+1
else:
print ch,"not found in string"
Output
Enter string:malayalam
Enter character to be searched:l
l found at position 2
Department of Computer Science and Engineering, MES CET
58

Computer Science Workshop Manual

28. Write a python program to find the count of a character in a string.


Algorithm
1) Start
2) Read a string str and character ch
3) Set index=0
4) Repeat step 5 to step 7 ,read character by character until there are characters in str else
go to step 8
5) if characters==ch go to step 6 else go to step 7
6) count=count+1
7) read next character
8) print count
9) Stop
Program
str1=raw_input("Enter string:")
ch=raw_input("Enter character to be searched:")
count=0
for char in str1:
if char==ch:
count=count+1
print "count of ",ch,"is ",count
Output
Enter string:malayalam
Enter character to be searched:a
count of a is 4

Department of Computer Science and Engineering, MES CET


59

Computer Science Workshop Manual

29. Write a python program to compare 2 strings using function.


Algorithm
1) Start
2) Read two strings str1,str2
3) if str1==str2 got to step 4 else go to step 5
4) print strings are equal
5) if str1<str2 go to step 6 else go to step 7
6) print str1 comes before str2
7) print str1 comes after str2
8) Stop
Program
str1=raw_input("Enter string1:")
str2=raw_input("Enter string2:")
if str1==str2:
print "strings are equal"
elif str1<str2:
print str1," comes before ",str2
else:
print str1," comes after ",str2
Output
Enter string1:blue
Enter string2:green
blue comes before green

Department of Computer Science and Engineering, MES CET


60

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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]

Department of Computer Science and Engineering, MES CET


62

Computer Science Workshop Manual

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']

Department of Computer Science and Engineering, MES CET


63

Computer Science Workshop Manual

32.Write a python program to swap 2 numbers using tuples and function.


Algorithm
1) Start
2) Define a function swap with 2 parameters x,y
1. return y,x
3) Input 2 numbers a and b
4) a,b=swap(a,b)
5) print a,b
6) Stop
Program
def swap(x,y):
return y,x
a=input("Enter number")
b=input("Enter number")
a,b=swap(a,b)
print a,b
Output
Enter number10
Enter number20
20 10

Department of Computer Science and Engineering, MES CET


64

Computer Science Workshop Manual

33.Write a python program to generate a list of random values using function.

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]

Department of Computer Science and Engineering, MES CET


65

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Department of Computer Science and Engineering, MES CET


67

Computer Science Workshop Manual

35.Write a python program to convert hex to binary using dictionary.

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

Department of Computer Science and Engineering, MES CET


68

Computer Science Workshop Manual

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)]

Department of Computer Science and Engineering, MES CET


69

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

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

Computer Science Workshop Manual

return n*fact(n-1)
num=input("Enter number")
print fact(num)
Output
Enter number5
120

Department of Computer Science and Engineering, MES CET


74

You might also like