PYTHON LAB MANNUALstudent

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 58
At a glance
Powered by AI
The key takeaways are that tkinter can be used to create GUIs in Python and that it provides different geometry managers like pack, grid and place to arrange widgets as well as the ability to create custom events and bind them to widgets.

The main geometry managers available in tkinter are pack, grid and place. Pack is used to stack widgets vertically or horizontally, grid allows arranging widgets in a table-like structure using rows and columns, and place allows absolute positioning. Pack is best for simple layouts while grid is more flexible for complex interfaces.

Custom events can be created by defining a string that identifies the event like <Enter> or <Key-a>. These events can then be bound to widgets using the bind method on the widget class and a callback function will be triggered when that event occurs on the widget.

EASWARI ENGINEERING COLLEGE

L DEPARTMENT OF INFORMATION
TECHNOLOGY
GE8161
A
PROBLEM SOLVING AND PYTHON

B PROGRAMMING LABORATORY
LAB MANUAL

M
A
I YEAR
N AUGUST 2018 TO DECEMBER 2018
PREPARED BY APPROVED BY

U Dr.R.Priyatharshini
Mrs.M.Sowmiya
Mrs.P.Deepika
Mrs.K.Kausalya

A Mr. K. Kumaran
Ms. Suganthi HOD

L
EASWARI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Vision

 To impart Quality Education towards the holistic development of students and be a strategic
partner in the Industrial Advancement arena and emerge as a 'Center of Excellence for Higher
Studies' in the specialization of Information Technology.
Mission

 To offer doctoral programmes in the field of Information Technology to enhance research


activities.
 To awaken the young minds and lay solid Engineering foundation among the graduates
through the design of experiments, analysis and interpretation of data.
 To produce graduates with ethical principles and commit to professional ethics to cater to the
norms of engineering practice.
 To create graduates to work individually and as a member of a team to function effectively in
multi-disciplinary areas for solving complex engineering problems.
 To use modern Information Technology tools and appropriate teaching techniques for predicting
and modeling the real world problems.
 To provide contextual knowledge among graduates to assess societal, health, safety, legal and
cultural issues through innovative professional engineering practice.
 To prepare and build the ability to recognise the need for independent and lifelong learning in the
context of technological changes in the field of Information Technology.
Program Educational Objectives (PEO)

 Graduates will be proficient in utilizing the fundamental knowledge of basic sciences,


mathematics and Information Technology for the applications relevant to various streams
of Engineering and Technology.
 Graduates will possess core competencies necessary for applying knowledge of
computers and telecommunications equipment to store, retrieve, transmit, manipulate and
analyze data in the context of business enterprise.
 Graduates will be capable of thinking logically, pursue lifelong learning and will have the
capacity to understand technical issues related to computing systems and to design optimal
solutions.
 Graduates will be able to develop hardware and software systems by understanding the
importance of social, business and environmental needs in the human context.
 Graduates will gain employment in organizations and establish themselves as professionals by
applying their technical skills to solve real world problems and meet the diversified needs of
industry, academia and research.
Program Outcomes (PO)

Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change
Program Specific Outcomes (PSO)

 Create, select, and apply appropriate techniques, resources, modern engineering and IT tools
including prediction and modelling to complex engineering activities with an understanding of the
limitations.
 Manage complex IT projects with consideration of the human, financial, ethical and environmental
factors and an understanding of risk management processes, and operational and policy implications.
GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LTPC
0042
OBJECTIVES
 To write, test, and debug simple Python programs.
 To implement Python programs with conditionals and loops.
 Use functions for structuring Python programs.
 Represent compound data using Python lists, tuples, dictionaries.
 Read and write data from/to files in Python.

LIST OF PROGRAMS

1. Compute the GCD of two numbers.


2. Find the square root of a number (Newton’s method)
3. Exponentiation (power of a number)
4. Find the maximum of a list of numbers
5. Linear search and Binary search
6. Selection sort, Insertion sort
7. Merge sort
8. First n prime numbers
9. Multiply matrices
10. Programs that take command line arguments (word count)
11. Find the most frequent words in a text read from a file
12. Simulate elliptical orbits in Pygame
13. Simulate bouncing ball using Pygame

PLATFORM NEEDED
Python 3 interpreter for Windows/Linux

OUTCOMES

Upon completion of the course, students will be able to

 Write, test, and debug simple Python programs


 Implement Python programs with conditionals and loops.
 Develop Python programs step-wise by defining functions and calling them.
 Use Python lists, tuples, dictionaries for representing compound data.
 Read and write data from/to files in Python.
FORMAT NO: LP 01
TOTAL: 60 PERIODS ISSUE NO: 2
ISSUE DATE: 28.01.12
EASWARI ENGINEERING COLLEGE
DEPARTMENT OF INFORMATION TECHNOLGY

LAB COURSE PLAN

