SlideShare a Scribd company logo
1Copyright Ā© 2012 Tata Consultancy Services Limited
Presentation on
Python Programming
2
 Introduction
 Python Basics
 Python Decision Making
 Python Loops
 Python Sequence Types
 Python Functions
 Python File I/O
Outline
3
Introduction
 Python is a clear and powerful object-oriented programming language.
 Uses an elegant syntax, making the programs you write easier to read.
 Comes with a large standard library that supports many common programming
tasks.
 Python's interactive mode makes it easy to test short snippets of code.
 Runs on many different computers and operating systems: Windows, MacOS,
many brands of Unix, OS/2.
 Is free software in two senses. It doesn't cost anything to download or use
Python, or to include it in your application. Python can also be freely modified
and re-distributed.
4
Python: The Basics
5
A Code Sample
x = 34 – 23 # A comment
y = ā€œHelloā€ # Another one.
z = 3.45
if z == 3.45 or y == ā€œHelloā€:
x = x + 1
y = y + ā€œ Worldā€ # String concat.
print x
print y
6
Enough to Understand the Code
 Assignment uses = and comparison uses ==.
 For numbers + - * / % are as expected.
 Special use of + for string concatenation.
 Special use of % for string formatting (as with printf in C)
 Logical operators are words (and, or, not) not symbols
 The basic printing command is ā€œprintā€
 The first assignment to a variable creates it.
 Variables types don’t need to be declared.
 Python figures out the variables types on its own.
7
Whitespace
 Whitespace is meaningful in Python: especially indentation and placement of
newlines.
 Use a newline to end a line of code.
 Use ā€˜ā€™ when must go to next line prematurely
 No braces { } to mark blocks of code in Python…
 Use consistent indentation instead.
 The first line with less indentation is outside of the block
 The first line with more indentation starts a nested block.
 Often a colon appears at the start of a new block. (Eg. For function and class
definitions.)
8
Comments
 Start comments with # - the rest of line is ignored.
 Can include a ā€œdocumentation stringā€ as the first line of any new function or
class that you define.
 The development environment, debugger, and other tools use it: it’s good
style to include one.
def my_function(x, y):
ā€œā€ā€This is the docstring. This
function does …..ā€ā€ā€
# The code would go here…
9
Assignment Statements
 Binding a variable in Python means setting a name to hold a reference to
some object.
 Assignment creates references, not copies.
 Names in Python do not have an intrinsic type. Objects have types.
 A reference is deleted via garbage collection after any names bound to it have
passed out of scope.
10
Multiple Assignment
 One can also assign to multiple names at the same time.
>>> x, y = 2, 3
>>> x
2
>>> y
3
11
Naming Rules
 Names are case sensitive and cannot start with a number. They can contain
letters, numbers, and underscores.
 Bob bob _bob _2_bob_ bob_2 BoB
 There are some reserved words. Those words cannot be used to label
identifiers in a Python program.
12
Variables in Python
 A variable stores a piece of data, and gives it a specific name.
 Python is a dynamically typed language.
 Variables need not be declared in Python before using them.
 Variables can be used on the fly and Python infers its type based on the value
stored by the variable.
 Example: Set the variable ā€œageā€ equal to the value 20.
>>> age = 20
 Now ā€œageā€ can be used in any arithmetic operations, such as,
>>> age_after_10 = age + 10 # 30
13
Basic Data Types
 Python supports the usual data types, such as,
ļ‚§ Integers
ļ‚§ Floats
ļ‚§ Strings
 If both operands are of type int, floor division is performed and an int is
returned.
 If either operand is a float, classic division is performed and a float is
returned.
 In addition to int and float, Python supports other types of numbers, such as
Decimal, Fraction and Complex numbers.
14
Fun with Python Arithmetic
>>> 17 / 3 # int / int -> int
5
>>> 17 / 3.0 # int / float -> float
5.666666666666667
>>> 17 % 3 # the % operator returns the remainder
2
>>> 5 ** 2 # 5 squared
25
15
Python Strings
 Besides numbers, Python can also manipulate strings, which can be expressed
in several ways.
 Strings can be enclosed in single quotes ('...') or double quotes ("…").
 The string is enclosed in double quotes if the string contains a single quote and
no double quotes, otherwise it is enclosed in single quotes.
 String literals can span multiple lines. One way is using triple-quotes:
"""...""" or '''...'''.
 Strings can be concatenated (glued together) with the + operator, and repeated
with *.
>>> 3 * ā€˜un’ + ā€˜ium’
ā€˜unununium’
16
String Examples
>>> 'doesn't' # use ' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Isn't," she said.'
'"Isn't," she said.'
>>> print '"Isn't," she said.'
"Isn't," she said.
17
Strings Continued…
 Strings can be indexed (subscripted), with the first character having index 0.
 There is no separate character type; a character is simply a string of size one.
 Indices may also be negative numbers, while counting from the right.
 Say, word = ā€˜Python’
>>> word[-1] # last character
ā€˜n’
>>> word[-2] # second last character
ā€˜o’
18
Strings Continued…
 In addition to indexing, slicing is also supported. While indexing is used to
obtain individual characters, slicing allows you to obtain a substring.
 In slicing, the start is always included, and the end always excluded. This
makes sure that s[:i] + s[i:] is always equal to s.
19
Python Decision Making:
if, if…else, if…elif…else
20
Python Decision Structures
 Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken to the conditions.
 Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome.
 Python programming language assumes any non-zero and non-null values as
TRUE, and if it is either zero or null, then it is assumed as FALSE value.
 If the suite of an if clause consists of a single line, it may go on the same line as
the header statement.
21
If in Action…
#!/usr/bin/python
var = 100
if var == 100: print ā€œValue of expression is 100ā€
print ā€œGood Bye!ā€
22
Loops In Python:
while, for…in, nested loops
23
Loop Statements
 Programming languages provide various control structures that allow for more
