Professional Documents
Culture Documents
Last but not least, it would not have possible for me to complete the
training without support of my family members. Constant encouragement
and support of my Father and Mother made me possible to complete the
work.
Date:
INSTITUTE OF CIVIL AND RURAL ENGINEERING, GARGOTI
DEPARTMENT OF COMPUTER ENGINEERING
CERTIFICATE
Mr.BhosaleA.R.
Principal
InstituteofCivil&RuralEngineering,Gargoti.
Sr.no. title Page no.
1 Company Profile
2 Module 1
3 Chapter 1 – Installation Python
4 Chapter 2 – Python Basic Syntax
5 Chapter 3 – Python Basic Operators
6 Chapter 4 – Python Decision Making
7 Chapter 5 – Python Loops
8 Chapter 6 – Python Numbers
9 Chapter 7 – Python Date & Time
10 Chapter 8 – Python Function
11 Chapter 9 – Python Module
12 Chapter 10 – Python File Handling
13 Chapter 11 – Python Exception
14 Chapter 12 – Python Classes & Object
15 Module 2
16 Module 3
Company Profile
Training Modules
Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties
atthe National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell, and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.─
Python Features
Easy-to-learn: Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries, and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
Chapter 1 - Installing Python─
Windows Installation
Open a Web browser and go to http://www.python.org/download/
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.
Follow the link to download zipped source code available for Unix/Linux.
make install
This installs Python at standard location /usr/local/bin and its libraries at
/usr/local/lib/pythonXX where XX is the version of Python.
Chapter 2 – Python Basic Syntax
print("Hello, Python!");
print('Hello, Students!');
Multi-Line Statements
print("Hello, \
Python!");
print('Hello, \
Students!');
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment.
“”print("Hello, Python!");
This is single multiline comment”””
print('Hello, Students!');
Python Lists
list1 = [ 121,'Present', 82.23,'Gargoti']
list2 = [123,'Absent']
print(list1 )
print(list1[0])
print(list1[1:4])
print(list1[2:])
print(list2 * 2)
print(list1 + list2)
Python Tuples
a = ( 121,'Present', 82.23,'Gargoti')
b = (123,'Absent')
print(a)
print(a[0])
print(a[1:4])
print(a[2:])
print(b * 2)
print(a + b)
Difference Between Python Lists & Tuple
a = [ 121,'Present', 82.23,'Gargoti']
b = (123,'Absent')
a[0]=525
b[0]=786
print(a)
print(b)
Python Dictionary
Python's dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs.
dict = {}
dict['one'] = "This is one named dictionary"
dict[2] = "This is two named dictionary"
print(dict['one'])
print(dict[2])
print('\n#################################\n')
a=25
b=float(a)
c=oct(a)
d=hex(a)
print("Int a =",a)
print("float b =",b)
print("Octal c =",c)
print("Hex d =",d)
Chapter 3 – Python Basic Operators
a=2
b=3
c = a**b
print ("After ** operation c is ", c)
a = 10
b=5
c = a//b
print("After// operation c is ", c)
a = 21
b = 10
c = a != b
print ("After operation c is ", c)
a = 21
c=1
c %= a
print ("After operation c is ", c)
#&,|,^,~,<<,>>
a=0
b=1
c = b<<2
print ("After operation c is ", c)
Python Membership Operators
#in , not in
a = 10
list = [1, 2, 3, 4, 5 ];
if ( a not in list ):
print("true")
else:
print("false")
If Statement
a = 100
if a:
print("Got a true expression value")
print(a)
b=0
if b:
print("Got a true expression value")
print(b)
print("Good bye!")
If else Statement
a = 100
b=50
if (a<b):
print("true expression")
print(a)
else:
print("false expression")
print(b)
while loop
#print all even numbers from 1 to 10
a=1
while (a <= 10):
print(a)
a=a+2
print("work is done")
for loop
for i in digits:
print(i)
else:
print("No items left.")
a=(23,5,38,45,2)
print(min(a))
print(max(a))
print(round(10.6))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
Trigonometric Functions
import math
# Output: 3.141592653589793
print(math.pi)
# Output: 22026.465794806718
print(math.exp(10))
# Output: 720
print(math.factorial(5))
time.time() function
The function time.time() returns the current system time in
ticks since 12:00am, January1, 1970(epoch).
import time;
localtime = time.localtime(time.time())
print("Local current time :", localtime)
ime.sleep(secs)
import time
print("Start : %s" % time.ctime())
time.sleep( 5 )
print("End : %s" % time.ctime())
def myfun(name):
print("Hello, " + name + ". Good morning!")
#calling function
myfun('vinayak')
def numreturner(num):
if num >= 0:
return num
else:
return -num
print(numreturner(2))
print(numreturner(-4))
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)
Default Arguments
total=0
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return
# Now you can call sum function
sum( 10, 20 );
print("Outside the function global total : ", total)
def mymodule():
print('Hi, this is mymodule speaking')
way1:-
import Wshop
Wshop.mymodule()
Way2:-
from DShop2 import mymodule
mymodule()
import math
data = dir(math)
print(data)
import derivedfile
data=dir(derivedfile)
print(data)
#str=obj.readlines()
#print(str)
str = obj.read();
print("Read String is : ", str)
obj.close()
_______________________________________________
__
import os
#os.remove('vsk.txt')
os.rename('foo.txt','d.txt')
________________________________________________
Directories in Python
import os
#os.mkdir("test")
#os.rmdir('test')
#os.chdir('test')
#print(os.getcwd())
Chapter 11 – Python Exception
What is Exception?
try:
obj = open("dx.txt", "r")
obj.write("\nThis is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
obj.close()
try:
a=5
b=0
c=a/b
print(c)
except ArithmeticError: #Exception IOError ArithmeticError
print("Error: can\'t divide by zero")
else:
obj.close()
Argument of an Exception
def num_display(arg):
try:
return int(arg)
except ValueError:
print('The argument does not contain numbers',arg)
# Call above function here.
print(num_display('xyz'))
Chapter 12 – Python classes & Object
Creating Classes
class student:
scount = 0
def __init__(self, ern, name ):
self.ern = ern
self.name = name
student.scount += 1
def showstudent(self):
print(" EnrollNu :", self.ern," Name :", self.name)
s1 = student(3712,"Motu")
s2 = student(9839,"Patlu")
s1.showstudent()
s2.showstudent()
print("Total Student",student.scount)
Destroying Objects (Garbage Collection)
class Point:
def __init( self, x=0, y=0):
self.x = x;
self.y = y;
def __del__(self):
class_name = self.__class__.__name__;
print(class_name, "destroyed");
pt1 = Point();
pt2 = pt1;
pt3 = pt1;
print(id(pt1), id(pt2), id(pt3)); # prints the ids of the obejcts
del pt1;
del pt2;
del pt3;
Class Inheritance
def getData(self):
print("Parent attribute :", parent.pAge)
def cMethod(self):
print("Calling child method")
Tkinter:
wxPython:
JPython:
Tkinter
Button
import tkinter
pwnd = tkinter.Tk()
B = tkinter.Button(pwnd, text ="Hello")
B.pack()
pwnd.mainloop()
Canvas
import tkinter
pwnd = tkinter.Tk()
C = tkinter.Canvas(pwnd, bg="blue", height=250, width=300)
coord = 10, 50, 240, 150
arc = C.create_arc(coord, start=0, extent=180, fill="red")
C.pack()
pwnd.mainloop()
Entry
import tkinter
pwnd = tkinter.Tk()
L1 = tkinter.Label(pwnd, text="User Name")
L1.pack()
E1 = tkinter.Entry(pwnd, bd =5)
E1.pack()
pwnd.mainloop()
Listbox
import tkinter
pwnd = tkinter.Tk()
Lb1 = tkinter.Listbox(pwnd)
Lb1.insert(1, "IND")
Lb1.insert(2, "CHN")
Lb1.insert(3, "PAK")
Lb1.insert(4, "USA")
Lb1.insert(5, "AUS")
Lb1.pack()
pwnd.mainloop()
Module 3
Create the Screen:
import pygame
pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake game by Data Corner Tech)
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.quit()
quit()
pygame.init()
dis = pygame.display.set_mode((400, 300))
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.draw.rect(dis, blue, [200, 150, 10, 10])
pygame.display.update()
pygame.quit()
quit()
import pygame
pygame.init()
x1 = 300
y1 = 300
x1_change = 0
y1_change = 0
clock = pygame.time.Clock()
x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, black, [x1, y1, 10, 10])
pygame.display.update()
clock.tick(30)
pygame.quit()
quit()
import pygame
import time
pygame.init()
dis_width = 600
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake Game by Data Corner Tech')
game_over = False
x1 = dis_width / 2
y1 = dis_height / 2
snake_block = 10
x1_change = 0
y1_change = 0
clock = pygame.time.Clock()
snake_speed = 10
x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
pygame.display.update()
clock.tick(snake_speed)
pygame.quit()
quit()
Adding the Food:
import pygame
import time
import random
pygame.init()
dis_width = 600
dis_height = 600
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 30
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, blue, [foodx, foody, snake_block,
snake_block])
pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
pygame.display.update()
pygame.quit()
quit()
gameLoop()
import pygame
import time
import random
pygame.init()
dis_width = 600
dis_height = 400
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
pygame.display.update()
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
pygame.display.update()
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
pygame.init()
dis_width = 600
dis_height = 400
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()