SlideShare a Scribd company logo
Aashish Jain
Consultant, KPIT Technologies Ltd.
Who all can learn?
Beginners who have never programmed
Programmers coming from another language
Python-An Introduction
General-purpose interpreted, interactive, object-oriented, high-level
programming language.
 Started in 1989 and published in 1991 by Guido Van Rossum.
 First version was released as Python 1.0 in 1994
ABC programming language is said to be the predecessor of Python
Influenced by ABC language and Modula-3
Python-Features
Easy- to- learn
Easy- to- read
Easy- to-
maintain
Portable
Interactive
mode
A broad
standard
library
Extendable
Databases
GUI
programming
Scalable
Python-Versions 1.0-
1994 1.5-
1997
1.6-
2000
2.0-
2000
2.1-
2001
2.2-
2001
2.3-
2003
2.4-
2004
2.5-
2006
2.6-
2008
2.7-
2010
3.0-
2008
3.1-
2009
3.2-
2011
3.3-
2012
3.4-
2014
3.5-
2015
3.6-
2016
3.6.4-
2017
Python
Versions
Python-Application Areas
 Web Applications Django, Pyramid, Flask frameworks
 Desktop GUI applications wxWidgets, Kivy etc. toolkits.
 Software Development
 Scientific and Numeric SciPy, Panda etc.
 Business Applications Tryton ERP (application)
 Console Based applications
 Audio or Video Based applications Timplayer, cPlay etc. (applications)
 3D CAD applications  Fandango
 Enterprise applications OpenErp, Picalo etc.
 Application for Images Vpython, Gogh etc.
Google,
Youtube,
Dropbox,
Quora, Spotify,
Instagram etc.
Python-Resources
https://www.python.org/
 Documentation, tutorials, beginners guide …
Other Resources:
 Learning Python by Mark Lutz
 Python Essential Reference by David Beazley
 Python Cookbook, ed. by Martelli, Ravenscroft and Ascher
 http://wiki.python.org/moin/PythonBooks
Python v/s Jython v/s IronPython
Python or CPython is written in C/C++. It is most commonly used
python by developers.
Jython is written in Java and runs on JVM. So, a developer can write a
plugin for Java application using it.
IronPython or IPython is written in .NET and runs on CLR (Common
Language Runtime). So, a developer can use .NET libraries.
Any Queries??
Python-Installation
 There are 2 different versions of Python:
 Python 2.7.14
 Python 3.6.4
 Click here: Download Python
Double click on the downloaded .exe file and install.
Python-IDEs
PyDev with Eclipse
Komodo
Emacs
Vim
TextMate
Gedit
Idle
PIDA (Linux)(VIM Based)
NotePad++ (Windows)
BlueFish (Linux)
Python-Setting Path
You can set the path for python in your system using below steps:
1. Right Click on My Computer icon and navigate to following path:
Properties  Advanced System Settings  Environment Variables
2. Under System Variables, search for variable Path and append C:Python27 to
existing value.
Any Queries??
Python-Variables
A name which is used to refer memory location.
Also known as identifier and used to hold value.
No need to specify type for variable.
Variable name can be a group of letters and digits, but it must start either
with a letter or an underscore.
Recommended to use lower case letters.
Python-Variables
 Multiple Assignments:
 Python allows developers to assign a value to multiple variables in a single
statement.
 Assigning Single Value to multiple variables:
 x=y=z=100
 Assigning Multiple Values to multiple variables:
 a, b, c=20, 30, 40
Python-Variables
 Multiple Assignments:
 Python allows developers to assign a value to multiple variables in a single
statement.
 Assigning Single Value to multiple variables:
 x=y=z=100
 Assigning Multiple Values to multiple variables:
 a, b, c=20, 30, 40
Python-Keywords
Special reserved words which convey a special meaning to the
compiler/ interpreter.
Python-Identifiers
 Names given to the fundamental building blocks in a program.
 Can be variable, class, list, object, dictionary, function etc.
 Rules:
 Sequence of letters and numbers.
 No special character can be used as an identifier except underscore (_)
 Keyword must not be used as identifier.
 Python is case sensitive, So using case is significant.
 Identifier must start with a letter or underscore (_).
Python-Literals
 Data given in a variable or constant.
 String literals: Can be formed by enclosing a text in either single or double
quotes.
 “Ram”, ‘232324’
 Single Line String: >>> text1= “Hello”
 Multi Line String: >>> text1= ‘Hello
User’
 Using triple quotation marks: >>> str= ‘’’ Welcome
to
India’’’
Python-Literals
 Numeric Literals:
 int (signed integers): 100
 long (long integers): 3456570L
 float (floating point): -25.7
 Complex (complex numbers): 3.14j
 Boolean Literals:
 True or False
 Special Literals:
 Python contains one special literal: None
 Used to specify that field which has not been created.
 Also used for end of lists.
Any Queries??
Python-Operators
 Symbols that are used to perform operations on operands.
 Types of Operators:
 Arithmetic Operators
 Comparison Operators
 Assignment Operators
 Logical Operators
 Membership Operators
 Identity Operators
 Bitwise Operators
Python-Operators
 Arithmetic Operators
Operators Description
// Performs floor division (gives integer value)
+ Performs addition
- Performs subtraction
* Performs multiplication
/ Performs division
% Performs Modulus (return remainder after division)
** Performs power
Python-Operators
 Comparison Operators
Operators Description
< Performs less than comparison
> Performs greater than comparison
<= Performs less than equal to comparison
>= Performs greater than equal to comparison
== Performs equal to comparison
!= Performs not equal to comparison
< > Performs not equal to comparison
Python-Operators
 Assignment Operators
Operators Description
= Simple assignment (right side expression to left side variable)
/= Performs division and then assignment
+= Performs addition and then assignment
-= Performs subtraction and then assignment
*= Performs multiplication and then assignment
%= Performs modulus and then assignment
**= Performs power and then assignment
//= Performs floor division and then assignment
Python-Operators
 Logical Operators
Operators Description
and Performs Logical AND (both conditions must be true)
or Performs Logical OR (one of the conditions must be true)
not Performs Logical NOT (compliment the condition i.e. reverse)
Python-Operators
 Identity Operators
Operators Description
is Returns true if identity of two variables are same else false.
is not Returns true if identity of two variables are not same else false.
Python-Operators
 Bitwise Operators
Operators Description
& Performs bitwise and operation
| Performs bitwise or operation
^ Performs bitwise xor operation
~ Performs bitwise complement operation
<< Performs bitwise left shift operation
>> Performs bitwise right shift operation
Python-Comments
 Single Line Comments
 To put single line comments in code, use # symbol
 Multi Line Comments
 To put multi line comments in code enclose the comment statements
with triple quotes. ‘’’ Your comment Statements ‘’’
Python-Control Statements
 Control statements are used to control the structure/flow of your
application program.
 An if statement decides whether to execute another statement or not.
 A loop statement decides how many times to execute another statement.
Python-Control Statements
 IF- Statement:
 Syntax:
if (condition):
// lines of code
 IF-ELSE Statement:
 Syntax:
if (condition):
// lines of code
else:
// lines of code
Python-Control Statements
 IF-ELIF-ELSE Statement:
 Syntax:
if (condition):
// lines of code
elif (condition):
// lines of code
else:
// lines of code
Any Queries??
Python-Control Statements
 FOR Loop Statement:
 Syntax:
for <variable> in <sequence>:
// statements
 Syntax:
for <variable> in <sequence>:
// statements
else:
//statements
Python-Control Statements
 WHILE Loop Statement:
 Syntax:
