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

Internship Project

Python is a widely used general-purpose programming language that was initially designed by Guido van Rossum in 1991. It emphasizes code readability through the use of whitespace indentation to define code blocks. The key advantages of Python include being free, powerful, portable, easy to use and learn, and having an interpreted runtime. It can be installed on Windows by downloading the Python software from python.org. Variables in Python do not require declaration and are dynamically typed, with names being case-sensitive. Values can be assigned to multiple variables simultaneously through multiple assignment.

Uploaded by

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

Internship Project

Python is a widely used general-purpose programming language that was initially designed by Guido van Rossum in 1991. It emphasizes code readability through the use of whitespace indentation to define code blocks. The key advantages of Python include being free, powerful, portable, easy to use and learn, and having an interpreted runtime. It can be installed on Windows by downloading the Python software from python.org. Variables in Python do not require declaration and are dynamically typed, with names being case-sensitive. Values can be assigned to multiple variables simultaneously through multiple assignment.

Uploaded by

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

Python

1. INTRODUCTION
Python is a widely used general-purpose, high level programming language. It
was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation. It was mainly developed for emphasis on code readability, and its syntax
allows programmers to express concepts in fewer lines of code. Python is a programming
language that lets you work quickly and integrate systems more efficiently.

There are two major Python versions- Python 2 and Python 3.

• On 16 October 2000, Python 2.0 was released with many new features.

• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.

1.1. Beginning with Python programming

1.1.1. Finding an Interpreter

Before we start Python programming, we need to have an interpreter to interpret


and run our programs. There are certain online interpreters like
https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/ that can be used
to start Python without installing an interpreter.

Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from http://python.org/downloads/

1.1.2. Writing first program

# Script Begins

Statement1

Statement2

Statement3

# Script Ends

1.2. Why to use Python

Dept. of ECE, UCET, MGU, Nalgonda 1


Python

The following are the primary factors to use python in day-to-day life:

 Python is object-oriented Structure supports such concepts as polymorphism,


operation overloading and multiple inheritance.
 Indentation
Indentation is one of the greatest feature in python.
 It‟s free (open source)
Downloading python and installing python is free and easy
 It‟s Powerful
o Dynamic typing
o Built-in types and tools
o Library utilities
o Third party utilities (e.g. Numeric, NumPy, sciPy)
o Automatic memory management
 It‟s Portable
o Python runs virtually every major platform used today.
o As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
 It‟s easy to use and learn
o No intermediate compile
o Python Programs are compiled automatically to an intermediate form
called byte code, which the interpreter then reads.
o This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
o Structure and syntax are pretty intuitive and easy to grasp.
 Interpreted Language
o Python is processed at runtime by python Interpreter
 Interactive Programming Language
o Users can interact with the python interpreter directly for writing the
programs
 Straight forward syntax
o The formation of python syntax is simple and straight forward which also
makes it popular.

Dept. of ECE, UCET, MGU, Nalgonda 2


Python

1.3. Installation
There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional).

Figure.1.1. Python installation

Dept. of ECE, UCET, MGU, Nalgonda 3


Python

1.3.1. Python Code Execution

Python‟s traditional runtime execution model: Source code you type is translated
to byte code, which is then run by the Python Virtual Machine (PVM). Your code is
automatically compiled, but then it is interpreted.

Figure.1.2. Source code extension is .py

byte code extension is . pyc (Compiled python code)

Dept. of ECE, UCET, MGU, Nalgonda 4


Python

2. INDENTATION IN PYTHON

Indentation is a very important concept of Python because without proper


indenting the Python code, you will end up seeing IndentationError and the code will
not get compiled. Python indentation is a way of telling a Python interpreter that the
group of statements belongs to a particular block of code. A block is a combination of all
these statements. Block can be regarded as the grouping of statements for a specific
purpose. Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented further
to the right.

2.1. The cause of Indentation Error in Python

As mentioned in the introduction paragraph, one of the main reasons for the
indentation error is the absence of tabs and or whitespaces between lines of code. Since
python makes use of procedural language, if you miss out on adding tabs or spaces
between your lines of code, then you will most likely experience this error. Although in
some cases the entire program will run correctly, in others the error will come in the
middle of the execution and therefore pause the entire process.

