Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python

The document provides an overview of Python programming, highlighting its runtime processing, portability, and extensive standard library. It includes a brief history of Python's development, a roadmap for learning the language, and details on setting up the programming environment. Additionally, it covers fundamental concepts such as identifiers, data types, operators, and error handling.

Uploaded by

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

Python

The document provides an overview of Python programming, highlighting its runtime processing, portability, and extensive standard library. It includes a brief history of Python's development, a roadmap for learning the language, and details on setting up the programming environment. Additionally, it covers fundamental concepts such as identifiers, data types, operators, and error handling.

Uploaded by

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

Practical Python 3

Programming
Technical Learning Services | SBU-BA

Copyright © 2014
2017 Tech Mahindra. All rights reserved.
Introduction

 Python programs are processed at runtime by the interpreter and not compiled.
 Python supports Object-Oriented programming but it can also be written in a
structured programming style too.
 Python programs are portable. Runs anywhere – OSX, Win, Linux or Unix.
 Python interpreter has an interactive mode to test and debug code
 Comes with a large standard library for most programming tasks
 Easily extended by adding new modules implemented even in C/C++
 Though a beginner-friendly language, it is very powerful and extremely popular
for Web Programming, Scientific & Numeric computing, Data Science, ML & AI
 Python is used by thousands of real-world business applications around the
world, including many large and mission critical systems >> Click for brochure

Copyright © 2017 Tech Mahindra. All rights reserved.


History

 Python was developed by Guido van Rossum in


the 80s at the National Research Institute for
Mathematics & Computer Science in Netherlands.
 Python is open-source, available under the GNU
General Public License (GPL).
 There are currently two major versions of Python
available: Python 2 and Python 3.
 Latest version is 3.7.4, released on 08 July 2019
 Official Site: https://www.python.org/
The Story of Python - https://www.youtube.com/watch?v=J0Aq44Pze-w @gvanrossum
2018 Fellow Award Speech - https://www.youtube.com/watch?v=cL_p6zrKQNU

Copyright © 2017 Tech Mahindra. All rights reserved.


Roadmap
These are only estimated timelines and may vary based on how the class is progressing

 Day 1
– Basics
– Functions
– Control Flow
– Strings
 Day 2
– Lists
– Tuples
– Dictionaries
 Day 3
– Files
– Exceptions
– Classes

Copyright © 2017 Tech Mahindra. All rights reserved.


Copyright © 2017 Tech Mahindra. All rights reserved.
Environment

 Local Environment Setup:


– Download the latest version from https://www.python.org/downloads/
– Python’s Integrated DeveLopment Environment (IDLE) is also installed

 Online Environments (no installation required):


– https://colab.research.google.com/ – Free Will be used for the demos
– https://repl.it/languages/python3 - Free
– https://www.pythonanywhere.com – Free

Copyright © 2017 Tech Mahindra. All rights reserved.


Become a software craftsman, not just a programmer

Copyright © 2017 Tech Mahindra. All rights reserved.


Copyright © 2017 Tech Mahindra. All rights reserved.
01-Basics

Copyright © 2017 Tech Mahindra. All rights reserved.


Identifiers

 Used to identify a variable, function, class, module or other object.


 Starts with a letter A to Z or a to z or an underscore (_) followed by letters,
underscores and digits (0 to 9). Special characters such as @, $, and % are
not allowed
 Python is case-sensitive
 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with underscore indicates that the identifier is private.
 Starting an identifier with two underscores indicates a strongly private identifier.
 If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name

Copyright © 2017 Tech Mahindra. All rights reserved.


Reserved Words

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Copyright © 2017 Tech Mahindra. All rights reserved.


Quiz: Which of these are valid identifiers?

a) Minimum
b) __id__
c) first name
d) last-name
e) 3rd row
f) exchange_rate_in_$
g) float
h) pass
i) _creditLimit_
j) insuredAmount_INR

Copyright © 2017 Tech Mahindra. All rights reserved.


Quiz: Which of these are valid identifiers?
Check your answers