while <expression>:
// statements
 Syntax:
while <expression>:
// statements
else:
//statements
Python-Control Statements
 BREAK Statement:
 A jump statement use to transfer execution control.
 Breaks the current execution
 In case of inner loop, terminates inner loop immediately.
 Example:
for letter in 'Python2':
if letter == 'o':
break
print (letter)
Python-Control Statements
 CONTINUE Statement:
 A jump statement use to skip execution of current iteration.
 After skipping, loop continues with next iteration.
 Example:
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print a
print "End of Loop"
Python-Control Statements
 PASS Statement:
 Keyword use to execute nothing.
 When developer don’t want to execute code, this can be used to execute
empty.
 Example:
for i in [1,2,3,4,5]:
if i==3:
pass
print "Pass when value is",i
print i
Any Queries??
Python-Numbers
 Store numeric values.
 Immutable in nature.
 Created when you assign a value to them.
Python-Numbers
 Type Conversion:
Function Description
int(x) Converts x to plain integer
long(x) Converts x to a long integer
float(x) Converts x to a floating-point number
complex(x)
Converts x to a complex number with real part x and imaginary
part zero.
complex(x, y)
Converts x to a complex number with real part x and imaginary
part y.
Python-Numbers
 Mathematical Functions:
Function Description
abs(x) The absolute value of x (positive)
ceil(x)* The ceiling of x: smallest integer not less than x.
cmp(x, y) -1 if x<y; 0 if x==y; 1 if x>y
floor(x) * The floor of x: largest integer not greater than x.
*import math
max(x1, x2, x3,…) The largest of its arguments.
Python-Numbers
 Mathematical Functions:
Function Description
min(x1, x2, x3,…) The smallest of its arguments.
pow(x, y) * The value of x**y.
round(x [, n]) Returns x rounded to n digits from the decimal point.
*import math
sqrt(x) * Returns square root of x for x>0
Python-Strings
 Immutable character sequence.
 Can be accessed from both the directions (forward and backward).
Python-Strings
 Tricky Operations:
 Use ‘+’ to concatenate strings and ‘*’ to replicate a string.
 ‘Ram’+’ Kumar’ ‘Ram Kumar’
 ‘Ram’*5‘RamRamRamRamRam’
 Use ‘in’ to check whether specified string is substring or not.
 str1=‘This is an in example’
 str2=‘in’
 str2 in str1 True
Python-Strings
 Tricky Operations:
 Use ‘:’ to slice a string.
 str1=‘This is an example’
 str1[2:3]‘i’ {startIndex (inclusive): endIndex (exclusive)}
 str[::-1] {reverse a string}
 Use ‘r’ to not interpret characters as special characters prefaced by ‘’.
 print ‘D:newPrognewInstruction’
 print r‘D:newPrognewInstruction’
Python-Strings
 Tricky Operations:
 Two strings enclosed with quotes will automatically be concatenated.
 str1=‘This’ ‘ is’
 print str1 This is
 Enclose string with ( ) to break long strings.
 str1=(‘This is’
‘ an example of’
‘ concatenating strings’)
 print str1 This is an example of concatenating strings
Python-Strings
 Functions:
Function Description
captialize() Capitalize the first character of the string
--count(sub string [, begin] [, end]) Counts no. of times sub string occurs within given start and
end index.
find(sub-string [, begin] [, end]) Returns index value of the string where sub-string found
between begin and end index.
index(sub-string [, begin] [, end]) Works same as find() but throws an exception if sub-string
not found.
isalnum() Returns True if string is alphanumeric and have at least 1
character.
isalpha() Returns True when all the characters are alphabets and
string have at least 1 character.
Python-Strings
 Functions:
Function Description
isdigit() Returns True when all the characters are digits and string
have at least 1 character.
isupper() Returns True if all the characters of a string are in upper
case.
islower() Returns True if all the characters of a string are in lower
case.
isspace() Returns True if all the characters of a string are white space.
len(string) Returns length of the string.
lower() Converts all the characters of a string to lower case.
upper() Converts all the characters of a string to upper case.
swapcase() Inverts case of all characters in a string.
Any Queries??
Python-Print Formatting
 Print Statements-Strings:
 print ‘This string will be printed’
 When using variables:
 str=‘Print this string’
 print ‘I have assigned the string in variable: %s’ %(str)
 Print Statement-Floating Point Numbers:
 print ‘Floating point Number: %f’ %(12.345)
 print ‘Floating point Number: %1.2f’ %(12.345)
 print ‘Floating point Number: %20.2f’ %(12.345)
Python-Print Formatting
 Print Statements-Conversion of Objects:
 print ‘Converting to string: %s’ %(12345)
 print ‘Converting to string : %s’ %(12.345)
 print ‘Converting to string : %r’ %(12.345)
 Print Statements- Multiple Variables:
 print ‘First: %s Second: %1.2f Third: %d’ %(‘String’, 12.34, 12)
} internally call str()
} internally call repr()
Python-Print Formatting
 Print Statements-Using format():
 print ‘First: {x} Second: {x}’.format(x=12)
 print ‘First: {x} Second: {y}’.format(x=12, y=‘String’)
 x, y=12, 10
 print ‘First: {x} Second: {y}’.format(x=x, y=y)
Python-Lists
 A mutable data structure which is used to store various types of data.
 Works as container which holds other objects in a given order.
 Can be composed by storing a sequence of different type of values separated by
commas.
 Enclosed between square ([ ]) brackets and elements are stored on the index basis
with starting index 0.
 Example:
 list1=[1,2,3,4]
 list2=[‘1’,’2’,’3’,’4’]
 list3=[‘1’,2.0,3,4]
Python-Lists
 Operations on Lists:
 Accessing Elements
 Elements can be accessed via indexing. e.g. list1[0]
 List can be sliced as well to access elements. e.g. list1[2:4]
Python-Lists
 Operations on Lists:
 Adding Lists
 List1=[2,3,4]
 List2=[5,6,7]
 List3=List1+List2
 List4=List1+[30]
 Replicating Lists
 List1=[2,3,4]
 List2=List1*2
Python-Lists
 Operations on Lists:
 Slicing Lists
 List1=[2,3,4]
 List2=List1[:1]
 print List1[::-1]
Python-Lists
 List Methods:
Method Name Description
append(object) Add an element at the end of the existing list.
pop([index]) If specified, remove the element at the given position in the list
otherwise remove the last element and returns it.
reverse() Reverse the elements of the list, in place.
sort() Sort the elements of the list, in place.
min(list) Returns the minimum value from the list given.
Python-Lists
 List Methods:
Method Name Description
max(list) Returns the maximum value from the list given.
len(list) Returns the number of elements in the list.
index(object) Returns the index value of the object.
insert(index, object) Insert an object at given position
remove(object) Remove the first object from the list, if not found throws an error.
Python-Lists Comprehension
 List Comprehension allows to build out list using a different notation.
 It can be thought as one line for loop built inside of brackets.
 Examples:
 List1=[x for x in range(1,10)]
 List2=[x**2 for x in range(1,10)]
 List3=[x for x in range(11) if x%2==0]
 List4=[x**2 for x in [x for x in range(20) if x%2==1]]
 List5=[x for x in ‘Hello World’]
Any Queries??
Python-Dictionaries
 An unordered set of key and value pair.
 A container that contains data, enclosed within {}.
 Key-value pair is known as item.
 Key must be unique.
 Key and value is separated by ‘:’ and items in dictionary are separated by
‘,’.
 Examples:
 my_dict={‘001’:’Alex’, ‘002’:’Akira’, ‘003’:’Ayesha’}