Regulation – 2017

Course/Branch : B.E/B.Tech(All branches) Total no. of hours given in


syllabus:
Subject Code : GE8161 Lecture : 0

Subject Title : Problem solving and Python Tutorials : 0


programming Laboratory
Year/Semester : I/I Practical : 60

Faculty Name : Dr.R.Priyatharshini TOTAL : 60


Mrs.M.Sowmiya
Mrs.P.Deepika
Mrs.K.Kausalya
Mr. K. Kumaran
Ms. Suganthi

COURSE OBJECTIVES:

1. To write, test, and debug simple Python programs.


2. To implement Python programs with conditionals and loops.
3. Use functions for structuring Python programs.
4. Represent compound data using Python lists, tuples, dictionaries.
5. Read and write data from/to files in Python.

S.No. Topics No. of hours

1. Introduction to Python 4

2. Compute the GCD of two numbers. 4

3. Find the square root of a number (Newton’s method) 4

4. Exponentiation (power of a number) 4

5. Find the maximum of a list of numbers 4

6. Linear search and Binary search 4

7. Selection sort 4

8. Insertion sort 4

9. Merge sort 4
10. First n prime numbers 4

11. Multiply matrices 4

12. Programs that take command line arguments (word count) 4

13. Find the most frequent words in a text read from a file 4

14. Simulate elliptical orbits in Pygame 4

15. Simulate bouncing ball using Pygame 4

Total Hours 60

CONTENT BEYOND THE SYLLABUS:

 Study on PIP(Package Manager) in Python


 To Create GUI apps in Python using Tkinter

At the end of the course, the students will be able to:

 Write, test, and debug simple Python programs


 Implement Python programs with conditionals and loops.
 Develop Python programs step-wise by defining functions and calling them.
 Use Python lists, tuples, dictionaries for representing compound data.
 Read and write data from/to files in Python.

Justification of mapping:
PO1 strongly maps since it needs engineering knowledge to solve python programs. PO2
C107.1 and PO3 weakly maps to this CO since it deals with simple problems. Since Python
supports lifelong learning ability to create solutions this CO maps PO12

PO1 strongly maps since it needs engineering knowledge to solve python programs. PO3
weakly maps to this CO since it deals with simple problems. Since Python supports life long
C107.2 learning ability to create solutions this CO maps PO12

PO1, PO2,PO3 strongly maps to this CO since it deals with development of solutions by
applying engineering knowledge and problem analysis.PO5 maps with this CO since it uses
C107.3
Python platform to solve problems . Since Python supports life long learning ability to
create solutions this CO maps PO12

PO1 and PO3 strongly maps to since it needs engineering knowledge design and
C107.4 development of solutions. PO4 and PO5 maps with this CO since it uses Python platform to
solve complex problems

PO1 strongly maps to this CO since it needs detailed knowledge for handling files using
C107.5
Python.

PO4 and PO5 strongly maps. Since it uses multiple tools for creating solutions to complex
CBS1 problems. Since developing real time solutions for problems uses Python and MYSQL
supports life long learning ability so PO12 strongly maps.

PO4 and PO5 strongly maps. Since PIP is a modern tools for managing Python Add on
CBS2 softwares.PO12 strongly maps since this is used for managing all the software packages
used in Python projects.
TABLE OF CONTENTS

Record Sign
EX.NO DATE TITLE
Mark
1 Introduction to Python

2 Compute the GCD of two numbers

Find the square root of a number (Newton’s


3 method)

4 Exponentiation (power of a number)

5 Find the maximum of a list of numbers

6a Linear search

6b Binary search

7 Selection sort

8 Insertion sort

9 Merge Sort

10 First n prime numbers

11 Multiply matrices

Programs that take command line arguments


12 (word count)

Find the most frequent words in a text read


13
from a file
14 Simulate elliptical orbits in Pygame
15 Simulate bouncing ball using Pygame
Record Sign
EX.NO DATE TITLE
Mark

CONTENT BEYOND THE SYLLABUS

16a Study on PIP(Package Manager) in Python


16b To Create GUI apps in Python using Tkinter

Ex.No.1 Introduction to Python