a) Minimum 
b) __id__ 
c) first name 
d) last-name 
e) 3rd row 
f) exchange_rate_in_$ 
g) float 
h) pass 
i) _creditLimit_ 
j) insuredAmount_INR 

Copyright © 2017 Tech Mahindra. All rights reserved.


Indentation

 Python does not use braces to indicate blocks of code for class and function
definitions or flow control.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.

Observe the indentation


in this block of code

Copyright © 2017 Tech Mahindra. All rights reserved.


Multi-Line Statements

 Statements in Python typically end with a new line.


 Use the line continuation character (\) to denote that the line should continue.

 Statements contained within the [], {}, or () brackets do not need to use the line
continuation character.

Copyright © 2017 Tech Mahindra. All rights reserved.


Quotes

 Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.

Copyright © 2017 Tech Mahindra. All rights reserved.


Comments

 A hash sign (#) that is not inside a string literal begins a comment.
 All characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
 For multi-line comments, you can also use triple-quoted strings

Copyright © 2017 Tech Mahindra. All rights reserved.


Input-Output

 To display output to user:


– print()
 To read user input:
– input()
– eval(input()) To evaluate the input as a Python expression

Copyright © 2017 Tech Mahindra. All rights reserved.


Variables

 Store data for reuse


 Assign a value using = operator
 Multiple assignment is possible. e.g.,
a = b = c = 1

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

 Python has five standard data types:
– Number
– String
– List
– Tuple
– Dictionary

Copyright © 2017 Tech Mahindra. All rights reserved.


Data Type Conversions

S.No. Function Description


1 int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
3 float(x) Converts x to a floating-point number.
4 complex(real [,imag]) Creates a complex number.
5 str(x) Converts object x to a string representation.
6 repr(x) Converts object x to an expression string.
7 eval(str) Evaluates a string and returns an object.
8 tuple(s) Converts s to a tuple.
9 list(s) Converts s to a list.
10 set(s) Converts s to a set.
11 dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s) Converts s to a frozen set.
13 chr(x) Converts an integer to a character.
14 unichr(x) Converts an integer to a Unicode character.
15 ord(x) Converts a single character to its integer value.
16 hex(x) Converts an integer to a hexadecimal string.
17 oct(x) Converts an integer to an octal string.
Copyright © 2017 Tech Mahindra. All rights reserved.
Errors

 Python will point to the location where an error occurred with a ^ character
 Two common errors are
– SyntaxError means there is something wrong with the way your program is
written — punctuation that does not belong, a command where it is not
expected, or a missing parenthesis can all trigger a SyntaxError
– NameError occurs when the Python interpreter sees a word it does not
recognize.

Copyright © 2017 Tech Mahindra. All rights reserved.


Numbers

 Number data types store numeric values


 Python supports four different numerical types:
– int (signed integers)
– long (long integers, they can also be represented in octal and hexadecimal)
– float (floating point real values)
– complex (complex numbers)
 Note: Python allows you to use a lowercase l with long, but it is recommended
that you use only an uppercase L to avoid confusion with the number 1. Python
displays long integers with an uppercase L
 Beware of Python’s floating-point limitations

Copyright © 2017 Tech Mahindra. All rights reserved.


Number Type Conversion

 Python converts numbers internally in an expression containing mixed types to


a common type for evaluation.
 Sometimes, you need to coerce a number explicitly from one type to another to
satisfy the requirements of an operator or function parameter.
– Type int(x) to convert x to a plain integer.
– Type long(x) to convert x to a long integer.
– Type float(x) to convert x to a floating-point number.
– Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
– Type complex(x, y) to convert x and y to a complex number with real
part x and imaginary part y. x and y are numeric expressions

Copyright © 2017 Tech Mahindra. All rights reserved.


Math Functions https://docs.python.org/3/library/math.html

S.No. Function & Returns ( description )


1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y) – Removed in Python 3
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
x
The exponential of x: e
5 fabs(x)
The absolute value of x.
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
Copyright © 2017 Tech Mahindra. All rights reserved.
The natural logarithm of x, for x> 0
Math Functions
S.No. Function & Returns ( description )
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity
11 modf(x)
The fractional and integer parts of x in a two-item tuple.
12 pow(x, y)
The value of x**y.
13 round(x [,n])
x rounded to n digits from the decimal point.
14 sqrt(x)
Copyright © 2017 Tech Mahindra. All rights reserved.
The square root of x for x > 0
Operators

 Python language supports the following types of operators.