Mentioned below are some of the common causes of an indentation error in Python:
 While coding you are using both the tab as well as space. While in theory both of
them serve the same purpose, if used alternatively in a code, the interpreter gets
confused between which alteration to use and thus returns an error.
 While programming you have placed an indentation in the wrong place. Since
python follows strict guidelines when it comes to arranging the code, if you
placed any indentation in the wrong place, the indentation error is mostly
inevitable.
 Sometimes in the midst of finishing a long program, we tend to miss out on
indenting the compound statements such as for, while and if and this in most cases
will lead to an indentation error.
 Last but not least, if you forget to use user defined classes, then an indentation
error will most likely pop up.

Dept. of ECE, UCET, MGU, Nalgonda 5


Python

3. VARIABLES
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory. Based on the data
type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals or characters in these variables.

3.1. Rules for Python variables

 A variable name must start with a letter or the underscore character.


 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
 Variable names are case-sensitive (age, Age and AGE are three different
variables).
3.2. Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign
(=) is used to assign values to variables. The operand to the left of the = operator is the
name of the variable and the operand to the right of the operator is the value stored in the
variable.

For example:

a= 100 # An integer assignment

b = 1000.0 # A floating point

c = "John" # A string

print (a)

print (b)

print (c)

This produces the following result :

Dept. of ECE, UCET, MGU, Nalgonda 6


Python

100

1000.0

John

3.2.1. Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example:

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.

For example:

a,b,c = 1,2,"mrcet“

Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

3.2.2. Output Variables

The Python print statement is often used to output variables.

Variables do not need to be declared with any particular type and can even change type
after they have been set.

x = 5 # x is of type int

x = "mrcet " # x is now of type str

print(x)

Output: mrcet

To combine both text and a variable, Python uses the “+” character:

Example

x = "awesome"

print("Python is " + x)

Dept. of ECE, UCET, MGU, Nalgonda 7


Python

Output

Python is awesome

You can also use the + character to add a variable to another variable:

Example:

x = "Python is "

y = "awesome"

z=x+y

print(z)

Output:

Python is awesome

3.3. Expressions

An expression is a combination of values, variables, and operators. An expression is


evaluated using assignment operator.
Examples: Y=x + 17

>>> x=10

>>> z=x+20

>>> z

30

>>> x=10

>>> y=20

>>> c=x+y

>>> c

30
A value all by itself is a simple expression, and so is a variable.
>>> y=20

Dept. of ECE, UCET, MGU, Nalgonda 8


Python

>>> y=20

Dept. of ECE, UCET, MGU, Nalgonda 9


Python

4. OPERATORS
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

4.1. Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common


mathematical operations:
Table 4.1. Arithmetic Operators
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

4.2. Python Assignment Operators

Assignment operators are used to assign values to variables:


Table 4.2. assignment operators
Operator Example Same As

= x=5 x=5

Dept. of ECE, UCET, MGU, Nalgonda 10


Python

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

4.3. Python Comparison Operators

Comparison operators are used to compare two values:


Table 4.3. Python Comparison Operators
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

Dept. of ECE, UCET, MGU, Nalgonda 11


Python

>= Greater than or x >= y


equal to

<= Less than or x <= y


equal to

4.4. Python Logical Operators

Logical operators are used to combine conditional statements:


Table 4.4. Python Logical Operators

Operator Description Example

and Returns True if both x < 5 and x <


statements are true 10

Or Returns True if one of the x < 5 or x < 4


statements is true

Not Reverse the result, returns not(x < 5 and


False if the result is true x < 10)

4.5. Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
Table 4.5. Python Identity Operators

Operator Description Example

Dept. of ECE, UCET, MGU, Nalgonda 12


Python

is Returns True if both x is y


variables are the same
object

is not Returns True if both x is not y


\ variables are not the same
object

4.6. Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Table 4.6. Python Membership Operators

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in


specified value is not present in the object y

4.7. Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Table 4.7. Python Bitwise Operators

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

Dept. of ECE, UCET, MGU, Nalgonda 13


Python

^ XOR Sets each bit to 1 if only one of two bits


is 1

~ NOT Inverts all the bits

<< Zero fill Shift left by pushing zeros in from the


left shift right and let the leftmost bits fall off

>> Signed Shift right by pushing copies of the