complicated execution paths.
 A loop statement allows us to execute a statement or group of statements
multiple times.
 Python provides the following looping constructs:
 While loop
 For loop
 Loop Control Statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
 Eg:. Break, continue, pass.
24
While Loop
 A while loop statement in Python, repeatedly executes a target statement as
long as a given condition is true.
 Syntax:
while expression:
statement(s)
Eg: #!/usr/bin/python
count = 0
while count < 9:
print ā€œThe count is:ā€, count
count = count + 1
25
For loop
 It has the ability to iterate over the items of any sequence, such as list or a
string.
 Syntax:
for iterating_var in sequence:
statement(s)
 If a sequence contains an expression list, it is evaluated first. Then, the first
item in the sequence is assigned to the iterating varaiable iterating_var.
 Each item in the sequence is iterated over, until the entire sequence is
exhausted.
26
For loop in action…
ā— Eg:.
#!usr/bin/python
for letter in ā€˜Python’: # First Example
print ā€˜Current letter:’, letter
Fruits = [ā€˜banana’, ā€˜apple’, ā€˜mango’]
for fruit in fruits: # Second Example
print ā€œCurrent Fruit:ā€, fruit
27
Iterating by sequence index
 An alternative way of iterating through each item is by index offset into the
sequence itself.
 Eg:.
fruits = [ā€œbananaā€, ā€œappleā€, ā€œmangoā€]
for index in range(len(fruits)):
print ā€œCurrent fruit:ā€, fruits[index]
 In the above example, we took assistance of the len() built-in function, which
provides the total number of elements in the tuple as well as the range() built-in
function to give us the actual sequence to iterate over.
28
Using else statements with Loops
 Python supports to have an else statement associated with a loop
 If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted the sequence.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
29
Else with loops Example
ā— The following example illustrates the combination of an else statement with
statement that searches for prime numbers from 10 through 20.
for num in range(10, 20): # to iterate between 10 to 20
for i in range(2, num): # to iterate on the factors of the number
if num % i == 0: # To determine the first factor
j = num / i # To calculate the second factor
print ā€˜%d equals %d * %d’ % (num, i, j)
break
else:
print num, ā€˜is a prime number’
30
Sequence Types:
Tuples, Lists, and Strings
31
Sequence Types
 Tuple
ļ‚§ A simple immutable ordered sequence of items
ļ‚§ Items can be of mixed types, including collection types
 Strings
ļ‚§ Immutable
ļ‚§ Conceptually very much like a tuple
 List
ļ‚§ Mutable ordered sequence of items of mixed types.
32
Similar Syntax
 All three sequence types (tuples, strings, and lists) share much of the same
syntax and functionality.
 Key Difference:
Tuples and strings are immutable
Lists are mutable
 The operations shown in this section can be applied to all sequence types
 Most examples will just show the operation performed on one.
33
Sequence Types 1
 Tuples are defined using parentheses (and commas).
>>> tu = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)
 Lists are defined using square brackets (and commas).
>>> li = [ā€œabcā€, 34, 4.34, 23]
 Strings are defined using quotes (ā€œ, ā€˜, or ā€œā€ā€).
>>> st = ā€œHello Worldā€
>>> st = ā€˜Hello World’
>>>st = ā€œā€ā€This is a multi-line string that
uses triple quotes.ā€ā€ā€
34
Sequence Types 2
 We can access individual members of a tuple, list, or string using square
bracket ā€œarrayā€ notation.
 Note that all are 0 based…
>>> tu[1] # Second item in the tuple.
ā€˜abc’
>>> li[1] # Second item in the list.
34
>>> st[1] # Second character in string.
ā€˜e’
35
Positive and Negative Indices
>>> t = (23, ā€˜abc’, 4.56, 2,3), ā€˜def’)
 Positive index: count from left, starting with 0.
>>> t[1]
ā€˜abc’
 Negative lookup: count from right, starting with -1.
>>> t[-3]
4.56
36
Slicing: Return Copy of a Subset 1
>>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)
 Return a copy of the container with a subset of the original members. Start
copying at the first index, and stop copying before the second index.
>>> t[1:4]
(ā€˜abc’, 4.56, (2,3))
 You can also use negative indices when slicing.
>>> t[1:-1]
(ā€˜abc’, 4.56, (2,3))
37
Slicing: Return Copy of a Subset 2
>>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)
 Omit the first index to make a copy starting from the beginning of the
container.
>>> t[:2]
(23, ā€˜abc’)
 Omit the second index to make a copy starting at the first index and going to
the end of the container.
>>> t[2:]
(4.56, (2,3), ā€˜def’)
38
Copying the Whole Sequence
 To make a copy of an entire sequence, you can use [:].
>>> t[:]
(23, ā€˜abc’, 4.56, (2,3), ā€˜def’)
 Note the difference between these two lines for mutable sequences:
>>> list2 = list1 # 2 names refer to 1 ref
# Changing one affects both
>>> list2 = list1[:] # Two independent copies, two refs
39
The ā€˜in’ Operator
 Boolean test whether a value is inside a container:
>>> t = [1, 2, 3, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
40
ā€˜in’ Operator Continued…
 For strings, tests for substrings
>>> a = ā€˜abcde’
>>> ā€˜c’ in a
True
>>> ā€˜cd’ in a
True
>>> ā€˜ac’ in a
False
 Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions.
41
The + Operator
 The + operator produces a new tuple, list, or string whose value is the
concatenation of its arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> ā€œHelloā€ + ā€œ ā€œ + ā€œWorldā€
ā€˜Hello World’
42
The * Operator
 The * operator produces a new tuple, list, or string that ā€œrepeatsā€ the
original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> ā€œHelloā€ * 3
ā€˜HelloHelloHello’
43
Mutability:
Tuples vs. Lists
44
Tuples: Immutable
>>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def)
>>> t[2] = 3.14
You can’t change a tuple.
 You can make a fresh tuple and assign its reference to a previously used