– Arithmetic Operators
– Comparison (Relational) Operators
– Assignment Operators
– Logical Operators
– Bitwise Operators
– Membership Operators
– Identity Operators

Copyright © 2017 Tech Mahindra. All rights reserved.


Arithmetic Operators
Operator Description Example
+ Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand
- a – b = -10
operand.
* Multiplies values on either side of the operator a * b = 200
/ Divides left hand operand by right hand operand b/a=2
% Divides left hand operand by right hand operand
b%a=0
(Modulus) and returns remainder
** Performs exponential (power) calculation on
a**b =10 to the power 20
(Exponent) operators
The division of operands where the result is the
9//2 = 4
quotient in which the digits after the decimal
// 9.0//2.0 = 4.0,
point are removed. If one of the operands is
(Floor Division) -11//3 = -4,
negative, the result is floored, i.e., rounded
-11.0//3 = -4.0
away from zero (towards negative infinity)

Copyright © 2017 Tech Mahindra. All rights reserved.


Comparison Operators
Operator Description Example
If the values of two operands are equal, then the condition
== (a == b) is not true.
becomes true.
If values of two operands are not equal, then condition
!= (a != b) is true.
becomes true.
If values of two operands are not equal, then condition
<> (a <> b) is true. Similar to != operator.
becomes true.
If the value of left operand is greater than the value of right
> (a > b) is not true.
operand, then condition becomes true.

If the value of left operand is less than the value of right


< (a < b) is true.
operand, then condition becomes true.

If the value of left operand is greater than or equal to the value


>= (a >= b) is not true.
of right operand, then condition becomes true.

If the value of left operand is less than or equal to the value of


<= (a <= b) is true.
right operand, then condition becomes true.

Copyright © 2017 Tech Mahindra. All rights reserved.


Assignment Operators
Operator Description Example
Assigns values from right side operands to left side
= c=a+b
operand
It adds right operand to the left operand and assign the
+= c += a
result to left operand
It subtracts right operand from the left operand and
-= c -= a
assign the result to left operand
It multiplies right operand with the left operand and
*= c *= a
assign the result to left operand
It divides left operand with the right operand and assign
/= c /= a
the result to left operand
It takes modulus using two operands and assign the
%= c %= a
result to left operand

Performs exponential (power) calculation on operators


**= c **= a
and assign value to the left operand
Copyright © 2017 Tech Mahindra. All rights reserved.
Logical Operators
Operator Description Example
and If both the operands are true then condition (1==1) and (2 ==2).
(Logical AND) becomes true.
or If any of the two operands are non-zero then (1==1) or (2 == 2)
(Logical OR) condition becomes true.
not Used to reverse the logical state of its not (1 ==1)
(Logical NOT) operand.

Copyright © 2017 Tech Mahindra. All rights reserved.


