You are on page 1of 45

Python Training

Introduction to Python
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC language, capable of
exception handling and interfacing with the Amoeba operating system. Its implementation
began in December 1989 released in 1991. Python is now open source with more set of
libraries to automate things.

Python was designed for readability with some similarities to the English language. Also it
uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.

Python relies more on indentation, using whitespace, to define scope such as:

 Scope of loops
 Functions
 Classes

Uses of Python
 Used on a server to create web applications.
 Used alongside software to create workflows.
 Used to connect to database systems and can also modify files (Read/Write)
 Used to handle big data.
 Used perform complex mathematics computations
 Used for rapid prototyping

Advantages of Python
 It can works on different platforms such as Windows, Mac, Linux, Raspberry Pi, etc
 It has simple syntax similar to the English language.
 It has syntax in such way that developers can program with few lines of code than other
programming languages.
 It runs on an interpreter system, means that code can be executed as soon as it is
developed which helps in quick prototyping.
 It can be treated in a procedural way, an object-orientated way or a functional way.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
Hello, World!

Example program in Python

 Open your Python editor (IDLE), and enter the following code:
print("Hello World")
 Save your program to a file called hello.py (python files needs to be saved in .py)
This is typically done using the editor's File > Save or similar. ...
 Run your Program by Run > Run Module

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
Variables
Variables

 Variables are used for storing data values.


 Python has no specific format for declaring a variable.
 A variable can be created, the moment a value first assign to it.
 Type of the variable even change type after they have been set
 A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
 Python allows you to assign values to multiple variables in single line

Examples of variables:
 X = 70 ; x is integer
 y = "test" ; y is string
 z = ‘ test ‘ ; z is string
 a, b, c = "Test1", " Test2", " Test3" ; assigning values to multiple variables in single line
 x = y = z = "Text" ; assigning values to same value to multiple variables in single line

Criteria for Variable names

 A variable name must start with a letter/the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

Examples of variables:

1. Valid variable names:

 var = 222
 var_1 = "test"
 var20 = "Feb"

2. Invalid variable names:

 4var = 222
 Var-N = "test"
 V ar = "Feb"

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Output Variables:
Print statement is used as output variables.
Example:
x, y, z = "Red", "Green", "Yellow"
print(x)
print(y)
print(z)

Concatenating text and variable:


In order to concatenate text and a variable ‘+’ is used
Example:
a = "Super"
print("EmbeddedFrU is " + a)
Note: In case of number ‘+’ is used as mathematical operator
Example:
a = 50
b = 20
print(a + b)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Global Variables:
Variables that are created outside the function are known as global variables.
Global variables can be used in both inside and outside the functions.
Example:
a = "Super"
def myfunc():
print("EmbeddedFrU is " + a)
myfunc()

Consider the global and local variable with the same name outside and inside
a function respectively. The variable created inside will hold local property and
can be accessed inside the function only whereas variable which is created
outside the function (i.e., globally) will hold the global property and can be
accessed anywhere inside the file. Hence in order to create global variable
inside function “Global “keyword.

Example
If the global keyword is used, the variable will hold global property:
def myfunc():
global x
x = "fantastic"

myfunc()

print("EmbeddedFrU is " + x)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
Data Types
Built-in data types
String Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Data Type Defining variables with unspecific Defining variables with specific
data types data types

str x = "Hello World" x = str("Hello World")

int x = 20 x = int(20)

float x = 20.5 x = float(20.5)

Complex x = 1j x = complex(1j)

list x = ["apple", "banana", "cherry"] x = list(("apple", "banana", "cherry"))

tuple x = ("apple", "banana", "cherry") x = tuple(("apple", "banana", "cherry"))

Range *************** x = range(6)

dict x = {"name" : "John", "age" : 36} x = dict(name="John", age=36)

set x = {"apple", "banana", "cherry"} x = set(("apple", "banana", "cherry"))

frozenset *************** x = frozenset(("apple", "banana",


"cherry"))

Bool x = True x = bool(5)

bytes x = b"Hello" x = bytes(5)

bytearray ****************** x = bytearray(5)