right shift leftmost bit in from the left, and let the
rightmost bits fall off

Dept. of ECE, UCET, MGU, Nalgonda 14


Python

5. DATA TYPES
The data stored in memory can be of many types. For example, a student roll
number is stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the operations
possible on them and the storage method for each of them.
5.1. Integer
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited Length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:

>>> type(10)

<class 'int'>

>>> a=11

>>> print(type(a))

<class 'int'>

Dept. of ECE, UCET, MGU, Nalgonda 15


Python

5.2. Float

Float, or "floating point number" is a number, positive or negative, containing one


or more decimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8

>>> y

2.8

>>> y=2.8

>>> print(type(y))

<class 'float'>

>>> type(.4)

<class 'float'>

>>> 2.

Example:

x = 35e3

y = 12E4

z = -87.7e100

print(type(x))

print(type(y))

print(type(z))

Output:

<class 'float'>

<class 'float'>

<class 'float'>

Dept. of ECE, UCET, MGU, Nalgonda 16


Python

5.3. Boolean

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

 Strings in Python are identified as a contiguous set of characters represented in


the Quotation marks. Python allows for either pairs of single or double quotes.
 'hello' is the same as "hello".
 Strings can be output to screen using the print function. For example:
print("hello").

>>> print("ucetmgu college")

ucetmgu college

>>> type("ucetmgu college")

<class 'str'>

>>> print(' ucetmgu college')

ucetmgu college

>>> " "

''

If you want to include either type of quote character within the string, the simplest
way is to delimit the string with the other type. If a string is to contain a single quote,
delimit it with double quotes and vice versa.

>>> print("ucetmgu is an autonomous (') college")