name.
>>> t = (23, ā€˜abc’, 3.14, (2,3), ā€˜def’)
45
Lists: Mutable
>>> li = [ā€˜abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[ā€˜abc’, 45, 4.34, 23]
We can change lists in place.
Name li still points to the same memory reference when we’re done.
The mutability of lists means that they aren’t as fast as tuples.
46
Operations on lists Only 1
>>> li = [1, 11, 3, 4, 5]
>>> li.append(ā€˜a’) # Our first exposure to method syntax
>>> li
[1, 11, 3, 4, 5, ā€˜a’]
>>> li.insert(2, ā€˜i’)
>>> li
[1, 11, ā€˜i’, 3, 4, 5, ā€˜a’]
47
The extend method vs the + operator
 ā€˜+’ creates a fresh list (with a new memory reference)
 Extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ā€˜i’, 3, 4, 5, ā€˜a’, 9, 8, 7]
 Confusing:
• Extend takes a list as an argument.
• Append takes a singleton as an argument.
>>> li.append([10, 11, 12])
48
Operations on Lists Only 3
>>> li = [ā€˜a’, ā€˜b’, ā€˜c’, ā€˜b’]
>>> li.index(ā€˜b’) # index of first occurrence
1
>>> li.count(ā€˜b’) # number of occurences
2
>>> li.remove(ā€˜b’) # remove first occurrence
>>> li
[ā€˜a’, ā€˜c’, ā€˜b’]
49
Operations on Lists Only 4
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
50
Tuples vs. Lists
 Lists slower but more powerful than tuples.
 Lists can be modified, and they have lots of handy operations we can perform
on them.
 Tuples are immutable and have fewer features.
 To convert between tuples and lists use the list() and tuple() functions:
>>> li = list(tu)
>>> tu = tuple(li)
51
Python Dictionary
 Each key is separated from its value by a colon ( : ), the items are separated by
commas, and the whole thing is enclosed in curly braces.
 An empty dictionary without any items is written with just two curly braces,
like this { }.
 Keys are unique within a dictionary while values my not be.
 The values can be of any type, but the keys must be of an immutable data type
such as strings, numbers, or tuples.
52
Accessing Values in a Dictionary
 To access dictionary elements, we can use the familiar square brackets along
with the key to obtain its value.
Eg:. dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’}
print dict[ā€˜Name’]
print dict[ā€˜Age’]
 If we attempt to access a data item with a key, which is not part of the
dictionary, we will get an error.
53
Updating Dictionary
 We can update a dictionary by adding a new entry or key-value pair,
modifying an existing entry, or deleting an existing entry.
Eg:.
dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’}
dict[ā€˜Age’] = 8 # Update existing entry
dict[ā€˜School’] = ā€œDPS Schoolā€ # Add new entry
54
Delete Dictionary Elements
 We can either remove individual dictionary elements or clear the entire
contents of a dictionary.
 We can also delete the entire dictionary in a single operation.
 To explicitly remove an entire dictionary, just use the del statement.
dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’}
del dict[ā€˜Name’] # Delete an element
dict.clear() # Clear the contents of the dictionary
del dict # Remove the entire dictionary structure.
55
Python Functions:
code organization and reusability
56
Function as a Concept
 A function is a block of organized, reusable code that is used to perform a
single, related action.
 Functions provide better modularity for an application and a high degree of
code reusing.
 Python gives us may built-in functions like print(), etc.
 We can also create our own functions. These are called user-defined functions.
57
Defining a Function
 Function blocks begin with the keyword def followed by the function
name and parentheses.
 Any input parameters or arguments should be placed within these
parentheses. We can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement – the
documentation string of the function or docstring.
 The code block within every function starts with a colon ( : ) and is
indented.
 The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments
is the same as return None.
58
Function Structure
def function_name ( parameters ):
ā€œfunction_docstringā€
function_suite
return [expression]
Eg:.
def printme (str):
ā€œThis prints a passed string into this functionā€
print str
return
59
Function Arguments
 Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
 Keyword arguments are related to the function calls. When we use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
 Default arguments are arguments that assume a default value if a value is not
provided in the function call for that argument.
 When we may need to process a function for more arguments than we specified
while defining the function, we use variable-length arguments. They are also
known as splat-arguments
60
Python files I/O:
input and output with persistence
61
Python File Manipulation
 Python provides basic functions and methods necessary to manipulate files by
default.
 Most of the file manipulation is done using a file object.
 The various file handling methods supported are:
open()
close()
write()
read()
tell()
62
The open() Function
 Before we can read or write to a file, we have to open it.
 This function creates a file object, which would be utilized to call other support
methods associated with it.
 Syntax:
file_object = open(file_name [, access_mode][, buffering])
 The commonly used access modes are ā€˜r’, ā€˜rb’, ā€˜r+’, ā€˜rb+’, ā€˜w’, ā€˜wb’, ā€˜w+’,
ā€˜wb+’ and ā€˜a’.
 Eg:.
fo = open(ā€œfoo.txtā€, ā€œwbā€)
63
The close() Method
 The close() method of a file object flushes any unwritten information and
closes the file object, after which no more I/O can be done.
 Python automatically closes a file when the reference object of a file is
reassigned to another file.
 Syntax:
file_object.close()
64
The write() Method
 The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
 The write() method does not add a newline character(ā€˜n’) to the end of the
string.
 Syntax:
File_object.write(string)
65
The read() Method
 The read() method reads a string from an open file.
 Syntax:
file_object.read ( [count] )
 Here, the passed parameter is the number of bytes to be read from the opened
file.
 This method starts reading from the beginning of the file and if count is
missing, then it tries to read as much as possible, maybe until the end of file.
66
An Example…
fo = open(ā€œfoo.txtā€, ā€œr+ā€) # Open a file
str = fo.read(10)
print ā€œRead string is: ā€œ, str
position = fo.tell() # Check current position
print ā€œCurrent file position: ā€œ, position
position = fo.seek(0,0) # Reposition pointer to the beginning
str = fo.read(10)
print ā€œAgain read string is: ā€œ, str
fo.close()
67
Renaming and Deleting Files
 Python os module provides methods that helps us perform file-processing
operations, such as renaming and deleting files.
 To use this module, we need to import it first and then only we can call any
related functions.
 Rename Method – os.rename (curr_file_name, new_file_name)
 Remove Method – os.remove (file_name)
 In order to import a module, we just type: import module_name
68
Directory Manipulation in Python
 The os module has several methods that help us create, remove and change
directories.
 Some of the commonly used methods are:
 mkdir() - os.mkdir(ā€œdir_nameā€)
 chdir() - os.chdir(ā€œnew_dir)
 getcwd() – os.getcwd()
 rmdir() – os.rmdir(ā€˜dir_name’)
69Copyright Ā© 2012 Tata Consultancy Services Limited
Thank You

More Related Content

PDF
Python Crash Course
Haim Michael
Ā 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
Ā 
PPTX
Python presentation by Monu Sharma
Mayank Sharma
Ā 
PDF
Python - the basics
University of Technology
Ā 
PPT
Introduction to Python
amiable_indian
Ā 
PPTX
Python basics
Jyoti shukla
Ā 
PDF
Python course syllabus
Sugantha T
Ā 
PDF
Python made easy
Abhishek kumar
Ā 
Python Crash Course
Haim Michael
Ā 
Python Tutorial Part 1
Haitham El-Ghareeb
Ā 
Python presentation by Monu Sharma
Mayank Sharma
Ā 
Python - the basics
University of Technology
Ā 
Introduction to Python
amiable_indian
Ā 
Python basics
Jyoti shukla
Ā 
Python course syllabus
Sugantha T
Ā 
Python made easy
Abhishek kumar
Ā 

What's hot (20)

PDF
Python basic
Saifuddin Kaijar
Ā 
PPT
Python ppt
Mohita Pandey
Ā 
PPTX
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
Ā 
PPTX
Looping statement in python
RaginiJain21
Ā 
ODP
Python Modules
Nitin Reddy Katkam
Ā 
PPTX
Python
Aashish Jain
Ā 
PPTX
Modules in Python Programming
sambitmandal
Ā 
PPT
Python ppt
Rohit Verma
Ā 
PPTX
Beginning Python Programming
St. Petersburg College
Ā 
PPTX
Introduction to python
Ayshwarya Baburam
Ā 
PPTX
Python - An Introduction
Swarit Wadhe
Ā 
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Edureka!
Ā 
PPTX
Python programming | Fundamentals of Python programming
KrishnaMildain
Ā 
PPTX
Python in 30 minutes!
Fariz Darari
Ā 
PPTX
Python
Sangita Panchal
Ā 
PDF
Operators in java
Muthukumaran Subramanian
Ā 
PPTX
Introduction python
Jumbo Techno e_Learning
Ā 
PPTX
Python programming
Ashwin Kumar Ramasamy
Ā 
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
Ā 
PPTX
Python for loop
Aishwarya Deshmukh
Ā 
Python basic
Saifuddin Kaijar
Ā 
Python ppt
Mohita Pandey
Ā 
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
Ā 
Looping statement in python
RaginiJain21
Ā 
Python Modules
Nitin Reddy Katkam
Ā 
Python
Aashish Jain
Ā 
Modules in Python Programming
sambitmandal
Ā 
Python ppt
Rohit Verma
Ā 
Beginning Python Programming
St. Petersburg College
Ā 
Introduction to python
Ayshwarya Baburam
Ā 
Python - An Introduction
Swarit Wadhe
Ā 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Edureka!
Ā 
Python programming | Fundamentals of Python programming
KrishnaMildain
Ā 
Python in 30 minutes!
Fariz Darari
Ā 
Python
Sangita Panchal
Ā 
Operators in java
Muthukumaran Subramanian
Ā 
Introduction python
Jumbo Techno e_Learning
Ā 
Python programming
Ashwin Kumar Ramasamy
Ā 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
Ā 
Python for loop
Aishwarya Deshmukh
Ā 
Ad

Viewers also liked (20)