memoryview ****************** x = memoryview(bytes(5))

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Basic Data structures


Most basic data structure in Python is called as sequence
Each element of sequence is assigned a number - its position or index. The first
index is zero, the second index is one, and so forth.

There are 6 built-in sequence types in python which are as follows:


 Strings
 Unicode strings
 Lists
 Tuples
 Buffers
 Range

However, most commonly used sequence types are Strings, Lists and Tuples.

Operations performed with all Sequence types:


 Indexing
 Slicing
 Adding
 Multiplying
 Checking for membership

Note: Python has built-in functions for finding the length of a sequence and for finding its
largest and smallest elements.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Lists
 The list is a most versatile data type available which can be written as a list of
comma-separated values (items) between square brackets.
 Lists are like dynamic sized arrays
 An list can contain DataTypes like Integers, Strings, as well as Objects
 Lists are mutable, hence, lists can be altered even after their creation
 List can be ordered and a definite count.
 Elements in a list are indexed according to a definite sequence and the
indexing of a list is done with 0 being the first index

Example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Accessing Values in Lists:

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

Example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

Updating Lists:

Python allows updating of lists adding/modifying/deletion

Example:
list = ['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : "
print list[2]
list[2] = 2001
print "New value available at index 2 : "
print list[2]

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

append():

Used to add its argument as a single element to the end of a list and length of the list
increases by one.

Example:
list = ['embedded', 'for']
list.append('U')
print list

extend():

Iterates over its argument and adding each element to the list and extending the list.
The length of the list increases by number of elements in it’s argument.

Example:
list = ['Embedded', 'for', 1, 2, 3, 4]
list.extend('you')
print list

Deleting elements of Lists:


“del” statement is used to remove along with specific index

Example:
list1 = ['physics', 'chemistry', 1997, 2000]
del list1[2];

“Remove()”: function is used to delete the first occurrence of number mentioned in its
arguments.

Example:
lis = [2, 1, 3, 5, 3, 8]
lis.remove(3)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

List operations:

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

Indexing, Slicing, and Matrixes:


Lists are type of sequence where indexing and slicing works similar to string.

Example:

List = ['spam', 'Spam', 'SPAM!']

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

Built-in List Functions:

Sl No Results Description
1 cmp(list1, list2) 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.

Built-in List Methods:

Sl No Results 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

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Basic Operators
Operators are basically a constructs which can manipulate the value of operands

Types of Operator

Python supports the following operators.

 Arithmetic Operators
 Comparison/Relational Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic Operators:
A is initialised with 10 and B is initialised with 5

Operator Description Example


+(Addition) Adds values on either side of the a + b = 15
operator
- (Subtraction) Subtracts right hand operand from left a–b=5
hand operand
* (Multiplication) Multiplies values on either side of the a * b = 50
operator
/ (Division) Divides left hand operand by right hand a/b=2
operand
% (Modulus) Divides left hand operand by right hand a%b=0
operand and returns remainder
** (Exponent) Performs exponential (power) a**b =100000
calculation on operators

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Relational Operators:

Operator Description Example


== If the values of two operands are equal, (a == b) : Can results in
then the condition becomes true. TRUE/FALSE, with respect to
the value driven
!= If values of two operands are not equal, (a != b) : Can results in
then condition becomes true. TRUE/FALSE, with respect to
the value driven
<> If values of two operands are not equal, (a <> b) : Can results in
then condition becomes true. TRUE/FALSE. This is similar
to != operator, with respect to
the value driven
> If the value of left operand is greater (a > b) : Can results in
than the value of right operand, then TRUE/FALSE, with respect to
condition becomes true. the value driven
< If the value of left operand is less than (a < b) : Can results in
the value of right operand, then TRUE/FALSE, with respect to
condition becomes true the value driven
>= If the value of left operand is greater (a >= b) : Can results in
than or equal to the value of right TRUE/FALSE, with respect to
operand, then condition becomes true. the value driven
<= If the value of left operand is less than (a <= b) : Can results in
or equal to the value of right operand, TRUE/FALSE, with respect to
then condition becomes true. the value driven

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Assignment Operators:
A is initialised with 10 and B is initialised with 20

Operator Description Example


= Assigns values from right side operands c = a + b assigns value of a +
to left side operand b into c
+= It adds right operand to the left operand c += a is equivalent to c = c +
and assign the result to left operand a
-= It subtracts right operand from the left c -= a is equivalent to c = c –
operand and assign the result to left a
operand

*= It multiplies right operand with the left c *= a is equivalent to c = c *


operand and assign the result to left a
operand
/= It divides left operand with the right c /= a is equivalent to c = c / a
operand and assign the result to left
operand
%= It takes modulus using two operands c %= a is equivalent to c = c
and assign the result to left operand %a
**= Performs exponential (power) c **= a is equivalent to c = c
calculation on operators and assign ** a
value to the left operand

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Bitwise Operators:
A is initialised with 01010101 and B is initialised with 10101010

Operator Description Example


& (Binary AND) Operator copies a bit to the result if it (a & b) = 0000 0000
exists in both operands
| (Binary OR) It copies a bit if it exists in either (a | b) = 1111 1111
operand.
^ (Binary XOR) It copies the bit if it is set in one (a ^ b) = 1111 1111
operand but not both.

~ (Binary NOT) It is unary and has the effect of 'flipping' ~a = 1010 1010
bits.
<< (Binary Left The left operands value is moved left by a << 2 = 1010 1000
shift) the number of bits specified by the right
operand.
>> (Binary Right The left operands value is moved right a >> 2 = 0010 1010
shift) by the number of bits specified by the
right operand.

Logical Operators:
A is initialised with TRUE and B is initialised with FALSE

Operator Description Example


and (Logical AND) Operator copies a bit to the result if it (a and b) is false.
exists in both operands
or (Logical OR) It copies a bit if it exists in either (a or b) is true.
operand.
Not (Logical NOT) It copies the bit if it is set in one Not(a and b) is true
operand but not both.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Membership Operators:
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 x in y, here in results in a 1 if
the specified sequence and false x is a member of sequence y.
otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results
variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.

Identity Operators:
Identity operators compare the memory locations of two objects

Operator Description Example


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

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

String Formatting
One of the best feature of python is string format operator % which is unique to string.

Example:
print "My name is %s and weight is %d kg!" % ('ABC', 55)

Output:
My name is ABC and weight is 55 kg!

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

Other supported symbols and functionality are listed as follows:


Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
# add the octal leading zero ( '0' ) or hexadecimal
leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the
number of digits to display after the decimal
point

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Strings

Strings are the most popular types in Python. It can be created by enclosing characters
in quotes. Python treats single quotes same as double quotes. Creating strings is as
simple as assigning a value to a variable.

Example:
var = 'Hello World!'
var = "Python Programming"

Accessing the Strings using indexing:


Individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the
String,

e.g. -1 refers to the last character, -2 refers to the second last character and so on.

E m b e d d e d F r U

0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example:
String1 = "EmbeddedFrU"
print(String1)  EmbeddedFrU

Printing First character of string


print(String1[0])  E

Printing Last character of string


print(String1[-1])  U

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Accessing the Strings using slicing:


Accessing string using Slicing is done by using a Slicing operator (: ‘colon’).

E m b e d d e d F r U

0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example:
String1 = "EmbeddedFrU"
print(String1)  EmbeddedFrU

Printing First character of string


print(String1[3:7])  edded

Printing Last character of string


print(String1[3:-2])  eddedFr

Deleting/Updating from a String:


In Python, Updating or deletion of characters from a String is not allowed. This will cause an
error because item assignment or item deletion from a String is not supported.
Since Strings are immutable, elements of a String cannot be changed once it has been
assigned.

Updation of entire string:


String1 = "EmbeddedFrU”
print(String1) -> "EmbeddedFrU”

String1 = "EmbeddedFrUTeam”
print(String1) -> "EmbeddedFrUTeam”

Deleting of entire string:


Deletion of entire string is possible with the use of del keyword.

Example: del String1

Note: if it is attempted to print the string after deletion, which prone to error since String is
deleted and is unavailable to print.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Formatting of Strings:
Strings in Python can be formatted with the use of keyword format() method which is very
versatile and powerful tool for formatting of Strings.

Format method in String contains curly braces {} as placeholders which can hold arguments
according to position or keyword to specify the order.

Example:

Default order
String1 = "{} {} {}".format('Embedded', 'Fr', 'U')
print(String1) -> Embedded Fr U

Positional Formatting
String1 = "{1} {0} {2}".format('Embedded', 'Fr', 'U')
print(String1) -> Fr Embedded U

Keyword Formatting
String1 = "{u} {f} {e}".format(e = ' Embedded ', f = 'Fr', u = 'U')
print(String1) -> U Fr Embedded

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

String constants

BUILT-IN FUNCTION DESCRIPTION


string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants.
string.ascii_lowercase Concatenation of lowercase letters
string.ascii_uppercase Concatenation of uppercase letters
string.digits Digit in strings
string.hexdigits Hexadigit in strings
string.letters concatenation of the strings lowercase and uppercase
string.lowercase A string must contain lowercase letters.
string.octdigits Octadigit in a string
string.punctuation ASCII characters having punctuation characters.
string.printable String of characters which are printable
String.endswith() Returns True if a string ends with the given suffix otherwise returns
False
String.startswith() Returns True if a string starts with the given prefix otherwise returns
False
String.isdigit() Returns “True” if all characters in the string are digits, Otherwise, It
returns “False”.
String.isalpha() Returns “True” if all characters in the string are alphabets,
Otherwise, It returns “False”.
string.isdecimal() Returns true if all characters in a string are decimal.
str.format() One of the string formatting methods in Python3, which allows
multiple substitutions and value formatting.
String.index Returns the position of the first occurrence of substring in a string
string.uppercase A string must contain uppercase letters.
string.whitespace A string containing all characters that are considered whitespace.
string.swapcase() Method converts all uppercase characters to lowercase and vice
versa of the given string, and returns it
replace() Returns a copy of the string where all occurrences of a substring is
replaced with another substring.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Deprecated string functions

BUILT-IN FUNCTION DESCRIPTION


string.Isdecimal Returns true if all characters in a string are decimal
String.Isalnum Returns true if all the characters in a given string are alphanumeric.
string.Istitle Returns True if the string is a titlecased string
String.partition splits the string at the first occurrence of the separator and returns a
tuple.
String.Isidentifier Check whether a string is a valid identifier or not.
String.len Returns the length of the string.
String.rindex Returns the highest index of the substring inside the string if
substring is found.
String.Max Returns the highest alphabetical character in a string.
String.min Returns the minimum alphabetical character in a string.
String.splitlines Returns a list of lines in the string.
string.capitalize Return a word with its first character capitalized.
string.expandtabs Expand tabs in a string replacing them by one or more spaces
string.find Return the lowest indexin a sub string.
string.rfind find the highest index.
string.count Return the number of (non-overlapping) occurrences of substring
sub in string
string.lower Return a copy of s, but with upper case letters converted to lower
case.
string.split Return a list of the words of the string,If the optional second
argument sep is absent or None
string.rsplit() Return a list of the words of the string s, scanning s from the end.
rpartition() Method splits the given string into three parts
string.splitfields Return a list of the words of the string when only used with two
arguments.
string.join Concatenate a list or tuple of words with intervening occurrences of
sep.
string.strip() It return a copy of the string with both leading and trailing
characters removed
string.lstrip Return a copy of the string with leading characters removed.
string.rstrip Return a copy of the string with trailing characters removed.
string.swapcase Converts lower case letters to upper case and vice versa.
string.translate translate the characters using table
string.upper lower case letters converted to upper case.
string.ljust left-justify in a field of given width.
string.rjust Right-justify in a field of given width.
string.center() Center-justify in a field of given width.
string-zfill Pad a numeric string on the left with zero digits until the given width
is reached.
string.replace Return a copy of string s with all occurrences of substring old
replaced by new.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
Conditions
Conditions uses different conditional operators to make decision which involve TRUE or
FALSE

Conditional operators: ‘==’, ‘!=’, ‘<=’, ‘>=’, ‘>’ and ‘<’

Decision making: Based on conditional operators, decision making is done

Decision making operators:

 IF statement:
An if statement consists of a boolean expression/conditional operator followed
by one or more statements
Syntax:
if expression:
statement(s)

 if...else statements:
An if statement can be followed by an optional else statement, which executes
when the Boolean expression/conditional operator is FALSE.
Syntax:
if expression:
statement(s)
else:
statement(s)

 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
Syntax:
if expression:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Loops
A loop statement allows us to execute a statement or group of statements
multiple times

Uses of Loops:
Loops are used for statements which needs to be executed sequentially like first
statement in a function is executed first, followed by the second, and so on.

Also, in the situation when it is needed to execute a block of code several number of
times.

Different types of loops:


 while loop
Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
Syntax:
while expression:
statement(s)

 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax:
for iterating_var in sequence:
statements(s)

 nested loops
You can use one or more loop inside any another while, for or do..while loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Loop Control Statements:


Loop control statements is used to change execution path from its normal sequence.

 break statement
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
Syntax:
break

 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
Syntax:
Continue

 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.
Syntax:
Pass

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

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.

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. Also parameters can be defined 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.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

Example

def printme( str ):


"This prints a passed string into this function"
print str
return

printme("I'm first call to user defined function!") /* calling function */

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Function Arguments:
Function can be called by using the following types of formal arguments -
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.

Keyword arguments:
Keyword arguments are related to the function calls. When keyword arguments is used
in a function call, the caller identifies the arguments by the parameter name.
This allows to skip arguments or place them out of order since the Python interpreter is
able to use the keywords provided to match the values with parameters.

Keyword arguments:
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.

Variable-length arguments:
It is needed to process a function for more arguments than specified while defining the
function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.

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.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Classes
A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance
variables) and methods, accessed via dot notation.

Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows -
class ClassName:
'Optional class documentation string'
class_suite
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.
Example
Following is the example of a simple Python class -
class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