Python-Dictionaries
 It is mutable i.e. values can be updated.
 Values can be accessed via key only.
 Example:
 my_dict[‘001’]
 Nested Dictionaries can also be defined:
 my_dict={‘key’:{‘subkey’:{‘subsubkey’:’value’}}}
Python-Dictionaries
 Dictionaries Methods:
Method Name Description
len(dict ) Returns the number of elements in the dictionary.
keys() Returns all the keys of a dictionary.
values() Returns all the values associated with keys in a dictionary.
items() Returns all the items (key-value pair) in a dictionary.
update(dict) Used to add items of dict to the dictionary.
Python-Dictionaries
 Dictionaries Methods:
Method Name Description
clear() Used to remove all items of a dictionary.
copy() Shallow copies data of a dictionary
has_key(key) Returns True if key is found in a dictionary otherwise False.
get(key) Returns the value associated with key. If key is not present, returns None.
Python-Tuples
 A sequence of immutable objects.
 Can be used to collect different types of object.
 Similar to list, except tuples has immutable objects whereas list has
mutable objects and list uses [] to enclose objects whereas tuple uses () to
enclose objects.
 Example:
 tuple1=(1,2,3)
Python-Tuples
 Operations on Tuples:
 Accessing Elements
 Elements can be accessed via indexing. e.g. tuple1[0]
 Tuple can be sliced as well to access elements. e.g. tuple1[2:4]
Python-Tuples
 Operations on Tuples:
 Adding Tuples
 Tuple1=(2,3,4)
 Tuple2=(5,6,7)
 Tuple3=Tuple1+Tuple2
 Tuple4=Tuple1+(30,50)
 Replicating Tuples
 Tuple1=(2,3,4)
 Tuple2=Tuple1*2
Python-Tuples
 Advantages of Tuples:
 Tuples are faster than lists.
 Makes data safe as tuples are immutable.
 Used for string formatting.
Any Queries??
Python-Files
 Python uses file object to interact with external files on system.
 It can be any type of file e.g. audio, video, text, etc.
 To interact with these types of files, need to install some libraries or
modules which are easily available.
 For instance, to read video files, need to install opencv-python package or
some other available packages for video files.
Python-Files
 Installation of modules/ libraries/ packages:
 To install any package for python, open command prompt and type:
python pip –m install packagename
e.g. python pip –m install opencv-python
 To install a specific version of package:
python pip –m install “packagename>=version”
e.g. python pip –m install “opencv-python>=3.4.0.12”
 To upgrade existing package:
python pip –m install --upgrade packagename
e.g. python pip –m install –upgrade opencv-python
Python-Files
 Operations on File:
 Opening a File:
 f=open(‘filename’, ’mode’)
 filename name of a file to be opened.
 mode specifies the mode in which a file can be opened. E.g. ‘r’ to
read a file.
 e.g. f=open(‘C:myFile.txt’, ’r’)
Python-Files
 Different modes to open a File (Text):
Mode Description
r Opens a file in reading mode. Pointer is at the beginning of the file.
r+ Opens a file for reading and writing. Pointer is at the beginning of the file.
w Opens a file in writing mode. If already exists, then overwrite the file else
creates a new file.
w+ Opens a file for reading and writing. If already exists, then overwrite the file
else creates a new file.
a Opens a file in appending mode. If already exists, then append the data at the
end of the file else creates a new file.
a+ Opens a file in reading and appending mode. If already exists, then append the
data at the end of the file else creates a new file.
Python-Files
 Different modes to open a File (Binary):
Mode Description
rb Opens a file in reading mode for binary format. Pointer is at the beginning of
the file.
rb+ Opens a file for reading and writing for binary format. Pointer is at the
beginning of the file.
wb Opens a file in writing mode for binary format. If already exists, then overwrite
the file else creates a new file.
wb+ Opens a file for reading and writing for binary format. If already exists, then
overwrite the file else creates a new file.
ab Opens a file in appending mode for binary format. If already exists, then
append the data at the end of the file else creates a new file.
ab+ Opens a file for reading and appending mode for binary format. If already
exists, then append the data at the end of the file else creates a new file.
Python-Files
 Use of with Keyword:
 Sample code:
with open('workfile', 'r') as f:
read_data = f.read()
 It’s a good practice to use this approach.
 File is properly closed after its suite finishes, even if an exception is
raised on the way.
Python-Files
 Methods for File object:
Method Description
read([size]) To read a file’s content. If size is omitted or negative then entire content of
the file will be returned else read the specified quantity of data.
readline() Reads a single line from the file.
readlines() Reads all the lines from the file and returned as list of lines.
write(text) Writes content to the file.
tell() Returns an integer giving the file object’s current position in the file.
close() Closes an opened file.
Python-Files
 Functions for File object by os module:
,
Function Description
rename(old_file_name new_file_name) Use to rename an existing file.
)remove(file_name Use to remove an existing file.
mkdir(directory_name) Use to create a directory with the name specified.
chdir(directory_name) Use to change the current working directory.
getcwd() Use to get the current working directory.
rmdir(directory_name) Use to delete a directory with the name specified.
Python-Sets
 A set in python holds a sequence of values.
 It is sequenced but not indexed.
 A set contains only unique values.
 A set is mutable, but may not contain mutable items like a list, set or
dictionary.
 Function set() can be used to create a set from an iterable like list.
Python-Sets
 Examples:
 d=set() # Creates an empty set
 d={1,2,3}
 Since sets do not support indexing, slicing operation can’t be performed on
sets.
 Since sets do not contain duplicate items, replication operation also can’t be
performed. (via *)
Python-Sets
 Methods:
Method Description
add(object) Adds a hashable object to the set.
update(object) Adds iterable objects to the set.
discard(object) Deletes an object from the set. If object isn’t in the set, does nothing.
remove(object) Deletes an object from the set. If object isn’t in the set, throws an error.
pop() Removes first object from the set.
Python-Sets
 Methods:
Method Description
clear() Removes all the objects from the set i.e. empties the set.
union(object) Performs union operations on the set with specified iterable objects in
the arguments.
intersection(object) Performs intersection operation on the set with specified iterable
objects in the arguments.
difference(object) Performs difference operation on the set with specified iterable objects
in the arguments
Python-Sets
 Methods:
Method Description
issubset(object) Checks whether the set is a sub set of given object in the argument.
issuperset(object) Checks whether the set is a super set of given object in the argument.
isdisjoint(object) Checks whether the set is disjoint with the given object in argument.
Python-Booleans
 A Boolean value may either be True or be False.
 A Boolean can be declared like other objects e.g. x=True.
 Function bool() can be used to convert other types in to Boolean.
 Any empty construct has a Boolean value of False and a non-empty one
has True.
Any Queries??
Python-Methods & Functions
 Methods are essentially functions built into objects.
 Methods perform specific actions on the objects and can also take
arguments.
 Example:
 object.method(arg1, arg2,…,etc)
 Any information about the methods can be retrieved through
help(method_name) in python.
Python-Methods & Functions
 Functions are the program section that are written once and let the
programmer to not repeat the same lines of code, hence make code
reusable.
 Functions work on data and produces some output.
 There are two types of functions:
 Built-in functions: Predefined and organized into a library.
 User-defined functions: Created by developer to meet the desired
requirements.
 Follow the link for built-in functions in python: Built-in Functions
Python-Methods & Functions
 A developer can define his/her own functions using below format:
 Keyword def is used to declare a function.
 def is followed by function name with parenthesis ending with a colon.
 If required arguments can be provided within the parenthesis.
 Example:
def function_name(parameter1, parameter2):
// line of codes
//sample code
def name_of_function():
pass
Python-Methods & Functions
 Example:
def iseven(num):
if num%2==0:
print “Number is even”
else:
print “Number is not even”
 The above function is defined to check whether the provided number is
even or not.
 The above defined function can be called as follows:
iseven(10)
Python-Methods & Functions
 Example using return statement:
def iseven(num):
return num%2==0
iseven(15)
 Add documentation for function:
def iseven(num):
‘’’
This function will check whether the input number is even or not
‘’’
return num%2==0
Python-Methods & Functions
 Example using default arguments:
def printMessage(id, name, branch=‘CSE’):
print “id=%sn name=%sn branch=%s” %(id,name,branch)
printMessage(id=‘101’, name=‘Andrew’)
printMessage(id=‘102’, name=‘Ajeet’,branch=‘IT’)
printMessage(name=‘Ajeet’, id=‘102’)
printMessage(id=‘102’, name=‘Ajeet’,branch=‘IT’)
Python-Methods & Functions
 Local and Global Variables:
 Variables defined inside a function is local variables and variables defined
outside the function is called global variables.
 Example:
LOCAL VARIABLES
def printValue():
x=10
print x
printValue()
print x
GLOBAL VARIABLES
y=5
def printValue():
x=10
print x
print y
printValue()
Any Queries??
Python-Lambda Expressions
 Allows a programmer to create anonymous functions.
 Allows to quickly make ad-hoc functions without needing to properly
define a function using def.
 It’s an expression, not a block of statements.
 The result of this is an expression without explicitly defining a return
statement.
 Designed for coding simple functions to limit program nesting.
Python-Lambda Expressions
 Converting a normal function to lambda expression:
Example:
def square(x):
return x*x
def square(x): return x*x
 Syntax for lambda:
lambda input: result
lambda x: x*x
square=lambda x:x*x
sqaure(10)
Python-Lambda Expressions
 Converting lambda expression to a normal function:
Example:
odd=lambda x: x%2==1
def odd(x):
return x%2==1
Python-Lambda Expressions
 Lambda expression with multiple arguments:
Example:
add= lambda x,y: x+y
add(5,4)
area= lambda length, width: length*width
area(40.5,30)
Any Queries??
Simple Project
Tic-Tac-Toe
Project: Tic-Tac-Toe
 Problem Statement:
Create an application in Python for 2-player Tic-Tac-Toe game.
 Step-by-step solution for problem statement:
 Variables for the application
 Board: Tic-Tac-Toe board a list with size 10
 Player Markers: ‘x’ and ‘o’ string types
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
1. Create and Display Tic-Tac-Toe board
2. Choose the player’s marker and player to start the game
3. Ask the player to place his marker
4. Check if board is empty or not
5. If empty, place his marker
6. Ask another player to place his marker
7. Repeat 2-6 until the board is full or someone doesn’t declare as winner
8. If no winner found, then it’s a tie and ask to restart the game.
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
1. Create and Display Tic-Tac-Toe board
def display_board(board):
print(' ___________ ')
print('| | | |')
print('| '+board[1]+' | '+board[2]+' |
'+board[3]+' |')
print('|___|___|___|')
print('| | | |')
print('| '+board[4]+' | '+board[5]+' |
'+board[6]+' |')
print('|___|___|___|')
print('| | | |')
print('| '+board[7]+' | '+board[8]+' |
'+board[9]+' |')
print('|___|___|___|')
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
2. Select player’s marker and choose the player to start the game
def player_input():
player_marker=' '
while not (player_marker=='X' or player_marker=='O'):
player_marker=raw_input("Please select either X or O").upper()
if player_marker=='X':
return ('X', 'O')
else:
return ('O', 'X')
def choose_first_player():
if random.randint(0,1)==0:
return 'Player 1'
else:
return 'Player 2'
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
3. Ask to place the marker, check the empty place and place the marker
def player_choice(board):
choice=' '
numberList='1 2 3 4 5 6 7 8 9'
while choice not in numberList.split() or not check_place(board, int(choice)):
choice=raw_input("Please enter a number between 1-9")
return int(choice)
def check_place(board, position):
return board[position]==' '
def place_marker(board, marker, position):
board[position]=marker
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
4. Check whether the board is full or not
def full_board_space_check(board):
for i in range(1,10):
if check_place(board, i):
return False
return True
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
5. Start the game, check for winner or tie
def play_game():
print('Welcome to Tic-Tac-Toe')
while True:
game_board=[' ']*10
player1_mark,player2_mark=player_input()
turn=choose_first_player()
print(turn+' will start this game')
game_on=True
while game_on:
if turn=='Player 1':
display_board(game_board)
position=player_choice(game_board)
place_marker(game_board, player1_mark, position)
if check_winner(game_board, player1_mark):
display_board(game_board)
print('Congratulation...!!!! Player1 has won')
game_on=False
else:
if full_board_space_check(game_board):
display_board(game_board)
print('Try next time.. Its a Tie.. ')
break
else:
turn='Player 2'
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
5. Start the game, check for winner or tie
else:
display_board(game_board)
position=player_choice(game_board)
place_marker(game_board, player2_mark, position)
if check_winner(game_board, player2_mark):
display_board(game_board)
print('Congratulation...!!!! Player2 has won')
game_on=False
else:
if full_board_space_check(game_board):
display_board(game_board)
print('Try next time.. Its a Tie.. ')
break
else:
turn='Player 1'
if not restart_play():
print('We will Miss you..')
break
def check_winner(board, marker):
return board[1]==board[2]==board[3]==marker or
board[4]==board[5]==board[6]==marker or
board[7]==board[8]==board[9]==marker or
board[1]==board[4]==board[7]==marker or
board[2]==board[5]==board[8]==marker or
board[3]==board[6]==board[9]==marker or
board[1]==board[5]==board[9]==marker or
board[3]==board[5]==board[7]==marker
Project: Tic-Tac-Toe
 Step-by-step solution for problem statement:
6. Ask to restart the game
 Let’s play the game: play_game()
def restart_play():
return raw_input("Do you want to play again (Yes/No)").lower().startswith('y')
Any Queries??

More Related Content

PDF
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
PPTX
Python
PPTX
Python presentation by Monu Sharma
PDF
Python Programming
PDF
Introduction To Python | Edureka
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PPTX
Python Tutorial Part 1
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python
Python presentation by Monu Sharma
Python Programming
Introduction To Python | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial Part 1

What's hot (20)

PPT
Python ppt
PPTX
Introduction to python
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
PDF
Python Basics | Python Tutorial | Edureka
PPT
Introduction to Python
PPTX
Python programming
PPTX
Beginning Python Programming
PPTX
Basic Python Programming: Part 01 and Part 02
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PPTX
Introduction to the basics of Python programming (part 1)
PDF
Introduction to Python
PPTX
Introduction to python
PDF
Introduction to python programming
PDF
Introduction to python
PPT
Introduction to Python
PDF
Introduction to python
PPTX
Fundamentals of Python Programming
PPTX
Introduction to Python Programming Basics
Python ppt
Introduction to python
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Basics | Python Tutorial | Edureka
Introduction to Python
Python programming
Beginning Python Programming
Basic Python Programming: Part 01 and Part 02
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Introduction to the basics of Python programming (part 1)
Introduction to Python
Introduction to python
Introduction to python programming
Introduction to python
Introduction to Python
Introduction to python
Fundamentals of Python Programming
Introduction to Python Programming Basics
Ad

Similar to Python (20)

PPTX
Introduction to python programming ( part-1)
PPTX
Chapter1 python introduction syntax general
PPTX
Unit -1 CAP.pptx
PPT
Python tutorialfeb152012
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
PDF
Introduction of Python
PDF
Tutorial on-python-programming
PPTX
Python Demo.pptx
PPTX
Python Demo.pptx
PPTX
Introduction To Python.pptx
PPTX
Introduction to Python for Data Science and Machine Learning
PPT
Python programming
PPTX
lecture 2.pptx
PDF
Introduction To Programming with Python
PPTX
Introduction to Python Programming .pptx
PPTX
presentation_python_7_1569170870_375360.pptx
PDF
Intro-to-Python-Part-1-first-part-edition.pdf
PDF
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PPTX
python introduction initial lecture unit1.pptx
Introduction to python programming ( part-1)
Chapter1 python introduction syntax general
Unit -1 CAP.pptx
Python tutorialfeb152012
Sessisgytcfgggggggggggggggggggggggggggggggg
Introduction of Python
Tutorial on-python-programming
Python Demo.pptx
Python Demo.pptx
Introduction To Python.pptx
Introduction to Python for Data Science and Machine Learning
Python programming
lecture 2.pptx
Introduction To Programming with Python
Introduction to Python Programming .pptx
presentation_python_7_1569170870_375360.pptx
Intro-to-Python-Part-1-first-part-edition.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
python introduction initial lecture unit1.pptx
Ad

More from Aashish Jain (6)

PPTX
PPTX
Let's start with Java- Basic Concepts
PPTX
ASP, ASP.NET, JSP, COM/DCOM
PPTX
JavaScript, VBScript, AJAX, CGI
PPTX
HTML, CSS and XML
PPTX
Introduction to Web Technology
Let's start with Java- Basic Concepts
ASP, ASP.NET, JSP, COM/DCOM
JavaScript, VBScript, AJAX, CGI
HTML, CSS and XML
Introduction to Web Technology

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
A Presentation on Artificial Intelligence
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Approach and Philosophy of On baking technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
cuic standard and advanced reporting.pdf
PPTX
Tartificialntelligence_presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Spectroscopy.pptx food analysis technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A Presentation on Artificial Intelligence
20250228 LYD VKU AI Blended-Learning.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Dropbox Q2 2025 Financial Results & Investor Presentation
Approach and Philosophy of On baking technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
cuic standard and advanced reporting.pdf
Tartificialntelligence_presentation.pptx
MYSQL Presentation for SQL database connectivity
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectral efficient network and resource selection model in 5G networks
Spectroscopy.pptx food analysis technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Python

  • 1. Aashish Jain Consultant, KPIT Technologies Ltd.
  • 2. Who all can learn? Beginners who have never programmed Programmers coming from another language
  • 3. Python-An Introduction General-purpose interpreted, interactive, object-oriented, high-level programming language.  Started in 1989 and published in 1991 by Guido Van Rossum.  First version was released as Python 1.0 in 1994 ABC programming language is said to be the predecessor of Python Influenced by ABC language and Modula-3
  • 4. Python-Features Easy- to- learn Easy- to- read Easy- to- maintain Portable Interactive mode A broad standard library Extendable Databases GUI programming Scalable
  • 6. Python-Application Areas  Web Applications Django, Pyramid, Flask frameworks  Desktop GUI applications wxWidgets, Kivy etc. toolkits.  Software Development  Scientific and Numeric SciPy, Panda etc.  Business Applications Tryton ERP (application)  Console Based applications  Audio or Video Based applications Timplayer, cPlay etc. (applications)  3D CAD applications  Fandango  Enterprise applications OpenErp, Picalo etc.  Application for Images Vpython, Gogh etc. Google, Youtube, Dropbox, Quora, Spotify, Instagram etc.
  • 7. Python-Resources https://www.python.org/  Documentation, tutorials, beginners guide … Other Resources:  Learning Python by Mark Lutz  Python Essential Reference by David Beazley  Python Cookbook, ed. by Martelli, Ravenscroft and Ascher  http://wiki.python.org/moin/PythonBooks
  • 8. Python v/s Jython v/s IronPython Python or CPython is written in C/C++. It is most commonly used python by developers. Jython is written in Java and runs on JVM. So, a developer can write a plugin for Java application using it. IronPython or IPython is written in .NET and runs on CLR (Common Language Runtime). So, a developer can use .NET libraries.
  • 10. Python-Installation  There are 2 different versions of Python:  Python 2.7.14  Python 3.6.4  Click here: Download Python Double click on the downloaded .exe file and install.
  • 11. Python-IDEs PyDev with Eclipse Komodo Emacs Vim TextMate Gedit Idle PIDA (Linux)(VIM Based) NotePad++ (Windows) BlueFish (Linux)
  • 12. Python-Setting Path You can set the path for python in your system using below steps: 1. Right Click on My Computer icon and navigate to following path: Properties  Advanced System Settings  Environment Variables 2. Under System Variables, search for variable Path and append C:Python27 to existing value.
  • 14. Python-Variables A name which is used to refer memory location. Also known as identifier and used to hold value. No need to specify type for variable. Variable name can be a group of letters and digits, but it must start either with a letter or an underscore. Recommended to use lower case letters.
  • 15. Python-Variables  Multiple Assignments:  Python allows developers to assign a value to multiple variables in a single statement.  Assigning Single Value to multiple variables:  x=y=z=100  Assigning Multiple Values to multiple variables:  a, b, c=20, 30, 40
  • 16. Python-Variables  Multiple Assignments:  Python allows developers to assign a value to multiple variables in a single statement.  Assigning Single Value to multiple variables:  x=y=z=100  Assigning Multiple Values to multiple variables:  a, b, c=20, 30, 40
  • 17. Python-Keywords Special reserved words which convey a special meaning to the compiler/ interpreter.
  • 18. Python-Identifiers  Names given to the fundamental building blocks in a program.  Can be variable, class, list, object, dictionary, function etc.  Rules:  Sequence of letters and numbers.  No special character can be used as an identifier except underscore (_)  Keyword must not be used as identifier.  Python is case sensitive, So using case is significant.  Identifier must start with a letter or underscore (_).
  • 19. Python-Literals  Data given in a variable or constant.  String literals: Can be formed by enclosing a text in either single or double quotes.  “Ram”, ‘232324’  Single Line String: >>> text1= “Hello”  Multi Line String: >>> text1= ‘Hello User’  Using triple quotation marks: >>> str= ‘’’ Welcome to India’’’
  • 20. Python-Literals  Numeric Literals:  int (signed integers): 100  long (long integers): 3456570L  float (floating point): -25.7  Complex (complex numbers): 3.14j  Boolean Literals:  True or False  Special Literals:  Python contains one special literal: None  Used to specify that field which has not been created.  Also used for end of lists.
  • 22. Python-Operators  Symbols that are used to perform operations on operands.  Types of Operators:  Arithmetic Operators  Comparison Operators  Assignment Operators  Logical Operators  Membership Operators  Identity Operators  Bitwise Operators
  • 23. Python-Operators  Arithmetic Operators Operators Description // Performs floor division (gives integer value) + Performs addition - Performs subtraction * Performs multiplication / Performs division % Performs Modulus (return remainder after division) ** Performs power
  • 24. Python-Operators  Comparison Operators Operators Description < Performs less than comparison > Performs greater than comparison <= Performs less than equal to comparison >= Performs greater than equal to comparison == Performs equal to comparison != Performs not equal to comparison < > Performs not equal to comparison
  • 25. Python-Operators  Assignment Operators Operators Description = Simple assignment (right side expression to left side variable) /= Performs division and then assignment += Performs addition and then assignment -= Performs subtraction and then assignment *= Performs multiplication and then assignment %= Performs modulus and then assignment **= Performs power and then assignment //= Performs floor division and then assignment
  • 26. Python-Operators  Logical Operators Operators Description and Performs Logical AND (both conditions must be true) or Performs Logical OR (one of the conditions must be true) not Performs Logical NOT (compliment the condition i.e. reverse)
  • 27. Python-Operators  Identity Operators Operators Description is Returns true if identity of two variables are same else false. is not Returns true if identity of two variables are not same else false.
  • 28. Python-Operators  Bitwise Operators Operators Description & Performs bitwise and operation | Performs bitwise or operation ^ Performs bitwise xor operation ~ Performs bitwise complement operation << Performs bitwise left shift operation >> Performs bitwise right shift operation
  • 29. Python-Comments  Single Line Comments  To put single line comments in code, use # symbol  Multi Line Comments  To put multi line comments in code enclose the comment statements with triple quotes. ‘’’ Your comment Statements ‘’’
  • 30. Python-Control Statements  Control statements are used to control the structure/flow of your application program.  An if statement decides whether to execute another statement or not.  A loop statement decides how many times to execute another statement.
  • 31. Python-Control Statements  IF- Statement:  Syntax: if (condition): // lines of code  IF-ELSE Statement:  Syntax: if (condition): // lines of code else: // lines of code
  • 32. Python-Control Statements  IF-ELIF-ELSE Statement:  Syntax: if (condition): // lines of code elif (condition): // lines of code else: // lines of code
  • 34. Python-Control Statements  FOR Loop Statement:  Syntax: for <variable> in <sequence>: // statements  Syntax: for <variable> in <sequence>: // statements else: //statements
  • 35. Python-Control Statements  WHILE Loop Statement:  Syntax: while <expression>: // statements  Syntax: while <expression>: // statements else: //statements
  • 36. Python-Control Statements  BREAK Statement:  A jump statement use to transfer execution control.  Breaks the current execution  In case of inner loop, terminates inner loop immediately.  Example: for letter in 'Python2': if letter == 'o': break print (letter)
  • 37. Python-Control Statements  CONTINUE Statement:  A jump statement use to skip execution of current iteration.  After skipping, loop continues with next iteration.  Example: a=0 while a<=5: a=a+1 if a%2==0: continue print a print "End of Loop"
  • 38. Python-Control Statements  PASS Statement:  Keyword use to execute nothing.  When developer don’t want to execute code, this can be used to execute empty.  Example: for i in [1,2,3,4,5]: if i==3: pass print "Pass when value is",i print i
  • 40. Python-Numbers  Store numeric values.  Immutable in nature.  Created when you assign a value to them.
  • 41. Python-Numbers  Type Conversion: Function Description int(x) Converts x to plain integer long(x) Converts x to a long integer float(x) Converts x to a floating-point number complex(x) Converts x to a complex number with real part x and imaginary part zero. complex(x, y) Converts x to a complex number with real part x and imaginary part y.
  • 42. Python-Numbers  Mathematical Functions: Function Description abs(x) The absolute value of x (positive) ceil(x)* The ceiling of x: smallest integer not less than x. cmp(x, y) -1 if x<y; 0 if x==y; 1 if x>y floor(x) * The floor of x: largest integer not greater than x. *import math max(x1, x2, x3,…) The largest of its arguments.
  • 43. Python-Numbers  Mathematical Functions: Function Description min(x1, x2, x3,…) The smallest of its arguments. pow(x, y) * The value of x**y. round(x [, n]) Returns x rounded to n digits from the decimal point. *import math sqrt(x) * Returns square root of x for x>0
  • 44. Python-Strings  Immutable character sequence.  Can be accessed from both the directions (forward and backward).
  • 45. Python-Strings  Tricky Operations:  Use ‘+’ to concatenate strings and ‘*’ to replicate a string.  ‘Ram’+’ Kumar’ ‘Ram Kumar’  ‘Ram’*5‘RamRamRamRamRam’  Use ‘in’ to check whether specified string is substring or not.  str1=‘This is an in example’  str2=‘in’  str2 in str1 True
  • 46. Python-Strings  Tricky Operations:  Use ‘:’ to slice a string.  str1=‘This is an example’  str1[2:3]‘i’ {startIndex (inclusive): endIndex (exclusive)}  str[::-1] {reverse a string}  Use ‘r’ to not interpret characters as special characters prefaced by ‘’.  print ‘D:newPrognewInstruction’  print r‘D:newPrognewInstruction’
  • 47. Python-Strings  Tricky Operations:  Two strings enclosed with quotes will automatically be concatenated.  str1=‘This’ ‘ is’  print str1 This is  Enclose string with ( ) to break long strings.  str1=(‘This is’ ‘ an example of’ ‘ concatenating strings’)  print str1 This is an example of concatenating strings
  • 48. Python-Strings  Functions: Function Description captialize() Capitalize the first character of the string --count(sub string [, begin] [, end]) Counts no. of times sub string occurs within given start and end index. find(sub-string [, begin] [, end]) Returns index value of the string where sub-string found between begin and end index. index(sub-string [, begin] [, end]) Works same as find() but throws an exception if sub-string not found. isalnum() Returns True if string is alphanumeric and have at least 1 character. isalpha() Returns True when all the characters are alphabets and string have at least 1 character.
  • 49. Python-Strings  Functions: Function Description isdigit() Returns True when all the characters are digits and string have at least 1 character. isupper() Returns True if all the characters of a string are in upper case. islower() Returns True if all the characters of a string are in lower case. isspace() Returns True if all the characters of a string are white space. len(string) Returns length of the string. lower() Converts all the characters of a string to lower case. upper() Converts all the characters of a string to upper case. swapcase() Inverts case of all characters in a string.
  • 51. Python-Print Formatting  Print Statements-Strings:  print ‘This string will be printed’  When using variables:  str=‘Print this string’  print ‘I have assigned the string in variable: %s’ %(str)  Print Statement-Floating Point Numbers:  print ‘Floating point Number: %f’ %(12.345)  print ‘Floating point Number: %1.2f’ %(12.345)  print ‘Floating point Number: %20.2f’ %(12.345)
  • 52. Python-Print Formatting  Print Statements-Conversion of Objects:  print ‘Converting to string: %s’ %(12345)  print ‘Converting to string : %s’ %(12.345)  print ‘Converting to string : %r’ %(12.345)  Print Statements- Multiple Variables:  print ‘First: %s Second: %1.2f Third: %d’ %(‘String’, 12.34, 12) } internally call str() } internally call repr()
  • 53. Python-Print Formatting  Print Statements-Using format():  print ‘First: {x} Second: {x}’.format(x=12)  print ‘First: {x} Second: {y}’.format(x=12, y=‘String’)  x, y=12, 10  print ‘First: {x} Second: {y}’.format(x=x, y=y)
  • 54. Python-Lists  A mutable data structure which is used to store various types of data.  Works as container which holds other objects in a given order.  Can be composed by storing a sequence of different type of values separated by commas.  Enclosed between square ([ ]) brackets and elements are stored on the index basis with starting index 0.  Example:  list1=[1,2,3,4]  list2=[‘1’,’2’,’3’,’4’]  list3=[‘1’,2.0,3,4]
  • 55. Python-Lists  Operations on Lists:  Accessing Elements  Elements can be accessed via indexing. e.g. list1[0]  List can be sliced as well to access elements. e.g. list1[2:4]
  • 56. Python-Lists  Operations on Lists:  Adding Lists  List1=[2,3,4]  List2=[5,6,7]  List3=List1+List2  List4=List1+[30]  Replicating Lists  List1=[2,3,4]  List2=List1*2
  • 57. Python-Lists  Operations on Lists:  Slicing Lists  List1=[2,3,4]  List2=List1[:1]  print List1[::-1]
  • 58. Python-Lists  List Methods: Method Name Description append(object) Add an element at the end of the existing list. pop([index]) If specified, remove the element at the given position in the list otherwise remove the last element and returns it. reverse() Reverse the elements of the list, in place. sort() Sort the elements of the list, in place. min(list) Returns the minimum value from the list given.
  • 59. Python-Lists  List Methods: Method Name Description max(list) Returns the maximum value from the list given. len(list) Returns the number of elements in the list. index(object) Returns the index value of the object. insert(index, object) Insert an object at given position remove(object) Remove the first object from the list, if not found throws an error.
  • 60. Python-Lists Comprehension  List Comprehension allows to build out list using a different notation.  It can be thought as one line for loop built inside of brackets.  Examples:  List1=[x for x in range(1,10)]  List2=[x**2 for x in range(1,10)]  List3=[x for x in range(11) if x%2==0]  List4=[x**2 for x in [x for x in range(20) if x%2==1]]  List5=[x for x in ‘Hello World’]
  • 62. Python-Dictionaries  An unordered set of key and value pair.  A container that contains data, enclosed within {}.  Key-value pair is known as item.  Key must be unique.  Key and value is separated by ‘:’ and items in dictionary are separated by ‘,’.  Examples:  my_dict={‘001’:’Alex’, ‘002’:’Akira’, ‘003’:’Ayesha’}
  • 63. Python-Dictionaries  It is mutable i.e. values can be updated.  Values can be accessed via key only.  Example:  my_dict[‘001’]  Nested Dictionaries can also be defined:  my_dict={‘key’:{‘subkey’:{‘subsubkey’:’value’}}}
  • 64. Python-Dictionaries  Dictionaries Methods: Method Name Description len(dict ) Returns the number of elements in the dictionary. keys() Returns all the keys of a dictionary. values() Returns all the values associated with keys in a dictionary. items() Returns all the items (key-value pair) in a dictionary. update(dict) Used to add items of dict to the dictionary.
  • 65. Python-Dictionaries  Dictionaries Methods: Method Name Description clear() Used to remove all items of a dictionary. copy() Shallow copies data of a dictionary has_key(key) Returns True if key is found in a dictionary otherwise False. get(key) Returns the value associated with key. If key is not present, returns None.
  • 66. Python-Tuples  A sequence of immutable objects.  Can be used to collect different types of object.  Similar to list, except tuples has immutable objects whereas list has mutable objects and list uses [] to enclose objects whereas tuple uses () to enclose objects.  Example:  tuple1=(1,2,3)
  • 67. Python-Tuples  Operations on Tuples:  Accessing Elements  Elements can be accessed via indexing. e.g. tuple1[0]  Tuple can be sliced as well to access elements. e.g. tuple1[2:4]
  • 68. Python-Tuples  Operations on Tuples:  Adding Tuples  Tuple1=(2,3,4)  Tuple2=(5,6,7)  Tuple3=Tuple1+Tuple2  Tuple4=Tuple1+(30,50)  Replicating Tuples  Tuple1=(2,3,4)  Tuple2=Tuple1*2
  • 69. Python-Tuples  Advantages of Tuples:  Tuples are faster than lists.  Makes data safe as tuples are immutable.  Used for string formatting.
  • 71. Python-Files  Python uses file object to interact with external files on system.  It can be any type of file e.g. audio, video, text, etc.  To interact with these types of files, need to install some libraries or modules which are easily available.  For instance, to read video files, need to install opencv-python package or some other available packages for video files.
  • 72. Python-Files  Installation of modules/ libraries/ packages:  To install any package for python, open command prompt and type: python pip –m install packagename e.g. python pip –m install opencv-python  To install a specific version of package: python pip –m install “packagename>=version” e.g. python pip –m install “opencv-python>=3.4.0.12”  To upgrade existing package: python pip –m install --upgrade packagename e.g. python pip –m install –upgrade opencv-python
  • 73. Python-Files  Operations on File:  Opening a File:  f=open(‘filename’, ’mode’)  filename name of a file to be opened.  mode specifies the mode in which a file can be opened. E.g. ‘r’ to read a file.  e.g. f=open(‘C:myFile.txt’, ’r’)
  • 74. Python-Files  Different modes to open a File (Text): Mode Description r Opens a file in reading mode. Pointer is at the beginning of the file. r+ Opens a file for reading and writing. Pointer is at the beginning of the file. w Opens a file in writing mode. If already exists, then overwrite the file else creates a new file. w+ Opens a file for reading and writing. If already exists, then overwrite the file else creates a new file. a Opens a file in appending mode. If already exists, then append the data at the end of the file else creates a new file. a+ Opens a file in reading and appending mode. If already exists, then append the data at the end of the file else creates a new file.
  • 75. Python-Files  Different modes to open a File (Binary): Mode Description rb Opens a file in reading mode for binary format. Pointer is at the beginning of the file. rb+ Opens a file for reading and writing for binary format. Pointer is at the beginning of the file. wb Opens a file in writing mode for binary format. If already exists, then overwrite the file else creates a new file. wb+ Opens a file for reading and writing for binary format. If already exists, then overwrite the file else creates a new file. ab Opens a file in appending mode for binary format. If already exists, then append the data at the end of the file else creates a new file. ab+ Opens a file for reading and appending mode for binary format. If already exists, then append the data at the end of the file else creates a new file.
  • 76. Python-Files  Use of with Keyword:  Sample code: with open('workfile', 'r') as f: read_data = f.read()  It’s a good practice to use this approach.  File is properly closed after its suite finishes, even if an exception is raised on the way.
  • 77. Python-Files  Methods for File object: Method Description read([size]) To read a file’s content. If size is omitted or negative then entire content of the file will be returned else read the specified quantity of data. readline() Reads a single line from the file. readlines() Reads all the lines from the file and returned as list of lines. write(text) Writes content to the file. tell() Returns an integer giving the file object’s current position in the file. close() Closes an opened file.
  • 78. Python-Files  Functions for File object by os module: , Function Description rename(old_file_name new_file_name) Use to rename an existing file. )remove(file_name Use to remove an existing file. mkdir(directory_name) Use to create a directory with the name specified. chdir(directory_name) Use to change the current working directory. getcwd() Use to get the current working directory. rmdir(directory_name) Use to delete a directory with the name specified.
  • 79. Python-Sets  A set in python holds a sequence of values.  It is sequenced but not indexed.  A set contains only unique values.  A set is mutable, but may not contain mutable items like a list, set or dictionary.  Function set() can be used to create a set from an iterable like list.
  • 80. Python-Sets  Examples:  d=set() # Creates an empty set  d={1,2,3}  Since sets do not support indexing, slicing operation can’t be performed on sets.  Since sets do not contain duplicate items, replication operation also can’t be performed. (via *)
  • 81. Python-Sets  Methods: Method Description add(object) Adds a hashable object to the set. update(object) Adds iterable objects to the set. discard(object) Deletes an object from the set. If object isn’t in the set, does nothing. remove(object) Deletes an object from the set. If object isn’t in the set, throws an error. pop() Removes first object from the set.
  • 82. Python-Sets  Methods: Method Description clear() Removes all the objects from the set i.e. empties the set. union(object) Performs union operations on the set with specified iterable objects in the arguments. intersection(object) Performs intersection operation on the set with specified iterable objects in the arguments. difference(object) Performs difference operation on the set with specified iterable objects in the arguments
  • 83. Python-Sets  Methods: Method Description issubset(object) Checks whether the set is a sub set of given object in the argument. issuperset(object) Checks whether the set is a super set of given object in the argument. isdisjoint(object) Checks whether the set is disjoint with the given object in argument.
  • 84. Python-Booleans  A Boolean value may either be True or be False.  A Boolean can be declared like other objects e.g. x=True.  Function bool() can be used to convert other types in to Boolean.  Any empty construct has a Boolean value of False and a non-empty one has True.
  • 86. Python-Methods & Functions  Methods are essentially functions built into objects.  Methods perform specific actions on the objects and can also take arguments.  Example:  object.method(arg1, arg2,…,etc)  Any information about the methods can be retrieved through help(method_name) in python.
  • 87. Python-Methods & Functions  Functions are the program section that are written once and let the programmer to not repeat the same lines of code, hence make code reusable.  Functions work on data and produces some output.  There are two types of functions:  Built-in functions: Predefined and organized into a library.  User-defined functions: Created by developer to meet the desired requirements.  Follow the link for built-in functions in python: Built-in Functions
  • 88. Python-Methods & Functions  A developer can define his/her own functions using below format:  Keyword def is used to declare a function.  def is followed by function name with parenthesis ending with a colon.  If required arguments can be provided within the parenthesis.  Example: def function_name(parameter1, parameter2): // line of codes //sample code def name_of_function(): pass
  • 89. Python-Methods & Functions  Example: def iseven(num): if num%2==0: print “Number is even” else: print “Number is not even”  The above function is defined to check whether the provided number is even or not.  The above defined function can be called as follows: iseven(10)
  • 90. Python-Methods & Functions  Example using return statement: def iseven(num): return num%2==0 iseven(15)  Add documentation for function: def iseven(num): ‘’’ This function will check whether the input number is even or not ‘’’ return num%2==0
  • 91. Python-Methods & Functions  Example using default arguments: def printMessage(id, name, branch=‘CSE’): print “id=%sn name=%sn branch=%s” %(id,name,branch) printMessage(id=‘101’, name=‘Andrew’) printMessage(id=‘102’, name=‘Ajeet’,branch=‘IT’) printMessage(name=‘Ajeet’, id=‘102’) printMessage(id=‘102’, name=‘Ajeet’,branch=‘IT’)
  • 92. Python-Methods & Functions  Local and Global Variables:  Variables defined inside a function is local variables and variables defined outside the function is called global variables.  Example: LOCAL VARIABLES def printValue(): x=10 print x printValue() print x GLOBAL VARIABLES y=5 def printValue(): x=10 print x print y printValue()
  • 94. Python-Lambda Expressions  Allows a programmer to create anonymous functions.  Allows to quickly make ad-hoc functions without needing to properly define a function using def.  It’s an expression, not a block of statements.  The result of this is an expression without explicitly defining a return statement.  Designed for coding simple functions to limit program nesting.
  • 95. Python-Lambda Expressions  Converting a normal function to lambda expression: Example: def square(x): return x*x def square(x): return x*x  Syntax for lambda: lambda input: result lambda x: x*x square=lambda x:x*x sqaure(10)
  • 96. Python-Lambda Expressions  Converting lambda expression to a normal function: Example: odd=lambda x: x%2==1 def odd(x): return x%2==1
  • 97. Python-Lambda Expressions  Lambda expression with multiple arguments: Example: add= lambda x,y: x+y add(5,4) area= lambda length, width: length*width area(40.5,30)
  • 100. Project: Tic-Tac-Toe  Problem Statement: Create an application in Python for 2-player Tic-Tac-Toe game.  Step-by-step solution for problem statement:  Variables for the application  Board: Tic-Tac-Toe board a list with size 10  Player Markers: ‘x’ and ‘o’ string types
  • 101. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 1. Create and Display Tic-Tac-Toe board 2. Choose the player’s marker and player to start the game 3. Ask the player to place his marker 4. Check if board is empty or not 5. If empty, place his marker 6. Ask another player to place his marker 7. Repeat 2-6 until the board is full or someone doesn’t declare as winner 8. If no winner found, then it’s a tie and ask to restart the game.
  • 102. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 1. Create and Display Tic-Tac-Toe board def display_board(board): print(' ___________ ') print('| | | |') print('| '+board[1]+' | '+board[2]+' | '+board[3]+' |') print('|___|___|___|') print('| | | |') print('| '+board[4]+' | '+board[5]+' | '+board[6]+' |') print('|___|___|___|') print('| | | |') print('| '+board[7]+' | '+board[8]+' | '+board[9]+' |') print('|___|___|___|')
  • 103. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 2. Select player’s marker and choose the player to start the game def player_input(): player_marker=' ' while not (player_marker=='X' or player_marker=='O'): player_marker=raw_input("Please select either X or O").upper() if player_marker=='X': return ('X', 'O') else: return ('O', 'X') def choose_first_player(): if random.randint(0,1)==0: return 'Player 1' else: return 'Player 2'
  • 104. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 3. Ask to place the marker, check the empty place and place the marker def player_choice(board): choice=' ' numberList='1 2 3 4 5 6 7 8 9' while choice not in numberList.split() or not check_place(board, int(choice)): choice=raw_input("Please enter a number between 1-9") return int(choice) def check_place(board, position): return board[position]==' ' def place_marker(board, marker, position): board[position]=marker
  • 105. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 4. Check whether the board is full or not def full_board_space_check(board): for i in range(1,10): if check_place(board, i): return False return True
  • 106. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 5. Start the game, check for winner or tie def play_game(): print('Welcome to Tic-Tac-Toe') while True: game_board=[' ']*10 player1_mark,player2_mark=player_input() turn=choose_first_player() print(turn+' will start this game') game_on=True while game_on: if turn=='Player 1': display_board(game_board) position=player_choice(game_board) place_marker(game_board, player1_mark, position) if check_winner(game_board, player1_mark): display_board(game_board) print('Congratulation...!!!! Player1 has won') game_on=False else: if full_board_space_check(game_board): display_board(game_board) print('Try next time.. Its a Tie.. ') break else: turn='Player 2'
  • 107. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 5. Start the game, check for winner or tie else: display_board(game_board) position=player_choice(game_board) place_marker(game_board, player2_mark, position) if check_winner(game_board, player2_mark): display_board(game_board) print('Congratulation...!!!! Player2 has won') game_on=False else: if full_board_space_check(game_board): display_board(game_board) print('Try next time.. Its a Tie.. ') break else: turn='Player 1' if not restart_play(): print('We will Miss you..') break def check_winner(board, marker): return board[1]==board[2]==board[3]==marker or board[4]==board[5]==board[6]==marker or board[7]==board[8]==board[9]==marker or board[1]==board[4]==board[7]==marker or board[2]==board[5]==board[8]==marker or board[3]==board[6]==board[9]==marker or board[1]==board[5]==board[9]==marker or board[3]==board[5]==board[7]==marker
  • 108. Project: Tic-Tac-Toe  Step-by-step solution for problem statement: 6. Ask to restart the game  Let’s play the game: play_game() def restart_play(): return raw_input("Do you want to play again (Yes/No)").lower().startswith('y')