PPT
Introduction to Python
Nowell Strite
Ā 
PDF
Learn 90% of Python in 90 Minutes
Matt Harrison
Ā 
PPTX
Python PPT
Edureka!
Ā 
PPTX
Introduction to python for Beginners
Sujith Kumar
Ā 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
Ā 
ODP
Inro to Secure Sockets Layer: SSL
Dipankar Achinta
Ā 
PPTX
Python Hype?
Brian Ray
Ā 
PDF
A 12 hour workshop on Introduction to Python
Satyaki Sikdar
Ā 
PPTX
Python programming language
Ebrahim Shakhatreh
Ā 
PDF
Workshop on Programming in Python - day II
Satyaki Sikdar
Ā 
PDF
An Introduction to Python Programming
Morteza Zakeri
Ā 
PPTX
Python Programming Language
Laxman Puri
Ā 
PDF
Object-oriented Programming in Python
Juan-Manuel Gimeno
Ā 
PDF
Python Advanced – Building on the foundation
Kevlin Henney
Ā 
PPTX
Introduction about Python by JanBask Training
JanBask Training
Ā 
PDF
Python/Django Training
University of Technology
Ā 
ODP
Python Presentation
Narendra Sisodiya
Ā 
PDF
Python Worst Practices
Daniel Greenfeld
Ā 
PPTX
Degenerative diseases
Ummu Abdurrahman
Ā 
Introduction to Python
Nowell Strite
Ā 
Learn 90% of Python in 90 Minutes
Matt Harrison
Ā 
Python PPT
Edureka!
Ā 
Introduction to python for Beginners
Sujith Kumar
Ā 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
Ā 
Inro to Secure Sockets Layer: SSL
Dipankar Achinta
Ā 
Python Hype?
Brian Ray
Ā 
A 12 hour workshop on Introduction to Python
Satyaki Sikdar
Ā 
Python programming language
Ebrahim Shakhatreh
Ā 
Workshop on Programming in Python - day II
Satyaki Sikdar
Ā 
An Introduction to Python Programming
Morteza Zakeri
Ā 
Python Programming Language
Laxman Puri
Ā 
Object-oriented Programming in Python
Juan-Manuel Gimeno
Ā 
Python Advanced – Building on the foundation
Kevlin Henney
Ā 
Introduction about Python by JanBask Training
JanBask Training
Ā 
Python/Django Training
University of Technology
Ā 
Python Presentation
Narendra Sisodiya
Ā 
Python Worst Practices
Daniel Greenfeld
Ā 
Degenerative diseases
Ummu Abdurrahman
Ā 
Ad

Similar to Intro to Python Programming Language (20)

PPTX
cupdf.com_python-seminar-ppt.pptx.........
ansuljoshi8456
Ā 
PDF
python-160403194316.pdf
gmadhu8
Ā 
PPTX
Python Seminar PPT
Shivam Gupta
Ā 
PPTX
Python
Shivam Gupta
Ā 
PPT
Python - Module 1.ppt
jaba kumar
Ā 
PPTX
Python Introduction
Punithavel Ramani
Ā 
PPTX
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
Ā 
PPTX
Basic of Python- Hands on Session
Dharmesh Tank
Ā 
PPTX
python BY ME-2021python anylssis(1).pptx
rekhaaarohan
Ā 
PDF
Python Module-1.1.pdf
4HG19EC010HARSHITHAH
Ā 
PPTX
Teach The Nation To Code.pptx
HermonYohannes2
Ā 
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
Ā 
PDF
Python indroduction
FEG
Ā 
PDF
Python_Programming_PPT Basics of python programming language
earningmoney9595
Ā 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
Ā 
PDF
Introduction To Programming with Python
Sushant Mane
Ā 
PDF
problem solving and python programming UNIT 2.pdf
rajesht522501
Ā 
PDF
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
Ā 
PPTX
python presntation 2.pptx
Arpittripathi45
Ā 
PPTX
Introduction to Python Programming Language
merlinjohnsy
Ā 
cupdf.com_python-seminar-ppt.pptx.........
ansuljoshi8456
Ā 
python-160403194316.pdf
gmadhu8
Ā 
Python Seminar PPT
Shivam Gupta
Ā 
Python
Shivam Gupta
Ā 
Python - Module 1.ppt
jaba kumar
Ā 
Python Introduction
Punithavel Ramani
Ā 
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
Ā 
Basic of Python- Hands on Session
Dharmesh Tank
Ā 
python BY ME-2021python anylssis(1).pptx
rekhaaarohan
Ā 
Python Module-1.1.pdf
4HG19EC010HARSHITHAH
Ā 
Teach The Nation To Code.pptx
HermonYohannes2
Ā 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
Ā 
Python indroduction
FEG
Ā 
Python_Programming_PPT Basics of python programming language
earningmoney9595
Ā 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
Ā 
Introduction To Programming with Python
Sushant Mane
Ā 
problem solving and python programming UNIT 2.pdf
rajesht522501
Ā 
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
Ā 
python presntation 2.pptx
Arpittripathi45
Ā 
Introduction to Python Programming Language
merlinjohnsy
Ā 

Recently uploaded (20)

PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
Ā 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
Ā 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
Ā 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
Ā 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
Ā 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
Ā 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
Ā 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
Ā 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
Ā 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
Ā 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
PDF
This slide provides an overview Technology
mineshkharadi333
Ā 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
Ā 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
PDF
Software Development Company | KodekX
KodekX
Ā 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
Ā 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
Ā 
Presentation about Hardware and Software in Computer
snehamodhawadiya
Ā 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
Ā 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
Ā 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
Ā 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
Ā 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
Ā 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
Ā 
cloud computing vai.pptx for the project
vaibhavdobariyal79
Ā 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
This slide provides an overview Technology
mineshkharadi333
Ā 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
Ā 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
Software Development Company | KodekX
KodekX
Ā 