The variable empCount is a class variable whose value is shared among all instances of
this class. This can be accessed as Employee.empCount from inside the class or
outside the class.
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
Declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self-argument to the list; it is not
needed to include, when it call the methods.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Creating Instance Objects


To create instances of a class, call the class using class name and pass in whatever
arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

Accessing Attributes
Access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows -
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Functions used to access attributes:


 getattr(obj, name[, default]) − to access the attribute of object.
 hasattr(obj,name) − to check if an attribute exists or not.
 setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be
created.
 delattr(obj, name) − to delete an attribute.

Built-In Class Attributes


Python class keeps following built-in attributes and can be accessed using dot operator
like any other attribute -
__dict__ - Dictionary containing the class's namespace.
__doc__ - Class documentation string or none, if undefined.
__name__ - Class name.
__module__ - Module name in which the class is defined. This attribute is "__main__" in
interactive mode.
__bases__ - A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result -
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Destroying Objects
Python deletes unneeded objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically reclaims blocks of memory
that no longer are in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the
number of aliases that point to it changes.
__del__() destructor prints the class name of an instance that is about to be destroyed

Example:
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Class variable - A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not
used as frequently as instance variables are.

Data member - A class variable or instance variable that holds data associated with a
class and its objects.

Function overloading - The assignment of more than one behavior to a particular