Introduction
Python is ahigh-level, general-purpose, interpreted, interactive, object-oriented
dynamic programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL). Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after
Python-the snake.
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been back ported to be
compatible with version 2.7
Installing Python
Virtually all modern programming languages make us of an IDE, or Integrated
Development Environment, which allows the creation, editing, testing, and saving of
programs and modules.
For Python programming you need a working Python installation and a text editor.
Python comes with its own editor, IDLE, which is quite nice and totally sufficient for the
beginning. 
The Python download page is http://www.python.org/download. The most recent
version is Python 3.5.3 (as of January 2017);
Windows users
Download the appropriate Windows installer (the x86 MSI installer, if you do not
have a 64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the
prompts.
See https://docs.python.org/3/using/windows.html#installing-python for information.
Mac users
Starting from Mac OS X Tiger, Python ships by default with the operating system,
but you will need to update to Python 3 until OS X starts including Python 3 (check the
version by starting python3 in a command line terminal). Also IDLE (the Python editor)
might be missing in the standard installation. If you want to (re-)install Python, get the
MacOS installer from the Python download site.

Linux, BSD, and UNIX users

You are probably lucky and Python is already installed on your machine. To test it
type python3 on a command line. If you see something like what is shown in the following
section, you are set.
IDLE may need to be installed separately, from its own package such as idle3 or as
part of python-tools.
If you have to install Python, first try to use the operating system's package
manager or go to the repository where your packages are available and get Python 3.
Python 3.0 was released in December 2008; all distributions should have Python 3
available, so you may not need to compile it from scratch. Ubuntu and Fedora do have
Python 3 binary packages available, but they are not yet the default, so they need to be
installed specially.
Roughly, here are the steps to compile Python from source code in Unix (If these
totally don't make sense, you may want to read another introduction to *nix, such
as Introduction to Linux):

 Download the .tgz file (use your Web browser to get the gzipped tar file
from https://www.python.org/downloads/release/python-343)
 Uncompress the tar file (put in the correct path to where you downloaded it):

$ tar -xvzf ~/Download/Python-3.4.3.tgz


... list of files as they are uncompressed

 Change to the directory and tell the computer to compile and install the program

cd Python-3.4/
$ ./configure --prefix=$HOME/python3_install
... lots of output. Watch for error messages here ...
$ make
... even more output. Hopefully no error messages ...
$ make install

 Add Python 3 to your path. You can test it first by specifying the full path. You
should add $HOME/python3_install/bin to your PATH bash variable.

$ ~/python3_install/bin/python3
Python 3.4.3 (... size and date information ...)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The above commands will install Python 3 to your home directory, which is probably
what you want, but if you skip the --prefix=$HOME/python3_install, it will install it
to /usr/local. If you want to use the IDLE graphical code editor, you need to make sure that
the tk and tcl libraries, together with their development files, are installed on the system.
You will get a warning during the make phase if these are not available.

Configuring your PATH environment variable


The PATH environment variable is a list of folders, separated by semicolons, in
which Windows will look for a program whenever you try to execute one by typing its
name at a Command Prompt. You can see the current value of your PATH by typing this
command at a Command Prompt:

echo %PATH%

The easiest way to permanently change environment variables is to bring up the


built-in environment variable editor in Windows. How you get to this editor is slightly
different on different versions of Windows.
On Windows 8 or Windows 10:
Press the Windows key and type Control Panel to locate the Windows Control Panel.
Once you've opened the Control Panel, select View by: Large Icons, then click on System. In
the window that pops up, click the Advanced System Settings link, then click
the Environment Variables... button.
On Windows 7 or Vista:
Click the Start button in the lower-left corner of the screen, move your mouse
over Computer, right-click, and select Properties from the pop-up menu. Click the Advanced
System Settings link, then click the Environment Variables... button.

On Windows XP:
Right-click the My Computer icon on your desktop and select Properties. Select
the Advanced tab, then click the Environment Variables... button.

Once you've brought up the environment variable editor, you'll do the same thing
regardless of which version of Windows you're running. Under System Variables in the
bottom half of the editor, find a variable called PATH. If there is is one, select it and
click Edit.... Assuming your Python root is C:\Python34, add these two folders to your path
(and make sure you get the semicolons right; there should be a semicolon between each
folder in the list):

:\Python34
C:\Python34\Scripts

Python programming – modes


Python has two basic modes: normal and interactive. The normal mode is the mode
where the scripted and finished .py files are run in the Python interpreter. Interactive mode
is a command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory. As new lines are fed into the interpreter, the
fed program is evaluated both in part and in whole.
Interactive mode is a good way to play around and try variations on syntax.
On macOS or linux, open a terminal and simply type "python". On Windows, bring
up the command prompt and type "py", or start an interactive Python session by selecting
"Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is
a GUI which includes both an interactive mode and options to edit and run files.

Python should print something like this:

$ python
Python 3.0b3 (r30b3:66303, Sep 8 2008, 14:01:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> is Python's way of telling you that you are in interactive mode. In interactive mode
what you type is immediately run. Try typing 1+1 in. Python will respond with 2.
Interactive mode allows you to test out and see what Python will do. If you ever feel the
need to play with new Python statements, go into interactive mode and try them out.

A sample interactive session:

>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'
>>> "hello".__class__
<type 'str'>

However, you need to be careful in the interactive environment to avoid confusion.


For example, the following is a valid Python script:

if 1:
print("True")
print("Done")

If you try to enter this as written in the interactive environment, you might be surprised by
the result:

>>> if 1:
... print("True")
... print("Done")
File "<stdin>", line 3
print("Done")
^
SyntaxError: invalid syntax

What the interpreter is saying is that the indentation of the second print was
unexpected. You should have entered a blank line to end the first (i.e., "if") statement,
before you started writing the next print statement. For example, you should have entered
the statements as though they were written:

if 1:
print("True")

print("Done")

Which would have resulted in the following:

>>> if 1:
... print("True")
...
True
>>> print("Done")
Done
>>>

Interactive mode

Instead of Python exiting when the program is finished, you can use the -i flag to
start an interactive session. This can be very useful for debugging and prototyping.

python -i hello.py
Ex.No.1 Introduction to Python

Introduction
Python is ahigh-level, general-purpose, interpreted, interactive, object-oriented
dynamic programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL). Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after
Python-the snake.
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been back ported to be
compatible with version 2.7
Installing Python
Virtually all modern programming languages make us of an IDE, or Integrated
Development Environment, which allows the creation, editing, testing, and saving of
programs and modules.
For Python programming you need a working Python installation and a text editor.
Python comes with its own editor, IDLE, which is quite nice and totally sufficient for the
beginning. 
The Python download page is http://www.python.org/download. The most recent
version is Python 3.5.3 (as of January 2017);
Windows users
Download the appropriate Windows installer (the x86 MSI installer, if you do not
have a 64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the
prompts.
See https://docs.python.org/3/using/windows.html#installing-python for information.
Mac users
Starting from Mac OS X Tiger, Python ships by default with the operating system,
but you will need to update to Python 3 until OS X starts including Python 3 (check the
version by starting python3 in a command line terminal). Also IDLE (the Python editor)
might be missing in the standard installation. If you want to (re-)install Python, get the
MacOS installer from the Python download site.
Linux, BSD, and UNIX users

You are probably lucky and Python is already installed on your machine. To test it
type python3 on a command line. If you see something like what is shown in the following
section, you are set.
IDLE may need to be installed separately, from its own package such as idle3 or as
part of python-tools.
If you have to install Python, first try to use the operating system's package
manager or go to the repository where your packages are available and get Python 3.
Python 3.0 was released in December 2008; all distributions should have Python 3
available, so you may not need to compile it from scratch. Ubuntu and Fedora do have
Python 3 binary packages available, but they are not yet the default, so they need to be
installed specially.
Roughly, here are the steps to compile Python from source code in Unix (If these
totally don't make sense, you may want to read another introduction to *nix, such
as Introduction to Linux):

 Download the .tgz file (use your Web browser to get the gzipped tar file
from https://www.python.org/downloads/release/python-343)
 Uncompress the tar file (put in the correct path to where you downloaded it):

$ tar -xvzf ~/Download/Python-3.4.3.tgz


... list of files as they are uncompressed

 Change to the directory and tell the computer to compile and install the program

cd Python-3.4/
$ ./configure --prefix=$HOME/python3_install
... lots of output. Watch for error messages here ...
$ make
... even more output. Hopefully no error messages ...
$ make install

 Add Python 3 to your path. You can test it first by specifying the full path. You
should add $HOME/python3_install/bin to your PATH bash variable.

$ ~/python3_install/bin/python3
Python 3.4.3 (... size and date information ...)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The above commands will install Python 3 to your home directory, which is probably
what you want, but if you skip the --prefix=$HOME/python3_install, it will install it
to /usr/local. If you want to use the IDLE graphical code editor, you need to make sure that
the tk and tcl libraries, together with their development files, are installed on the system.
You will get a warning during the make phase if these are not available.

Configuring your PATH environment variable


The PATH environment variable is a list of folders, separated by semicolons, in
which Windows will look for a program whenever you try to execute one by typing its
name at a Command Prompt. You can see the current value of your PATH by typing this
command at a Command Prompt:

echo %PATH%

The easiest way to permanently change environment variables is to bring up the


built-in environment variable editor in Windows. How you get to this editor is slightly
different on different versions of Windows.
On Windows 8 or Windows 10:
Press the Windows key and type Control Panel to locate the Windows Control Panel.
Once you've opened the Control Panel, select View by: Large Icons, then click on System. In
the window that pops up, click the Advanced System Settings link, then click
the Environment Variables... button.
On Windows 7 or Vista:
Click the Start button in the lower-left corner of the screen, move your mouse
over Computer, right-click, and select Properties from the pop-up menu. Click the Advanced
System Settings link, then click the Environment Variables... button.

On Windows XP:

Right-click the My Computer icon on your desktop and select Properties. Select


the Advanced tab, then click the Environment Variables... button.
Once you've brought up the environment variable editor, you'll do the same thing
regardless of which version of Windows you're running. Under System Variables in the
bottom half of the editor, find a variable called PATH. If there is is one, select it and
click Edit.... Assuming your Python root is C:\Python34, add these two folders to your path
(and make sure you get the semicolons right; there should be a semicolon between each
folder in the list):

:\Python34
C:\Python34\Scripts

Python programming – modes


Python has two basic modes: normal and interactive. The normal mode is the mode
where the scripted and finished .py files are run in the Python interpreter. Interactive mode
is a command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory. As new lines are fed into the interpreter, the
fed program is evaluated both in part and in whole.
Interactive mode is a good way to play around and try variations on syntax.
On macOS or linux, open a terminal and simply type "python". On Windows, bring
up the command prompt and type "py", or start an interactive Python session by selecting
"Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is
a GUI which includes both an interactive mode and options to edit and run files.

Python should print something like this:

$ python
Python 3.0b3 (r30b3:66303, Sep 8 2008, 14:01:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is Python's way of telling you that you are in interactive mode. In interactive mode
what you type is immediately run. Try typing 1+1 in. Python will respond with 2.
Interactive mode allows you to test out and see what Python will do. If you ever feel the
need to play with new Python statements, go into interactive mode and try them out.

A sample interactive session:

>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'
>>> "hello".__class__
<type 'str'>

However, you need to be careful in the interactive environment to avoid confusion.


For example, the following is a valid Python script:

if 1:
print("True")
print("Done")

If you try to enter this as written in the interactive environment, you might be surprised by
the result:

>>> if 1:
... print("True")
... print("Done")
File "<stdin>", line 3
print("Done")
^
SyntaxError: invalid syntax

What the interpreter is saying is that the indentation of the second print was
unexpected. You should have entered a blank line to end the first (i.e., "if") statement,
before you started writing the next print statement. For example, you should have entered
the statements as though they were written:
if 1:
print("True")

print("Done")

Which would have resulted in the following:

>>> if 1:
... print("True")
...
True
>>> print("Done")
Done
>>>

Interactive mode

Instead of Python exiting when the program is finished, you can use the -i flag to
start an interactive session. This can be very useful for debugging and prototyping.

python -i hello.py
Ex.No.2 Compute GCD of two numbers
Aim:

To Write a Python program to compute the GCD of two numbers.

Algorithm:

Step 1: Start

Step 2: Take two numbers from the user as input

Step 3: Calculate the remainder d1%d2

Step 4: While the remainder is not equal to 0

Step 5: d1=d2

Step 6: d2=remainder

Step 7: remainder=d1 % d2

Step 8: print the GCD

Step 9: Stop

Output:

Enter the first number:15


Enter the second number:5
The GCD of the two numbers is 5
Result:

Thus the Python program to compute the GCD of two numbers was created and
executed successfully.
Ex.N0.3 Find the square root of Number(Newtons Method)
Aim:

To Write a Python program to find the square root of a number (Newton’s method)

Algorithm:

Step 1: Start

Step 2: The first parameter is the value whose square root will be approximated.

Step 3: The second is the number of times to iterate the calculation yielding a better
result from the user.

Step 4: Calculate better = ½*(approx.+n/approx.)

Step 5: Print the final result

Step 6: Stop

Output:

>>> my_sqrt(16)
4.0000006366929393
Result:

Thus the Python program to find the square root of a number (Newton’s method)
was created and executed successfuly
Ex.N0.4 Exponentiation (Power of a Number)
Aim:

To Write a Python program to find the exponentiation (Power of a number)

Algorithm:

Step 1: Start

Step 2: r->n

Step 3: Read Base Number n

Step 4: Read Exponent Number e

Step 5: FOR i-> 1 to e

Step 5.1: Compute r->n*r

Step 6: Print ‘Exponent’ r

Step 7: Stop

Output:

Enter base: 2
Enter exponential value: 5
Result: 32
Result:

Thus the a Python program to find the exponentiation (Power of a number) was
created and executed successfully
Ex.N0.5 Find the maximum of a list of numbers
Aim:

To write a Python program to find the maximum of a list of numbers.

Algorithm:

Step 1: Start

Step 2: Take n the number of elements and store it in a variable.

Step 3: Take the elements of the list one by one.

Step 4: Sort the list in ascending order.

Step 5: Print the last element of the list

Step 6: Stop

Output:

Enter number of elements:3

Enter element:23

Enter element:567

Enter element:3

Largest element is: 567


Result:

Thus a Python program to find the maximum of a list of numbers was created and
executed successfully.
Ex.N0.6a Linear Search
Aim:

To write a python program to search an element in an array using Linear search


technique.

Algorithm:

Step 1: Start

Step 2: Get list of elements from the user

Step 3: Get the number to be searched

Step 4: Set i to 1

Step 5: if i>n then go to step 7

Step 6: if A[i]=x then go to step 6

Step 7: Set I to i+1

Step 8: Go to Step 2

Step 9: Print Element x found at index I and step 8

Step 10: Print element not found

Step 11: Stop

Output:

Enter the list of elements: 10 15 20 24 98

Enter the element to be searched: 20

20 found at position 3
Result:

Thus a python program to search an element was created using linear search
technique and executed successfully
Ex.N0.6b Binary Search
Aim:

To write a Python program to search an element in a list of elements using Binary


search technique.

Algorithm:

Step 1:Start

Step 2: Get list of elements from the user

Step 3: Get the number to be searched

Step 4: Found<-False

Step 5:While not found and first <=top

if List[Midpoint]=ItemSought Then

ItemFound=True

Elif first>=Last Then

SearchFailed=True
Elif List[Midpoint]>ItemSought Then
Last=Midpoint-1
Else
First=Midpoint+1
End if
End While
Step 7: Stop

Output:
Enter the list of elements: 10 15 20 24 98

Enter the element to be searched: 20

20 found at position 3
Result:

Thus a python program to search an element using Binary search technique was
created and executed successfully
Ex.N0.7 Selection Sort
Aim:

To write a Python program to sort the elements using selection sort.

Algorithm:

Step 1: Start

Step 2: Get the elements from the user

Step 3: Set MIN to location 0

Step 4: Search the minimum element in the list.

Step 5: Swap with value at location MIN

Step 6: Increment MIN to point to next element

Step 7: Repeat until list is sorted.

Step 8: Stop

Output:

Enter the elements: [55, 20, 54, 17, 31, 93, 44, 26, 77]

[17, 20, 26, 31, 44, 54, 55, 77, 93]


Result:

Thus a Python programs to sort elements using selection sort method was created
and executed successfully.
Ex.N0.8 Insertion Sort
Aim:

To write a Python program to sort the elements using insertion sort .

Algorithm:

Step 1: Start

Step 2: Get the elements from the user

Step 3a: The second element in the list is compared with the elements that appear
before it (only first element in this case).

Step 3b: If the second element is smaller than first element, second element is
inserted in the position of first element. After first step, first two elements of an
array will be sorted.

Step 3c: Pick next element

Step 8: Repeat step 3 until all the elements in the list is sorted

Step 9: Stop

Output:

Enter the elements: [55, 20, 54, 17, 31, 93, 44, 26, 77]

[17, 20, 26, 31, 44, 54, 55, 77, 93]


Result:

Thus a Python program to sort the elements using selection sort method was
created and executed successfully
Ex.N0.9 Merge Sort

Aim:

To write a Python program to sort elements using merge sort method.

Algorithm:

Step 1: Start

MERGE-SORT(A,p,r)

Step 2: if r>p

Step 3: Find the middle point to divide the array into two halves:

Then q=FLOOR [(p+r)/2] //Divide step

Step 4: Call merge Sort for first half:

Call MERGE (A,p,q)

Step 5: Call merge Sort for second half:

Call MERGE (A,q+1,r)

Step 6: Merge the two halves sorted in step 2 and 3:

Call MERGE (A,p,q,r) //Conquer step

Step 7: Stop

Output:

[1, 2, 5, 7, 8, 10]
Result:

Thus a Python programs to sort the element using merge sort method was created
and executed successfully
Ex.N0.10 Find n Prime numbers

Aim:

To Write a Python program to find the first n prime numbers.

Algorithm:

Step 1: Start

Step 2: Take the number to be checked and store it in a variable.

Step 3: Initialize the count variable to 0

Step 4: Let the for loop range from 2 to half number (excluding 1 and the number
itself).

Step 5: Then find the number of divisors using the if statement and increment the
count variable each time.

Step 6: If the number of divisors is lesser than or equal to 0, the number is prime.

Step 7: Print the final result

Step 8: Stop

Output:

Enter the number: 10

11

13
15

17
Result:

Thus a Python program to find the first n prime numbers was created and executed
successfully.
Ex.N0.11 Multiply Matrices

Aim:

To write a Python program to multiply two matrices.

Algorithm:

Step 1: Start

Step 2: Declare variables and initialize necessary variables

Step 3: Enter the element of matrices by row wise using loops

Step 4: Check the numbers of rows and column of first and second matrices

Step 5: If number of rows of first matrix is equal to the number of columns of second
matrix, go to Otherwise, print matrix multiplications are not possible and go to step
3

Step 6: Multiply the matrices using nested loops

Step 7: Print the product in matrix form as console output.

Step 8: Stop

Output:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]


Result:

Thus a Python program to multiply two matrices was created and executed
successfully
Ex.N0.12 Programs that take command line arguments (word count)

Aim:

To write a Python program to take command line arguments(word count)

Algorithm:

Step 1: Start

Step 2: Take the file name from the user

Step 3: Read each line from a file and split a lines to form a list of words

Step 4: Find the length of items in a list and print it

Step 5: Stop

Output:

Enter the File name: python.py

Number of words: 12
Result:

Thus a Python program for word count was created and executed successfully
Ex.N0.13 Find the most frequent words in a text read from a file
Aim:

To write a Python program to find the most frequent words in a text read from a file

Algorithm:

Step 1: Start

Step 2: Create a file in a notepad and save it with .py extension.

Step 2: Take the file name and letter to be counted from the user

Step 2: Read each line from the file and split the line to form a list of words.

Step 3: Use a for loop to traverse through the words in the list and another for loop
to traverse through the letters in the word

Step 4: Check if the letter provided by the user and the letter encountered over
iteration is equal and if they are, increment the letter count.

Step 5: stop

Output:

Enter the File name: python.py

Enter the letter to be searched: e

Occurrences of the letter: 20


Result:

Thus a Python program to find the most frequent words in a text read from a file
was created and successfully
Ex.N0.14 Simulate elliptical orbits in Pygame

Aim:

To write a Python program to simulate elliptical orbits in pygame.

Algorithm:

Step 1: Start

Step 2: Import necessary mathematical function library from numpy package

Step 3: Import plot library

Step 4: Create the necessary window and

Step 5: draw elliptical orbit by using the equation ay2 + bxy + cx + dy + e = x2

Step 6:Plot the points using Scatter plot functions and draw orbit

Step 7: Stop

Output:
Result:

Thus a Python program to simulate elliptical orbits in pygame was created and
executed successfully.
Ex.N0.15 Simulate bouncing ball using Pygame
Aim:

To write a Python program to simulate bouncing ball using pygame.

Algorithm:

Step 1: Start

Step 2: Import necessary GUI for simulation

Step 3: Set the window coordinates and the ball coordiates

Step 4: Assign various colors for the ball and set the base color

Step 5: Fix the color, shape and bouncing speed randomly

Step 6: Write a function to move the base according to the ball position

Step 7: Stop

Output:

Result:

Thus a Python program to simulate bouncing ball using pygame was simulated
successfully
Ex.N0.16.a Introduction to PIP(Packet Manager)

pip is a package management system used to install and manage software packages written in
Python. Many packages can be found in the default source for packages and their dependencies
— Python Package Index (PyPI).[4]

Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip (pip3 for
Python 3) by default.[5]Starting with pip 10.0.0, python 2.6 is no longer supported. Users willing
to use pip on python 2.6 should stay on version 9.[6]

pip is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs
Python".[7][8] Alternatively, pip stands for "preferred installer program".

Command-line interface

Most distributions of Python come with pip preinstalled. If pip is missing, it can be installed
through the system package manager or by invoking cURL, a client-side data transfer tool:

curl https://bootstrap.pypa.io/get-pip.py | python

One major advantage of pip is the ease of its command-line interface, which makes installing
Python software packages as easy as issuing one command:

pip install some-package-name

Users can also easily remove the package:

pip uninstall some-package-name

Most importantly pip has a feature to manage full lists of packages and corresponding version
numbers, possible through a "requirements" file. [4] This permits the efficient re-creation of an
entire group of packages in a separate environment (e.g. another computer) or virtual
environment. This can be achieved with a properly formatted requirements.txt file and the
following command:

pip install -r requirements.txt

Install some package for a specific version python, where ${version} is replaced for 2, 3, 3.4, etc.:

pip${version} install some-package-name

Result:

Thus the PIP(Packet Manager) is installed and studied using Python


Ex.N0.16.b Introduction to GUI programming with Tkinter in Python

Tkinter basics

Tkinter provides us with a variety of common GUI elements which we can use to build our
interface – such as buttons, menus and various kinds of entry fields and display areas. We call
these elements widgets. We are going to construct a tree of widgets for our GUI – each widget
will have a parent widget, all the way up to the root window of our application. For example, a
button or a text field needs to be inside some kind of containing window.

The widget classes provide us with a lot of default functionality. They have methods for
configuring the GUI’s appearance – for example, arranging the elements according to some kind
of layout – and for handling various kinds of user-driven events. Once we have constructed the
backbone of our GUI, we will need to customise it by integrating it with our internal application
class.

Our first GUI will be a window with a label and two buttons:

from tkinter import Tk, Label, Button

class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple GUI")

self.label = Label(master, text="This is our first GUI!")


self.label.pack()

self.greet_button = Button(master, text="Greet", command=self.greet)


self.greet_button.pack()

self.close_button = Button(master, text="Close", command=master.quit)


self.close_button.pack()

def greet(self):
print("Greetings!")

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

Try executing this code for yourself. You should be able to see a window with a title, a text label
and two buttons – one which prints a message in the console, and one which closes the window.
The window should have all the normal properties of any other window you encounter in your
window manager – you are probably able to drag it around by the titlebar, resize it by dragging
the frame, and maximise, minimise or close it using buttons on the titlebar.

There are many ways in which we could organise our application class. In this example, our class
doesn’t inherit from any tkinter objects – we use composition to associate our tree of widgets with
our class. We could also use inheritance to extend one of the widgets in the tree with our custom
functions.

root.mainloop()is a method on the main window which we execute when we want to run our
application. This method will loop forever, waiting for events from the user, until the user exits
the program – either by closing the window, or by terminating the program with a keyboard
interrupt in the console.

Widget classes

There are many different widget classes built into tkinter – they should be familiar to you from
other GUIs:

 A Frame is a container widget which is placed inside a window, which can have its own border
and background – it is used to group related widgets together in an application’s layout.
 Toplevel is a container widget which is displayed as a separate window.

 Canvas is a widget for drawing graphics. In advanced usage, it can also be used to create custom
widgets – because we can draw anything we like inside it, and make it interactive.

 Text displays formatted text, which can be editable and can have embedded images.

 A Button usually maps directly onto a user action – when the user clicks on a button, something
should happen.

 A Label is a simple widget which displays a short piece of text or an image, but usually isn’t
interactive.

 A Message is similar to a Label, but is designed for longer bodies of text which need to be
wrapped.

 A Scrollbar allows the user to scroll through content which is too large to be visible all at once.

 Checkbutton, Radiobutton, Listbox, Entry and Scale are different kinds of input widgets – they allow
the user to enter information into the program.

 Menu and Menubutton are used to create pull-down menus.

Layout options

The GUI in the previous example has a relatively simple layout: we arranged the three widgets in
a single column inside the window. To do this, we used the pack method, which is one of the
three different geometry managers available in tkinter. We have to use one of the available
geometry managers to specify a position for each of our widgets, otherwise the widget will not
appear in our window.

By default, pack arranges widgets vertically inside their parent container, from the top down, but
we can change the alignment to the bottom, left or right by using the optional side parameter. We
can mix different alignments in the same container, but this may not work very well for complex
layouts. It should work reasonably well in our simple case, however:
from tkinter import LEFT, RIGHT

# (...)

self.label.pack()
self.greet_button.pack(side=LEFT)
self.close_button.pack(side=RIGHT)

We can create quite complicated layouts with pack by grouping widgets together in frames and
aligning the groups to our liking – but we can avoid a lot of this complexity by using the grid
method instead. It allows us to position widgets in a more flexible way, using a grid layout. This
is the geometry manager recommended for complex interfaces:

from tkinter import W

# (...)

self.label.grid(columnspan=2, sticky=W)
self.greet_button.grid(row=1)
self.close_button.grid(row=1, column=1)

We place each widget in a cell inside a table by specifying a row and a column – the default row
is the first available empty row, and the default column is 0.

If a widget is smaller than its cell, we can customise how it is aligned using the sticky parameter –
the possible values are the cardinal directions (N, S, E and W), which we can combine through
addition. By default, the widget is centered both vertically and horizontally, but we can make it
stick to a particular side by including it in the sticky parameter. For example, sticky=W will cause
the widget to be left-aligned horizontally, and sticky=W+E will cause it to be stretched to fill the
whole cell horizontally. We can also specify corners using NE, SW, etc..

To make a widget span multiple columns or rows, we can use the columnspan and rowspan options
– in the example above, we have made the label span two columns so that it takes up the same
space horizontally as both of the buttons underneath it.

Custom events

So far we have only bound event handlers to events which are defined in tkinter by default – the
Button class already knows about button clicks, since clicking is an expected part of normal
button behaviour. We are not restricted to these particular events, however – we can make
widgets listen for other events and bind handlers to them, using the bind method which we can
find on every widget class.

Events are uniquely identified by a sequence name in string format – the format is described by a
mini-language which is not specific to Python. Here are a few examples of common events:

 "<Button-1>", "<Button-2>" and "<Button-3>" are events which signal that a particular mouse button
has been pressed while the mouse cursor is positioned over the widget in question. Button 1 is the
left mouse button, Button 3 is the right, and Button 2 the middle button – but remember that not
all mice have a middle button.
 "<ButtonRelease-1>" indicates that the left button has been released.

 "<B1-Motion>" indicates that the mouse was moved while the left button was pressed (we can use
B2 or B3 for the other buttons).

 "<Enter>" and "<Leave>" tell us that the mouse curson has entered or left the widget.

 "<Key>" means that any key on the keyboard was pressed. We can also listen for specific key
presses, for example "<Return>" (the enter key), or combinations like "<Shift-Up>" (shift-up-
arrow). Key presses of most printable characters are expressed as the bare characters, without
brackets – for example, the letter a is just "a".

 "<Configure>" means that the widget has changed size.


Result:
Thus a GUI programming with Tkinter in Python is studied.

You might also like