Python
Python
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
Day 1
– Basics
– Functions
– Control Flow
– Strings
Day 2
– Lists
– Tuples
– Dictionaries
Day 3
– Files
– Exceptions
– Classes
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
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
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.
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character.
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.
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
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.
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.
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 ))
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.
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.
You can call a function by using the following types of formal arguments −
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
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.
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.
When exiting a loop, all objects that were created in that scope are destroyed
Copyright © 2017 Tech Mahindra. All rights reserved.
Exercises
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
%c character
%o octal integer
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
To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index
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
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.
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.
Because lists are sequences, indexing and slicing work the same way for lists
as they do for strings.
To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index.
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.
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.
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
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value.
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.
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
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.