function. The operation performed varies by the types of objects or arguments involved.

Instance variable - A variable that is defined inside a method and belongs only to the
current instance of a class.

Inheritance - The transfer of the characteristics of a class to other classes that are
derived from it.

Instance - An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.

Instantiation - The creation of an instance of a class.

Method - A special kind of function that is defined in a class definition.

Object - A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.

Operator overloading - The assignment of more than one function to a particular


operator

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Objects
A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods

Example:
p1 = MyClass()
print(p1.x)

Object Methods:
Objects can also contain methods. Methods in objects are functions that belong to the
object.

Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Delete Object Properties:


Delete properties on objects by using the ‘del’ keyword:
Example:
Delete the age property from the p1 object:
del p1.age

Delete Objects:
Delete objects by using the ‘del’ keyword:
Example:
Delete the age property from the p1 object:
del p1

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

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.

Accessing Values in Dictionary:


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

Following is a simple example -


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result -

dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get
an error as follows -

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result -

dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Updating Dictionary
dictionary can be updating by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example -

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result -

dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


Remove/delete individual dictionary elements or clear the entire contents of a dictionary.
Dictionary can be completely removed in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example -

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after del dict
dictionary does not exist any more -

dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note - del() method is discussed in subsequent section.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Properties of Dictionary Keys