Bitwise Operators
Operator Description Example (if a = 60; and b = 13)
& Operator copies a bit to the result if it exists in both
(a & b) (means 0000 1100)
Binary AND operands
| It copies a bit if it exists in either operand.
(a | b) = 61 (means 0011 1101)
Binary OR
^ It copies the bit if it is set in one operand but not both.
(a ^ b) = 49 (means 0011 0001)
Binary XOR
~ (~a ) = -61 (means 1100 0011 in 2's
Binary Ones It is unary and has the effect of 'flipping' bits. complement form due to a signed
Complement binary number.
<< The left operands value is moved left by the number
a << 2 = 240 (means 1111 0000)
Left Shift of bits specified by the right operand.
>> The left operands value is moved right by the number
Right Shift of bits specified by the right operand. a >> 2 = 15 (means 0000 1111)

Copyright © 2017 Tech Mahindra. All rights reserved.


Membership Operators

 Python’s membership operators test for membership in a sequence, such as


strings, lists, or tuples
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a
specified sequence and false otherwise. member of sequence y.
not in Evaluates to true if it does not finds a variable x not in y, here not in results in a 1 if x
in the specified sequence and false otherwise. is not a member of sequence y.

Copyright © 2017 Tech Mahindra. All rights reserved.


Identity Operators

 Identity operators compare the memory locations of two objects.

Operator Description Example


is Evaluates to true if the variables on either side
x is y, here is results in 1 if id(x) equals
of the operator point to the same object and
id(y).
false otherwise.
is not Evaluates to false if the variables on either
x is not y, here is not results in 1 if
side of the operator point to the same object
id(x) is not equal to id(y).
and true otherwise.

Copyright © 2017 Tech Mahindra. All rights reserved.


Operator Precedence

 Python has well-defined rules for specifying the order in which the operators in
an expression are evaluated when the expression has several operators.
 Python evaluates expressions from left to right. While evaluating an
assignment, the right-hand side is evaluated before the left-hand side.
 Precedence rules can be overridden by explicit parentheses.
 Python uses short circuiting when evaluating expressions involving the and or
or operators. When using those operators, Python does not evaluate the
second operand unless it is necessary to resolve the result.

Copyright © 2017 Tech Mahindra. All rights reserved.


Operator Precedence
Operator Description
() Parentheses (grouping)
f(args...) Function call
x[index:index] Slicing
x[index] Subscription
x.attribute Attribute reference
** Exponentiation
~x Bitwise not
+x, -x Positive, negative
*, /, % Multiplication, division, remainder
+, - Addition, subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=,
Comparisons, membership, identity
<>, !=, ==
not x Boolean NOT
and Boolean AND
or Boolean OR
lambda Lambda expression
Copyright © 2017 Tech Mahindra. All rights reserved.
Quiz: Predict the output using Operator Precedence

 20 / 5 == 2 + 3 / 3 * 2

 2 << 2 + 2 * 2 ** 2
 If a = 2, b = 10:
Find: ((a > 0) | (a / 2 == 0 & b / 2 != 0 ))

Copyright © 2017 Tech Mahindra. All rights reserved.


02-Functions

Copyright © 2017 Tech Mahindra. All rights reserved.


Functions

 A function is a block of organized, reusable code that is used to perform a


single, related action.
 Functions provide better modularity for your application and a high degree of
code reusing.
 Python gives you many built-in functions like print(), etc. but you can also
create your own functions.
 These functions are called user-defined functions.

Copyright © 2017 Tech Mahindra. All rights reserved.


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. You can also define parameters inside these parentheses.
 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.

Copyright © 2017 Tech Mahindra. All rights reserved.


Calling a Function

 Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
 Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt.

Copyright © 2017 Tech Mahindra. All rights reserved.


Pass by reference vs value

 All parameters (arguments) in the Python language are passed by reference.

Copyright © 2017 Tech Mahindra. All rights reserved.


Function Arguments

 You can call a function by using the following types of formal arguments −
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments

Copyright © 2017 Tech Mahindra. All rights reserved.


The Anonymous Functions

 These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword
to create small anonymous functions.
 Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.

Copyright © 2017 Tech Mahindra. All rights reserved.


The return Statement

 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
 A return statement can return multiple values also.

Copyright © 2017 Tech Mahindra. All rights reserved.


Scope of Variables

 All variables in a program may not be accessible at all locations in that


program. This depends on where you have declared a variable.
 The scope of a variable determines the portion of the program where you can
access a particular identifier.
 There are two basic scopes of variables in Python:
– Global variables
– Local variables

Copyright © 2017 Tech Mahindra. All rights reserved.


Global vs. Local variables

 Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
 This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout
the program body by all functions.
 When you call a function, the variables declared inside it are brought into
scope.

Copyright © 2017 Tech Mahindra. All rights reserved.


Exercises

This works while learning to


program too!
Let’s start coding now!

Copyright © 2017 Tech Mahindra. All rights reserved.


03-Control Flow

Copyright © 2017 Tech Mahindra. All rights reserved.


Decision Making & Branching

 Python provides following types of control flow statements.


Sr.No. Statement & Description
1 if statements
An if statement consists of a boolean expression followed by one or more statements.
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).

 Python 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