ucetmgu is an autonomous (') college

>>> print(' ucetmgu is an autonomous (") college')

Dept. of ECE, UCET, MGU, Nalgonda 17


Python

ucetmgu is an autonomous (") college

5.4. Suppressing Special Character

Specifying a backslash (\) in front of the quote character in a string “escapes” it and
causes Python to suppress its usual special meaning. It is then interpreted simply as a
literal single

5.4.1. Quote character

>>> print("ucetmgu is an autonomous (\') college")

ucetmgu is an autonomous (') college

>>> print(' ucetmgu is an autonomous (\") college')

ucetmgu is an autonomous (") college

5.4.2. List
 It is a general purpose most widely used in data structures.
 List is a collection which is ordered and changeable and allows duplicate
members. (Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many ways.
Ex: >>> list1=[1,2,3,‟A‟,‟B‟,7,8,[10,11]]
>>> print(list1)
[1, 2, 3, „A‟, „B‟, 7, 8, [10, 11]]

Dept. of ECE, UCET, MGU, Nalgonda 18


Python

6. DECISION MAKING
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions. Decision structures
evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to
determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.

Following is the general form of a typical decision making structure found in most of
the programming languages

Figure.6.1. Flowchart

Python programming language assumes any non-zero and non-null values as


TRUE, and if it is either zero or null, then it is assumed as FALSE value.

Python programming language provides following types of decision making statements.

Sr.No. Statement & Description

1 if statements

An if statement consists of a boolean


expression followed by one or more

Dept. of ECE, UCET, MGU, Nalgonda 19


Python

statements.

2 if...else statements

An if statement can be followed by an


optional else statement, which executes
when the boolean expression is FALSE.

3 nested if statements
You can use one if or else if statement inside
another if or else if statement(s).

6.1. Conditional (if)


The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.

Figure.6.2. Operation of if statement

Dept. of ECE, UCET, MGU, Nalgonda 20


Python

6.2. Alternative if (If-Else)


An else statement can be combined with an if statement. An else statement contains
the block of code (false block) that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value. The else statement is an optional statement and
there could be at most only one else Statement following if.
Syntax of if - else:
if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :

Figure.6.3. if-else Flowchart


6.3. Chained Conditional: (If-elif-else)
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
Syntax of if – elif - else :
If test expression:

Dept. of ECE, UCET, MGU, Nalgonda 21


Python

Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Figure.6.4. Flowchart of if – elif - else

Dept. of ECE, UCET, MGU, Nalgonda 22


Python

7. CONTROL FLOW, LOOPS


A loop statement allows us to execute a statement or group of statements multiple
times as long as the condition is true. Repeated execution of a set of statements with the
help of loops is called iteration. Loops statements are used when we need to run same
code again and again, each time with a different value.

7.1. Statements
In Python Iteration (Loops) statements are of three types:
 While Loop
 For Loop
 ested For Loops

7.1.1. While loop


 Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
 The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
 The statements that are executed inside while can be a single line of code or a
block of multiple statements.
Syntax:
while(expression):
Statement(s)

Dept. of ECE, UCET, MGU, Nalgonda 23


Python

Flowchart:

Figure.7.1.While loop Flowchart

7.1.2. For loop:


Python for loop is used for repeated execution of a group of statements for the
desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and
other iterable objects.
Syntax: for var in sequence:
Statement(s)
A sequence of values assigned to var in each iteration
Holds the value of item in sequence in each iteration.

Dept. of ECE, UCET, MGU, Nalgonda 24


Python

Figure.7.2. Operation of for loop


7.1.2.1. Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
For val in sequence:
For val in sequence:
Statements
Statements
 Nested for loop Syntax
The basic syntax of a nested for loop in Python is:
For [iterating_variable_1] in [sequence_1]: #Outer Loop
For [iterating_variable_2] in [iterating_variable_1/sequence_2]: #Inner Loop
[code to execute]
 Nested While Loop
Syntax
The syntax for nesting while loop in Python is:
while (expression_1): #Outer loop
[code to execute] #Optional
while (expression_2): #Inner loop [code to execute]

Dept. of ECE, UCET, MGU, Nalgonda 25


Python

8. PYTHON FUNCTIONS
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword
Arguments
Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.

8.1. Types of Functions in Python


In real-time, a Python function may define with or without parameters, and a
function may or may not return a value. It entirely depends upon the user requirement. In
Python programming, as per our requirement, We can define the User defined functions
in multiple ways. The following are the list of available types of functions in Python.
 Python Function with no argument and no return value.
 Function with no argument and with a Return value. .
 Python Function with argument and No Return value.
 Function with argument and return value.

8.1.1. Python Function with No argument and No Return value


In this type of function in Python, While defining, declaring, or calling the
function, We won‟t pass any arguments to the function. This type of Python function
won‟t return any value when we call the function.

8.1.2. Python Function with no argument and with a Return value


In this type of function in Python, We won‟t pass any arguments to the function
while defining, declaring, or calling the function. When we call the Python function, this
type of function returns some value.

8.1.3. Python Function with argument and No Return value

This type of function in Python allows us to pass the arguments to the function
while calling the function. But, This type of function in Python won‟t return any value
when we call the function.

Dept. of ECE, UCET, MGU, Nalgonda 26


Python

8.1.4. Python Function with argument and Return value


This type of python function allows us to pass the arguments to the function while
calling the function. This type of functions in Python returns some value when we call
the function. This type of user defined function called a fully dynamic function means it
provides maximum control to the end-user.

Dept. of ECE, UCET, MGU, Nalgonda 27


Python

9. PYTHON OOPS CONCEPTS


In Python, object-oriented Programming (OOPs) is a programming paradigm that
uses objects and classes in programming. It aims to implement real-world entities like
inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of
OOPs is to bind the data and the functions that work on that together as a single unit so
that no other part of the code can access this data.

9.1. Concepts of Object-Oriented Programming (OOPs)


 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance

9.1.1. Class
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes and
methods.
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute.
Class Definition Syntax:
ClassName
#statement1
.
.
.
#statement-N

9.1.2. Objects

The object is an entity that has a state and behavior associated with it. It may be
any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings,

Dept. of ECE, UCET, MGU, Nalgonda 28


Python

floating-point numbers, even arrays, and dictionaries, are all objects. More specifically,
any single integer or any single string is an object. The number 12 is an object, the string
“Hello, world” is an object, a list is an object that can hold other objects, and so on.
You‟ve been using objects all along and may not even realize it.

An object consists of :

 State: It is represented by the attributes of an object. It also reflects the properties of


an object.
 Behavior: It is represented by the methods of an object. It also reflects the response
of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with
other objects.
 The identity can be considered as the name of the dog.
 State or Attributes can be considered as the breed, age, or color of the dog.
 The behavior can be considered as to whether the dog is eating or sleeping.

Dept. of ECE, UCET, MGU, Nalgonda 29


Python

10. NUMPY
Numpy is a Python library used for working with arrays. It also has functions for working in
domain of linear algebra, fourier transform, and matrices. NumPy was created in 2005 by Travis
Oliphant. It is an open source project and you can use it freely. NumPy stands for Numerical
Python. In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists. The
array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy. Arrays are very frequently used in data science, where speed
and resources are very important. The source code for NumPy is located at this github repository
https://github.com/numpy/.

10.1. Arrays in Numpy

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of
nonnegative integers. The number of dimensions is the rank of the array; the shape of an
array is a tuple of integers giving the size of the array along each dimension.

Dept. of ECE, UCET, MGU, Nalgonda 30


Python

11. MATPLOTLIB

Matplotlib is a plotting library for the Python programming language and its
numerical mathematics extension NumPy. It provides an object-oriented API for
embedding plots into applications using general-purpose GUI toolkits like Tkinter,
wxPython, Qt, or GTK. Matplotlib was originally written by John D. Hunter. Since then it
has an active development community and is distributed under a BSD-style license.
Michael Droettboom was nominated as matplotlib's lead developer shortly before John
Hunter's death in August 2012 and was further joined by Thomas Caswell. Matplotlib
2.0.x supports Python versions 2.7 through 3.10. Python 3 support started with Matplotlib
1.2. Matplotlib 1.4 is the last version to support Python 2.6. Matplotlib has pledged not to
support Python 2 past 2020 by signing the Python 3 Statement.

Figure.11.1. Line Plot

Dept. of ECE, UCET, MGU, Nalgonda 31


Python

Figute.11.2. Histogram

Figure.11.3.3D Plot

Dept. of ECE, UCET, MGU, Nalgonda 32


Python

12. TIC TAC TOE

Tic Tac Toe is one of the most played games and is the best time killer game that you
can play anywhere with just a pen and paper. If you don‟t know how to play this game
don‟t worry let us first understand that. The game is played by two individuals. First, we
draw a board with a 3×3 square grid. The first player chooses „X‟ and draws it on any of
the square grid, then it‟s the chance of the second player to draw „O‟ on the available
spaces. Like this, the players draw „X‟ and „O‟ alternatively on the empty spaces until a
player succeeds in drawing 3 consecutive marks either in the horizontal, vertical or
diagonal way. Then the player wins the game otherwise the game draws when all spots
are filled.

11.1. Python Tic Tac Toe – Project Details

The interesting Python project will be build using the pygame library. We will be
explaining all the pygame object methods that are used in this project. Pygame is a
great library that will allow us to create the window and draw images and shapes on the
window. This way we will capture mouse coordinates and identify the block where we
need to mark „X‟ or „O‟. Then we will check if the user wins the game or not.

Prerequisites
To implement this game, we will use the basic concepts of Python and Pygame
which is a Python library for building cross-platform games. It contains the modules
needed for computer graphics and sound libraries. To install the library, you can use pip
installer from the command line
pip install pygame
Steps To Build A Python Tic Tac Toe Game
First, let‟s check the steps to build Tic Tac Toe program in Python:
 Create the display window for our game.
 Draw the grid on the canvas where we will play Tic Tac Toe.
 Draw the status bar below the canvas to show which player‟s turn
is it and who wins the game.
 When someone wins the game or the game is a draw then we reset
the game.

Dept. of ECE, UCET, MGU, Nalgonda 33


Python

We need to run our game inside an infinite loop. It will continuously look for events
and when a user presses the mouse button on the grid we will first get the X and Y
coordinates of the mouse. Then we will check which square the user has clicked. Then
we will draw the appropriate „X‟ or „O‟ image on the canvas. So that is basically what
we will do in this Python project idea.
Initializing game components
So let‟s start by importing the pygame library and the time library because we
will use the time.sleep() method to pause game at certain positions. Then we initialize
all the global variables that we will use in our Tic Tac Toe game.
import pygame as pg,sys
from pygame.locals import *
import time#initialize global variables
XO = 'x'
winner = None
draw = False
width = 400
height = 400
white = (255, 255, 255)
line_color = (10,10,10)
#TicTacToe 3x3 board
TTT = [[None]*3,[None]*3,[None]*3]
Here, the TTT is the main 3×3 Tic Tac Toe board and at first, it will have 9 None
values. The height and width of the canvas where we will play the game is 400×400.
Initializing Pygame window
We use the pygame to create a new window where we‟ll play our Tic Tac Toe
game. So we initialize the pygame with pg.init() method and the window display is set
with a width of 400 and a height of 500. We have reserved 100-pixel space for
displaying the status of the game.
The pg.display.set_mode() initializes the display and we reference it with the screen
variable. This screen variable will be used whenever we want to draw something on the
display.The pg.display.set_caption method is used to set a name that will appear at the
top of the display window.
#initializing pygame window

Dept. of ECE, UCET, MGU, Nalgonda 34


Python

pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.set_mode((width, height+100),0,32)
pg.display.set_caption("Tic Tac Toe")

Load and transform images


The Python project uses many images like the opening image that will display
when the game starts or resets. The X and O images that we will draw when the user
clicks on the grid. We load all the images and resize them so that they will fit easily in
our window. #loading the images
opening = pg.image.load('tic tac opening.png')
x_img = pg.image.load('x.png')
o_img = pg.image.load('o.png')
#resizing images
x_img = pg.transform.scale(x_img, (80,80))
o_img = pg.transform.scale(o_img, (80,80))
opening = pg.transform.scale(opening, (width, height+100))

Define the functions


Now we create a function that will start the game. We will also use this
function when we want to restart the game. In pygame, the blit() function is used on the
surface to draw an image on top of another image. So we draw the opening image and
after drawing, we always need to update the display with pg.display.update(). When
the opening image is drawn, we wait for 1 second using time.sleep(1) and fill the
screen with white colourNext, we draw 2 vertical and horizontal lines on the white
background to make the 3×3 grid. In the end, we call the draw_status() function
def game_opening():
screen.blit(opening,(0,0))
pg.display.update()
time.sleep(1)
screen.fill(white)
# Drawing vertical lines
pg.draw.line(screen,line_color,(width/3,0),(width/3, height),7)

Dept. of ECE, UCET, MGU, Nalgonda 35


Python

pg.draw.line(screen,line_color,(width/3*2,0),(width/3*2, height),7)
# Drawing horizontal lines
pg.draw.line(screen,line_color,(0,height/3),(width, height/3),7)
pg.draw.line(screen,line_color,(0,height/3*2),(width, height/3*2),7)
draw_status()
The draw_status() function draws a black rectangle where we update the
status of the game showing which player‟s turn is it and whether the game ends or
draws.
def draw_status():
global draw
if winner is None:
message = XO.upper() + "'s Turn"
else:
message = winner.upper() + " won!"
if draw:
message = 'Game Draw!'
font = pg.font.Font(None, 30)
text = font.render(message, 1, (255, 255, 255))
# copy the rendered message onto the board
screen.fill ((0, 0, 0), (0, 400, 500, 100))
text_rect = text.get_rect(center=(width/2, 500-50))
screen.blit(text, text_rect)
pg.display.update()
The check_win() function checks the Tic Tac Toe board to see all the marks
of „X‟ and „O‟. It calculates whether a player has won the game or not. They can either
win when the player has marked 3 consecutive marks in a row, column or diagonally.
This function is called every time when we draw a mark „X‟ or „O‟ on the board.
def check_win():
global TTT, winner,draw
# check for winning rows
for row in range (0,3):

Dept. of ECE, UCET, MGU, Nalgonda 36


Python

if ((TTT [row][0] == TTT[row][1] == TTT[row][2]) and(TTT [row][0] is not


None)):
# this row won
winner = TTT[row][0]
pg.draw.line(screen, (250,0,0), (0, (row + 1)*height/3 -height/6),\
(width, (row + 1)*height/3 - height/6 ), 4)
break

# check for winning columns


for col in range (0, 3):
if (TTT[0][col] == TTT[1][col] == TTT[2][col]) and (TTT[0][col] is not None):
# this column won
winner = TTT[0][col]
#draw winning line
pg.draw.line (screen, (250,0,0),((col + 1)* width/3 - width/6, 0),\
((col + 1)* width/3 - width/6, height), 4)
break

# check for diagonal winners


if (TTT[0][0] == TTT[1][1] == TTT[2][2]) and (TTT[0][0] is not None):
# game won diagonally left to right
winner = TTT[0][0]
pg.draw.line (screen, (250,70,70), (50, 50), (350, 350), 4)

if (TTT[0][2] == TTT[1][1] == TTT[2][0]) and (TTT[0][2] is not None):


# game won diagonally right to left
winner = TTT[0][2]
pg.draw.line (screen, (250,70,70), (350, 50), (50, 350), 4)

if(all([all(row) for row in TTT]) and winner is None ):


draw = True
draw_status()

Dept. of ECE, UCET, MGU, Nalgonda 37


Python

The drawXO(row, col) function takes the row and column where the mouse is
clicked and then it draws the „X‟ or „O‟ mark. We calculate the x and y coordinates of
the starting point from where we‟ll draw the png image of the mark.
def drawXO(row,col):
global TTT,XO
if row==1:
posx = 30
if row==2:
posx = width/3 + 30
if row==3:
posx = width/3*2 + 30

if col==1:
posy = 30
if col==2:
posy = height/3 + 30
if col==3:
posy = height/3*2 + 30
TTT[row-1][col-1] = XO
if(XO == 'x'):
screen.blit(x_img,(posy,posx))
XO= 'o'
else:
screen.blit(o_img,(posy,posx))
XO= 'x'
pg.display.update()
#print(posx,posy)
#print(TTT)
The userClick() function is triggered every time the user presses the mouse button.
When the user clicks the mouse, we first take the x and y coordinates of where
the mouse is clicked on the display window and then if that place is not occupied we
draw the „XO‟ on the canvas. We also check if the player wins or not after drawing
„XO‟ on the board.

Dept. of ECE, UCET, MGU, Nalgonda 38


Python

def userClick():
#get coordinates of mouse click
x,y = pg.mouse.get_pos()

#get column of mouse click (1-3)


if(x<width/3):
col = 1
elif (x<width/3*2):
col = 2
elif(x<width):
col = 3
else:
col = None

#get row of mouse click (1-3)


if(y<height/3):
row = 1
elif (y<height/3*2):
row = 2
elif(y<height):
row = 3
else:
row = None
#print(row,col)

if(row and col and TTT[row-1][col-1] is None):


global XO

#draw the x or o on screen


drawXO(row,col)
check_win()
The last function is the reset_game(). This will restart the game and we also reset all
the variables to the beginning of the game.

Dept. of ECE, UCET, MGU, Nalgonda 39


Python

def reset_game():
global TTT, winner,XO, draw
time.sleep(3)
XO = 'x'
draw = False
game_opening()
winner=None
TTT = [[None]*3,[None]*3,[None]*3]

Run the tic tac toe game forever


To start the game, we will call the game_opening() function. Then, we run
an infinite loop and continuously check for any event made by the user. If the user
presses mouse button, the MOUSEBUTTONDOWN event will be captured and then
we will trigger the userClick() function. Then if the user wins or the game draws, we
reset the game by calling reset_game() function. We update the display in each
iteration and we have set the frames per second to 30.

game_opening()

# run the game loop forever


while(True):
for event in pg.event.get():
if event.type == QUIT:
pg.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
# the user clicked; place an X or O
userClick()
if(winner or draw):
reset_game()

pg.display.update()
CLOCK.tick(fps)

Dept. of ECE, UCET, MGU, Nalgonda 40


Python

Hooray! The game is complete and ready to play. Save the source code with
the tictactoe.py file name and run the file.

Output:

Figure.12.1. Tic Tac Toe Gamer

Dept. of ECE, UCET, MGU, Nalgonda 41


Python

Figure.12.2. X Win The Game

Dept. of ECE, UCET, MGU, Nalgonda 42


Python

13. CONCLUSION

With this project in Python, we have successfully made the Tic Tac Toe
game. We used the popular pygame library for rendering graphics on a display
window. We learned how to capture events from the keyboard or mouse and
trigger a function when the mouse button is pressed. This way we can calculate
mouse position, draw X or O on the display and check if the player wins the
game or not.

Dept. of ECE, UCET, MGU, Nalgonda 43

You might also like