Internship Project
Internship Project
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.
• 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.
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/
# Script Begins
Statement1
Statement2
Statement3
# Script Ends
The following are the primary factors to use python in day-to-day life:
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).
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.
2. INDENTATION 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.
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.
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:
c = "John" # A string
print (a)
print (b)
print (c)
100
1000.0
John
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.
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
print(x)
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
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
>>> 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
>>> y=20
4. OPERATORS
Operators are used to perform operations on variables and values.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= 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
== Equal x == y
!= Not equal x != y
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
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'>
5.2. Float
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'>
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:
ucetmgu college
<class 'str'>
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.
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.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]]
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
1 if statements
statements.
2 if...else statements
3 nested if statements
You can use one if or else if statement inside
another if or else if statement(s).
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
7.1. Statements
In Python Iteration (Loops) statements are of three types:
While Loop
For Loop
ested For Loops
Flowchart:
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.
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.
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,
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 :
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/.
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.
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.
Figute.11.2. Histogram
Figure.11.3.3D Plot
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.
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.
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
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")
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):
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.
def userClick():
#get coordinates of mouse click
x,y = pg.mouse.get_pos()
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]
game_opening()
pg.display.update()
CLOCK.tick(fps)
Hooray! The game is complete and ready to play. Save the source code with
the tictactoe.py file name and run the file.
Output:
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.