Copyright © 2017 Tech Mahindra. All rights reserved.
Exercises

Time for a workout!

Copyright © 2017 Tech Mahindra. All rights reserved.


Loops

 Python provides following types of loops for looping statements.


Sr.No. Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

Copyright © 2017 Tech Mahindra. All rights reserved.


Loop Control

 Python provides following types of loop control statements.


Sr.No. Control Statement & Description
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.

 When exiting a loop, all objects that were created in that scope are destroyed
Copyright © 2017 Tech Mahindra. All rights reserved.
Exercises

Time for a workout!

Copyright © 2017 Tech Mahindra. All rights reserved.


05-Strings

Copyright © 2017 Tech Mahindra. All rights reserved.


Strings

 Strings are amongst the most popular types in Python.


 We can create them simply by enclosing characters in quotes.
 Python treats single quotes the same as double quotes.
 Creating strings is as simple as assigning a value to a variable

Copyright © 2017 Tech Mahindra. All rights reserved.


Accessing Values in Strings

 Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
 To access substrings, use the square brackets for slicing along with the index
or indices to obtain your substring

Copyright © 2017 Tech Mahindra. All rights reserved.


Updating Strings

 You can "update" an existing string by (re)assigning a variable to another


string.
 The new value can be related to its previous value or to a completely different
string altogether.

Copyright © 2017 Tech Mahindra. All rights reserved.


Special String Operators
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
Repetition - Creates new strings, concatenating multiple
* a*2 will give -HelloHello
copies of the same string
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
Membership - Returns true if a character exists in the given
in H in a will give 1
string
Membership - Returns true if a character does not exist in the
not in M not in a will give 1
given string
Raw String - Suppresses Escape characters. precedes the print r'\n' prints \n and print
r/R
quotation marks.. R'\n'prints \n
% Format - Performs String formatting See next slide
Copyright © 2017 Tech Mahindra. All rights reserved.
String Formatting Operator
Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E


Copyright © 2017 Tech Mahindra. All rights reserved.
Built-in String Methods
capitalize() format_map() isprintable() partition() splitlines()
casefold() index() isspace() replace() startswith()
center() isalnum() istitle() rfind() strip()
count() isalpha() isupper() rindex() swapcase()
encode() isdecimal() join() rjust() title()
endswith() isdigit() ljust() rpartition() translate()
expandtabs() isidentifier() lower() rsplit() upper()
find() islower() lstrip() rstrip() zfill()
format() isnumeric() maketrans() split()

Copyright © 2017 Tech Mahindra. All rights reserved.


Exercises

Copyright © 2017 Tech Mahindra. All rights reserved.


04-Lists

Copyright © 2017 Tech Mahindra. All rights reserved.


Lists

 The list is a most versatile datatype available in Python which can be written as
a list of comma-separated values (items) between square brackets.
 Important thing about a list is that items in a list need not be of the same type.
 Creating a list is as simple as putting different comma-separated values
between square brackets

Copyright © 2017 Tech Mahindra. All rights reserved.


Accessing Values in Lists

 To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index

Copyright © 2017 Tech Mahindra. All rights reserved.


Updating Lists

 You can update single or multiple elements of lists by giving the slice on the
left-hand side of the assignment operator
 You can add to elements in a list with the append() method

Copyright © 2017 Tech Mahindra. All rights reserved.


Delete List Elements

 To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do
not know.

Copyright © 2017 Tech Mahindra. All rights reserved.


Basic List Operations

 Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not a
string.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration

Copyright © 2017 Tech Mahindra. All rights reserved.


Indexing & Slicing

 Because lists are sequences, indexing and slicing work the same way for lists
as they do for strings.

Assuming following input: L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description


L[2] SPAM! Offsets start at zero
L[-2] Spam Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Copyright © 2017 Tech Mahindra. All rights reserved.


Built-in List Functions & Methods

 Python includes the following list functions:


S.No. Function with Description
1 cmp(list1, list2) – deprecated with Python 3
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
Copyright © 2017 Tech Mahindra. All rights reserved.
Built-in List Functions & Methods

 Python includes the following list methods:


S.No. Methods Description
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort([func]) Sorts objects of list, use compare func if given

Copyright © 2017 Tech Mahindra. All rights reserved.


06-Tuples

Copyright © 2017 Tech Mahindra. All rights reserved.


Tuples

 A tuple is a sequence of immutable Python objects.


 Tuples are sequences, just like lists. The differences are:
– the tuples cannot be changed unlike lists
– tuples use parentheses, whereas lists use square brackets.
 Creating a tuple is as simple as putting different comma-separated values.
 Optionally you can put these comma-separated values between parentheses
also

Copyright © 2017 Tech Mahindra. All rights reserved.


Accessing Values in Tuples

 To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index.

Copyright © 2017 Tech Mahindra. All rights reserved.


Updating Tuples

 Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new
tuples.

Copyright © 2017 Tech Mahindra. All rights reserved.


Delete Tuple Elements

 Removing individual tuple elements is not possible.


 To explicitly remove an entire tuple, just use the del statement.

Copyright © 2017 Tech Mahindra. All rights reserved.


Basic Tuples Operations

 Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple, not
a string.

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration

Copyright © 2017 Tech Mahindra. All rights reserved.


Indexing, Slicing, and Matrixes

Assuming following input - L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Copyright © 2017 Tech Mahindra. All rights reserved.


Built-in Tuple Functions

Sr.No. Function with Description


cmp(tuple1, tuple2)
1
Compares elements of both tuples.
len(tuple)
2
Gives the total length of the tuple.
max(tuple)
3
Returns item from the tuple with max value.
min(tuple)
4
Returns item from the tuple with min value.
tuple(seq)
5
Converts a list into tuple.

Copyright © 2017 Tech Mahindra. All rights reserved.


07-Dictionaries

Copyright © 2017 Tech Mahindra. All rights reserved.


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 may not be.
 The values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples

Copyright © 2017 Tech Mahindra. All rights reserved.


Accessing Values in Dictionary

 To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value.

Copyright © 2017 Tech Mahindra. All rights reserved.


Updating Dictionary

 You can update a dictionary by adding a new entry or a key-value pair,


modifying an existing entry, or deleting an existing entry

Copyright © 2017 Tech Mahindra. All rights reserved.


Delete Dictionary Elements

 You can either remove individual dictionary elements or clear the entire
contents of a dictionary.
 You can also delete entire dictionary in a single operation.

Copyright © 2017 Tech Mahindra. All rights reserved.


Built-in Functions
Sr.No. Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.

Copyright © 2017 Tech Mahindra. All rights reserved.


Sr.No. Methods with Description
1 dict.clear() Removes all elements of dictionary dict
2 dict.copy() Returns a shallow copy of dictionary dict
3 dict.fromkeys() Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None) For key key, returns value or default if key not in dictionary
5 dict.has_key(key) Returns true if key in dictionary dict, false otherwise
6 dict.items() Returns a list of dict's (key, value) tuple pairs
7 dict.keys() Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict

Copyright © 2017 Tech Mahindra. All rights reserved.


Files

 Open files using open() method


 Close files using close() method
 Read using read() method
 Write using write() method

Copyright © 2017 Tech Mahindra. All rights reserved.


Exceptions

 If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block.
 After the try: block, include an except: statement
 You can use a finally: block along with a try: block. The finally block is a place
to put any code that must execute, whether the try-block raised an exception or
not

Copyright © 2017 Tech Mahindra. All rights reserved.


Creating Classes

 The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon
 The class has a documentation string, which can be accessed via
ClassName.__doc__.
 The class_suite consists of all the component statements defining class
members, data attributes and functions.
 The variable empCount is a class variable whose value is shared among all
instances of a this class. This can be accessed outside the class also.
 The first method __init__() is a constructor or initialization method that Python
calls when you create a new instance of this class.
 You declare other class methods like normal functions with the exception that
the first argument to each method is self.
Copyright © 2017 Tech Mahindra. All rights reserved.

You might also like