Intro to Python Programming Language

  • 1. 1Copyright Ā© 2012 Tata Consultancy Services Limited Presentation on Python Programming
  • 2. 2  Introduction  Python Basics  Python Decision Making  Python Loops  Python Sequence Types  Python Functions  Python File I/O Outline
  • 3. 3 Introduction  Python is a clear and powerful object-oriented programming language.  Uses an elegant syntax, making the programs you write easier to read.  Comes with a large standard library that supports many common programming tasks.  Python's interactive mode makes it easy to test short snippets of code.  Runs on many different computers and operating systems: Windows, MacOS, many brands of Unix, OS/2.  Is free software in two senses. It doesn't cost anything to download or use Python, or to include it in your application. Python can also be freely modified and re-distributed.
  • 5. 5 A Code Sample x = 34 – 23 # A comment y = ā€œHelloā€ # Another one. z = 3.45 if z == 3.45 or y == ā€œHelloā€: x = x + 1 y = y + ā€œ Worldā€ # String concat. print x print y
  • 6. 6 Enough to Understand the Code  Assignment uses = and comparison uses ==.  For numbers + - * / % are as expected.  Special use of + for string concatenation.  Special use of % for string formatting (as with printf in C)  Logical operators are words (and, or, not) not symbols  The basic printing command is ā€œprintā€  The first assignment to a variable creates it.  Variables types don’t need to be declared.  Python figures out the variables types on its own.
  • 7. 7 Whitespace  Whitespace is meaningful in Python: especially indentation and placement of newlines.  Use a newline to end a line of code.  Use ā€˜ā€™ when must go to next line prematurely  No braces { } to mark blocks of code in Python…  Use consistent indentation instead.  The first line with less indentation is outside of the block  The first line with more indentation starts a nested block.  Often a colon appears at the start of a new block. (Eg. For function and class definitions.)
  • 8. 8 Comments  Start comments with # - the rest of line is ignored.  Can include a ā€œdocumentation stringā€ as the first line of any new function or class that you define.  The development environment, debugger, and other tools use it: it’s good style to include one. def my_function(x, y): ā€œā€ā€This is the docstring. This function does …..ā€ā€ā€ # The code would go here…
  • 9. 9 Assignment Statements  Binding a variable in Python means setting a name to hold a reference to some object.  Assignment creates references, not copies.  Names in Python do not have an intrinsic type. Objects have types.  A reference is deleted via garbage collection after any names bound to it have passed out of scope.
  • 10. 10 Multiple Assignment  One can also assign to multiple names at the same time. >>> x, y = 2, 3 >>> x 2 >>> y 3
  • 11. 11 Naming Rules  Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores.  Bob bob _bob _2_bob_ bob_2 BoB  There are some reserved words. Those words cannot be used to label identifiers in a Python program.
  • 12. 12 Variables in Python  A variable stores a piece of data, and gives it a specific name.  Python is a dynamically typed language.  Variables need not be declared in Python before using them.  Variables can be used on the fly and Python infers its type based on the value stored by the variable.  Example: Set the variable ā€œageā€ equal to the value 20. >>> age = 20  Now ā€œageā€ can be used in any arithmetic operations, such as, >>> age_after_10 = age + 10 # 30
  • 13. 13 Basic Data Types  Python supports the usual data types, such as, ļ‚§ Integers ļ‚§ Floats ļ‚§ Strings  If both operands are of type int, floor division is performed and an int is returned.  If either operand is a float, classic division is performed and a float is returned.  In addition to int and float, Python supports other types of numbers, such as Decimal, Fraction and Complex numbers.
  • 14. 14 Fun with Python Arithmetic >>> 17 / 3 # int / int -> int 5 >>> 17 / 3.0 # int / float -> float 5.666666666666667 >>> 17 % 3 # the % operator returns the remainder 2 >>> 5 ** 2 # 5 squared 25
  • 15. 15 Python Strings  Besides numbers, Python can also manipulate strings, which can be expressed in several ways.  Strings can be enclosed in single quotes ('...') or double quotes ("…").  The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes.  String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''.  Strings can be concatenated (glued together) with the + operator, and repeated with *. >>> 3 * ā€˜un’ + ā€˜ium’ ā€˜unununium’
  • 16. 16 String Examples >>> 'doesn't' # use ' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Isn't," she said.' '"Isn't," she said.' >>> print '"Isn't," she said.' "Isn't," she said.
  • 17. 17 Strings Continued…  Strings can be indexed (subscripted), with the first character having index 0.  There is no separate character type; a character is simply a string of size one.  Indices may also be negative numbers, while counting from the right.  Say, word = ā€˜Python’ >>> word[-1] # last character ā€˜n’ >>> word[-2] # second last character ā€˜o’
  • 18. 18 Strings Continued…  In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring.  In slicing, the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s.
  • 19. 19 Python Decision Making: if, if…else, if…elif…else
  • 20. 20 Python Decision Structures  Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken to the conditions.  Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.  Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.  If the suite of an if clause consists of a single line, it may go on the same line as the header statement.
  • 21. 21 If in Action… #!/usr/bin/python var = 100 if var == 100: print ā€œValue of expression is 100ā€ print ā€œGood Bye!ā€
  • 22. 22 Loops In Python: while, for…in, nested loops
  • 23. 23 Loop Statements  Programming languages provide various control structures that allow for more complicated execution paths.  A loop statement allows us to execute a statement or group of statements multiple times.  Python provides the following looping constructs:  While loop  For loop  Loop Control Statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.  Eg:. Break, continue, pass.
  • 24. 24 While Loop  A while loop statement in Python, repeatedly executes a target statement as long as a given condition is true.  Syntax: while expression: statement(s) Eg: #!/usr/bin/python count = 0 while count < 9: print ā€œThe count is:ā€, count count = count + 1
  • 25. 25 For loop  It has the ability to iterate over the items of any sequence, such as list or a string.  Syntax: for iterating_var in sequence: statement(s)  If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating varaiable iterating_var.  Each item in the sequence is iterated over, until the entire sequence is exhausted.
  • 26. 26 For loop in action… ā— Eg:. #!usr/bin/python for letter in ā€˜Python’: # First Example print ā€˜Current letter:’, letter Fruits = [ā€˜banana’, ā€˜apple’, ā€˜mango’] for fruit in fruits: # Second Example print ā€œCurrent Fruit:ā€, fruit
  • 27. 27 Iterating by sequence index  An alternative way of iterating through each item is by index offset into the sequence itself.  Eg:. fruits = [ā€œbananaā€, ā€œappleā€, ā€œmangoā€] for index in range(len(fruits)): print ā€œCurrent fruit:ā€, fruits[index]  In the above example, we took assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.
  • 28. 28 Using else statements with Loops  Python supports to have an else statement associated with a loop  If the else statement is used with a for loop, the else statement is executed when the loop has exhausted the sequence.  If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
  • 29. 29 Else with loops Example ā— The following example illustrates the combination of an else statement with statement that searches for prime numbers from 10 through 20. for num in range(10, 20): # to iterate between 10 to 20 for i in range(2, num): # to iterate on the factors of the number if num % i == 0: # To determine the first factor j = num / i # To calculate the second factor print ā€˜%d equals %d * %d’ % (num, i, j) break else: print num, ā€˜is a prime number’
  • 31. 31 Sequence Types  Tuple ļ‚§ A simple immutable ordered sequence of items ļ‚§ Items can be of mixed types, including collection types  Strings ļ‚§ Immutable ļ‚§ Conceptually very much like a tuple  List ļ‚§ Mutable ordered sequence of items of mixed types.
  • 32. 32 Similar Syntax  All three sequence types (tuples, strings, and lists) share much of the same syntax and functionality.  Key Difference: Tuples and strings are immutable Lists are mutable  The operations shown in this section can be applied to all sequence types  Most examples will just show the operation performed on one.
  • 33. 33 Sequence Types 1  Tuples are defined using parentheses (and commas). >>> tu = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)  Lists are defined using square brackets (and commas). >>> li = [ā€œabcā€, 34, 4.34, 23]  Strings are defined using quotes (ā€œ, ā€˜, or ā€œā€ā€). >>> st = ā€œHello Worldā€ >>> st = ā€˜Hello World’ >>>st = ā€œā€ā€This is a multi-line string that uses triple quotes.ā€ā€ā€
  • 34. 34 Sequence Types 2  We can access individual members of a tuple, list, or string using square bracket ā€œarrayā€ notation.  Note that all are 0 based… >>> tu[1] # Second item in the tuple. ā€˜abc’ >>> li[1] # Second item in the list. 34 >>> st[1] # Second character in string. ā€˜e’
  • 35. 35 Positive and Negative Indices >>> t = (23, ā€˜abc’, 4.56, 2,3), ā€˜def’)  Positive index: count from left, starting with 0. >>> t[1] ā€˜abc’  Negative lookup: count from right, starting with -1. >>> t[-3] 4.56
  • 36. 36 Slicing: Return Copy of a Subset 1 >>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)  Return a copy of the container with a subset of the original members. Start copying at the first index, and stop copying before the second index. >>> t[1:4] (ā€˜abc’, 4.56, (2,3))  You can also use negative indices when slicing. >>> t[1:-1] (ā€˜abc’, 4.56, (2,3))
  • 37. 37 Slicing: Return Copy of a Subset 2 >>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)  Omit the first index to make a copy starting from the beginning of the container. >>> t[:2] (23, ā€˜abc’)  Omit the second index to make a copy starting at the first index and going to the end of the container. >>> t[2:] (4.56, (2,3), ā€˜def’)
  • 38. 38 Copying the Whole Sequence  To make a copy of an entire sequence, you can use [:]. >>> t[:] (23, ā€˜abc’, 4.56, (2,3), ā€˜def’)  Note the difference between these two lines for mutable sequences: >>> list2 = list1 # 2 names refer to 1 ref # Changing one affects both >>> list2 = list1[:] # Two independent copies, two refs
  • 39. 39 The ā€˜in’ Operator  Boolean test whether a value is inside a container: >>> t = [1, 2, 3, 4, 5] >>> 3 in t False >>> 4 in t True >>> 4 not in t False
  • 40. 40 ā€˜in’ Operator Continued…  For strings, tests for substrings >>> a = ā€˜abcde’ >>> ā€˜c’ in a True >>> ā€˜cd’ in a True >>> ā€˜ac’ in a False  Be careful: the in keyword is also used in the syntax of for loops and list comprehensions.
  • 41. 41 The + Operator  The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments. >>> (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> ā€œHelloā€ + ā€œ ā€œ + ā€œWorldā€ ā€˜Hello World’
  • 42. 42 The * Operator  The * operator produces a new tuple, list, or string that ā€œrepeatsā€ the original content. >>> (1, 2, 3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> ā€œHelloā€ * 3 ā€˜HelloHelloHello’
  • 44. 44 Tuples: Immutable >>> t = (23, ā€˜abc’, 4.56, (2,3), ā€˜def) >>> t[2] = 3.14 You can’t change a tuple.  You can make a fresh tuple and assign its reference to a previously used name. >>> t = (23, ā€˜abc’, 3.14, (2,3), ā€˜def’)
  • 45. 45 Lists: Mutable >>> li = [ā€˜abc’, 23, 4.34, 23] >>> li[1] = 45 >>> li [ā€˜abc’, 45, 4.34, 23] We can change lists in place. Name li still points to the same memory reference when we’re done. The mutability of lists means that they aren’t as fast as tuples.
  • 46. 46 Operations on lists Only 1 >>> li = [1, 11, 3, 4, 5] >>> li.append(ā€˜a’) # Our first exposure to method syntax >>> li [1, 11, 3, 4, 5, ā€˜a’] >>> li.insert(2, ā€˜i’) >>> li [1, 11, ā€˜i’, 3, 4, 5, ā€˜a’]
  • 47. 47 The extend method vs the + operator  ā€˜+’ creates a fresh list (with a new memory reference)  Extend operates on list li in place. >>> li.extend([9, 8, 7]) >>> li [1, 2, ā€˜i’, 3, 4, 5, ā€˜a’, 9, 8, 7]  Confusing: • Extend takes a list as an argument. • Append takes a singleton as an argument. >>> li.append([10, 11, 12])
  • 48. 48 Operations on Lists Only 3 >>> li = [ā€˜a’, ā€˜b’, ā€˜c’, ā€˜b’] >>> li.index(ā€˜b’) # index of first occurrence 1 >>> li.count(ā€˜b’) # number of occurences 2 >>> li.remove(ā€˜b’) # remove first occurrence >>> li [ā€˜a’, ā€˜c’, ā€˜b’]
  • 49. 49 Operations on Lists Only 4 >>> li = [5, 2, 6, 8] >>> li.reverse() # reverse the list *in place* >>> li [8, 6, 2, 5] >>> li.sort() # sort the list *in place* >>> li [2, 5, 6, 8] >>> li.sort(some_function) # sort in place using user-defined comparison
  • 50. 50 Tuples vs. Lists  Lists slower but more powerful than tuples.  Lists can be modified, and they have lots of handy operations we can perform on them.  Tuples are immutable and have fewer features.  To convert between tuples and lists use the list() and tuple() functions: >>> li = list(tu) >>> tu = tuple(li)
  • 51. 51 Python Dictionary  Each key is separated from its value by a colon ( : ), the items are separated by commas, and the whole thing is enclosed in curly braces.  An empty dictionary without any items is written with just two curly braces, like this { }.  Keys are unique within a dictionary while values my not be.  The values can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
  • 52. 52 Accessing Values in a Dictionary  To access dictionary elements, we can use the familiar square brackets along with the key to obtain its value. Eg:. dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’} print dict[ā€˜Name’] print dict[ā€˜Age’]  If we attempt to access a data item with a key, which is not part of the dictionary, we will get an error.
  • 53. 53 Updating Dictionary  We can update a dictionary by adding a new entry or key-value pair, modifying an existing entry, or deleting an existing entry. Eg:. dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’} dict[ā€˜Age’] = 8 # Update existing entry dict[ā€˜School’] = ā€œDPS Schoolā€ # Add new entry
  • 54. 54 Delete Dictionary Elements  We can either remove individual dictionary elements or clear the entire contents of a dictionary.  We can also delete the entire dictionary in a single operation.  To explicitly remove an entire dictionary, just use the del statement. dict = {ā€˜Name’: ā€˜Zara’, ā€˜Age’: 7, ā€˜Class’: ā€˜First’} del dict[ā€˜Name’] # Delete an element dict.clear() # Clear the contents of the dictionary del dict # Remove the entire dictionary structure.
  • 56. 56 Function as a Concept  A function is a block of organized, reusable code that is used to perform a single, related action.  Functions provide better modularity for an application and a high degree of code reusing.  Python gives us may built-in functions like print(), etc.  We can also create our own functions. These are called user-defined functions.
  • 57. 57 Defining a Function  Function blocks begin with the keyword def followed by the function name and parentheses.  Any input parameters or arguments should be placed within these parentheses. We can also define parameters inside these parentheses.  The first statement of a function can be an optional statement – the documentation string of the function or docstring.  The code block within every function starts with a colon ( : ) and is indented.  The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
  • 58. 58 Function Structure def function_name ( parameters ): ā€œfunction_docstringā€ function_suite return [expression] Eg:. def printme (str): ā€œThis prints a passed string into this functionā€ print str return
  • 59. 59 Function Arguments  Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.  Keyword arguments are related to the function calls. When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name.  Default arguments are arguments that assume a default value if a value is not provided in the function call for that argument.  When we may need to process a function for more arguments than we specified while defining the function, we use variable-length arguments. They are also known as splat-arguments
  • 60. 60 Python files I/O: input and output with persistence
  • 61. 61 Python File Manipulation  Python provides basic functions and methods necessary to manipulate files by default.  Most of the file manipulation is done using a file object.  The various file handling methods supported are: open() close() write() read() tell()
  • 62. 62 The open() Function  Before we can read or write to a file, we have to open it.  This function creates a file object, which would be utilized to call other support methods associated with it.  Syntax: file_object = open(file_name [, access_mode][, buffering])  The commonly used access modes are ā€˜r’, ā€˜rb’, ā€˜r+’, ā€˜rb+’, ā€˜w’, ā€˜wb’, ā€˜w+’, ā€˜wb+’ and ā€˜a’.  Eg:. fo = open(ā€œfoo.txtā€, ā€œwbā€)
  • 63. 63 The close() Method  The close() method of a file object flushes any unwritten information and closes the file object, after which no more I/O can be done.  Python automatically closes a file when the reference object of a file is reassigned to another file.  Syntax: file_object.close()
  • 64. 64 The write() Method  The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.  The write() method does not add a newline character(ā€˜n’) to the end of the string.  Syntax: File_object.write(string)
  • 65. 65 The read() Method  The read() method reads a string from an open file.  Syntax: file_object.read ( [count] )  Here, the passed parameter is the number of bytes to be read from the opened file.  This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
  • 66. 66 An Example… fo = open(ā€œfoo.txtā€, ā€œr+ā€) # Open a file str = fo.read(10) print ā€œRead string is: ā€œ, str position = fo.tell() # Check current position print ā€œCurrent file position: ā€œ, position position = fo.seek(0,0) # Reposition pointer to the beginning str = fo.read(10) print ā€œAgain read string is: ā€œ, str fo.close()
  • 67. 67 Renaming and Deleting Files  Python os module provides methods that helps us perform file-processing operations, such as renaming and deleting files.  To use this module, we need to import it first and then only we can call any related functions.  Rename Method – os.rename (curr_file_name, new_file_name)  Remove Method – os.remove (file_name)  In order to import a module, we just type: import module_name
  • 68. 68 Directory Manipulation in Python  The os module has several methods that help us create, remove and change directories.  Some of the commonly used methods are:  mkdir() - os.mkdir(ā€œdir_nameā€)  chdir() - os.chdir(ā€œnew_dir)  getcwd() – os.getcwd()  rmdir() – os.rmdir(ā€˜dir_name’)
  • 69. 69Copyright Ā© 2012 Tata Consultancy Services Limited Thank You