Dictionary values have no restrictions. Dictionary can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys -

(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For
example -

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}


print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result -

dict['Name']: Manni

(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example -

dict = {['Name']: 'Zara', 'Age': 7}


print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result -

Traceback (most recent call last):


File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Built-in Dictionary Functions & Methods:

Sl No Built-in Functions 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.

Sl No Built-in Methods 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
10 dict.values() Returns list of dictionary dict's values

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Module
Module allows to organize logically in Python code. Grouping related code into a module
the code easier to understand and use. A module is a Python object with arbitrarily
named attributes that can be binded with reference.

Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.

Example
The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

Import Statement
Python source file as a module by executing an import statement in some other Python
source file. The import has the following syntax -

import module1[, module2[,... moduleN]


When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module. For example, to import the module
support.py, it is needed to put the following command at the top of the script -

# Import module support


import support

# Now defined function can call that module as follows


support.print_func("Zara")
When the above code is executed, it produces the following result -

Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple imports
occur.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

From...import Statement
This statement allows to import specific attributes from a module into the current
namespace.

Syntax:
from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib, use the following
statement -

from fib import fibonacci


This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the
importing module.

From...import * Statement
This allows to import all names from a module into the current namespace by using the
following import statement –

from modname import *

This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

Locating Modules
When you import a module, the Python interpreter searches for the module in the
following sequences -

 The current directory.

 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.

 If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The
syntax of PYTHONPATH is the same as that of the shell variable PATH.

The typical PYTHONPATH from a Windows system -

set PYTHONPATH = c:\python20\lib;


And here is a typical PYTHONPATH from a UNIX system -

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.

Each function has its own local namespace. Class methods follow the same scoping rule
as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes
that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first
use the global statement.

The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the function
Money, we assign Money a value, therefore Python assumes Money as a local variable.
However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

Example:
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print Money
AddMoney()
print Money

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names defined by
a module.

The list contains the names of all the modules, variables and functions that are defined
in a module. Following is a simple example -

# Import built-in module math


import math

content = dir(math)
print content
When the above code is executed, it produces the following result -

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',


'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the
filename from which the module was loaded.

Globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed
locally from that function.

If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function.

Reload() Function
When the module is imported into a script, the code in the top-level portion of a module
is executed only once.
Therefore, re-execute the top-level code in a module and can use the reload() function.
The reload() function imports a previously imported module again

Syntax: reload(module_name);
Example: reload(hello)

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training
Packages
A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules, subpackages, sub-subpackages, and
so on.

Consider a file Pots.py available in Phone directory. This file has following line of source
code -

def Pots():
print "I'm Pots Phone"

Similar way, another two files having different functions with the same name as above -

Phone/Isdn.py file having function Isdn()


Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory -
Phone/__init__.py

To make all functions available when function of phone imported, it is needed to put
explicit import statements in __init__.py as follows -

from Pots import Pots


from Isdn import Isdn
from G3 import G3

Once these lines added to __init__.py, all of these classes available when the Phone
package imported .

# Now import Phone Package.


import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result -

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

Programs
1.Creating a countdown timer in Python

Output:

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

2.Creating a simple calculator in Python

Output:

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru


Python Training

3.Creating “Guess the number” game in Python

Output:

Email: info.embeddedfru@gmail.com Telegram channel: https://t.me/embeddedfru

You might also like