0% found this document useful (0 votes)
3 views152 pages

Python Doc (2)

Uploaded by

deepaansh kapoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views152 pages

Python Doc (2)

Uploaded by

deepaansh kapoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 152

List of content:

 Introduction to Python
 Python Print Statement
 Python Variable
 Python Data Type
 Python Operators
 Python If elif else
 Python For Loop
 Python While Loop
 Python break, continue
 Python String
 Python Lists
 Python Dictionary
 Python Tuples
 Python Sets
 Python User define function
 Python Classes
 Python Built-in Functions
Introduction to Python
 Python is an open source, object-oriented, high-level powerful programming language.
 Developed by Guido van Rossum in the early 1990s. Named after Monty Python
 Python runs on many Unix variants, on the Mac, and on Windows 2000 and later.
 Available for download from http://www.python.org.

Features of Python

 Open source: Python is publicly available open source software, any one can use source
code that doesn't cost anything.
 Easy-to-learn: Popular (scripting/extension) language, clear and easy syntax, no type
declarations, automatic memory management, high-level data types and operations, design to
read (more English like syntax) and write (shorter code compared to C, C++, and Java) fast.
 High-level Language:
High-level language (closer to human) refers to the higher level of concept from machine
language (for example assembly languages). Python is an example of a high-level language
like C, C++, Perl, and Java with low-level optimization.
 Portable:
High level languages are portable, which means they are able to run across all major
hardware and software platforms with few or no change in source code. Python is portable
and can be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS,
AS/400 and many more.
 Object-Oriented: Python is a full-featured object-oriented programming language, with
features such as classes, inheritance, objects, and overloading.
 Python is Interactive :
Python has an interactive console where you get a Python prompt (command line) and
interact with the interpreter directly to write and test your programs. This is useful for
mathematical programming.
 Interpreted: Python programs are interpreted, takes source code as input, and then compiles
(to portable byte-code) each statement and executes it immediately. No need to compiling or
linking
 Extendable: Python is often referred to as a "glue" language, meaning that it is capable to
work in mixed-language environment. The Python interpreter is easily extended and can add
a new built-in function or modules written in C/C++/Java code.
 The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support
for this end-of-life release. Python 3.0 was released in 2008. The 2.x release will see no new
major releases after that. 3.x is under active development and has already seen over several
years of stable releases, including version 3.3 in 2012, 3.4 in 2014, and 3.5 in 2015.
 If you're new to programming or an experienced developer, it's easy to learn and use Python
3. Python 3 represents the future of the language as all development has stopped with Python
2.x, save for security and bug fixes.

Comments in Python:

A comment begins with a hash character(#) which is not a part of the string literal and ends at the end
of the physical line. All characters after the # character up to the end of the line are part of the
comment and the Python interpreter ignores them. See the following example. It should be noted that
Python has no multi-lines or block comments facility.

Joining two lines:


When you want to write a long code in a single line you can break the logical line in two or more
physical lines using backslash character (\). Therefore when a physical line ends with a backslash
characters (\) and not a part of a string literal or comment then it can join another physical line. See
the following example
Multiple Statements on a Single Line:
You can write two separate statements into a single line using a semicolon (;) character
between two line.

Indentation:
Python uses whitespace (spaces and tabs) to define program blocks whereas other
languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow
control. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be the indented same amount. In the following program,
the block statements have no indentation.

This is a program with single space indentation.


This is a program with single tab indentation.

Python Reserve words:


The following identifiers are used as reserved words of the language, and cannot be used as
ordinary identifiers.

False class finally is return

None continue for lambda try

True def from nonlocal while


and del global not with

as el if or yield

assert else import pass

break except in raise

Python print() function

The print statement has been replaced with a print() function, with keyword arguments to replace most
of the special syntax of the old print statement.
The print statement can be used in the following ways:

 print("Good Morning")
 print("Good", <Variable Containing the String>)
 print("Good" + <Variable Containing the String>)
 print("Good %s" % <variable containing the string>)
In Python, single, double and triple quotes are used to denote a string. Most use single quotes when
declaring a single character. Double quotes when declaring a line and triple quotes when declaring a
paragraph/multiple lines.
print('Hello')
print("Python is very simple language")
print("""Python is very popular language.
It is also friendly language.""")
Variable Use:
Strings can be assigned to variable say string1 and string2 which can called when using the print
statement.

str1 = 'Wel'
print(str1,'come')
str1 = 'Welcome'
str2 = 'Python'
print(str1, str2)

String Concatenation:
String concatenation is the "addition" of two strings. Observe that while concatenating there will be no
space between the strings.
str1 = 'Python'
str2 = ':'
print('Welcome' + str1 + str2)
Using as String:
%s is used to refer to a variable which contains a string.
str1 = 'Python'
print("Welcome %s" % str1)
Using other data types:
Similarly, when using other data types

 %d -> Integer
 %e -> exponential
 %f -> Float
 %o -> Octal
 %x -> Hexadecimal
print("Exponential equivalent of the number = %e" %15)
print("Hexadecimal equivalent of the number = %x" %15)
Using multiple variables:
When referring to multiple variables parenthesis is used.
str1 = 'World'
str2 = ':'
print("Python %s %s" %(str1,str2))
\n is used for Line Break
print("Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\
nSaturday")
Example-3:
Any word print multiple times.
print('-w3r'*5)
\t is used for tab.
print("""
Language:
\t1 Python
\t2 Java\n\t3 JavaScript
""")

Variable and Value


 A variable is a memory location where a programmer can store a value. Example : roll_no,
amount, name etc.
 Value is either string, numeric etc. Example : "Sara", 120, 25.36
 Variables are created when first assigned.
 Variables must be assigned before being referenced.
 The value stored in a variable can be accessed or updated later.
 No declaration required
 The type (string, int, float etc.) of the variable is determined by Python
 The interpreter allocates memory on the basis of the data type of a variable.

Python Variable Name Rules

 Must begin with a letter (a - z, A - B) or underscore (_)


 Other characters can be letters, numbers or _
 Case Sensitive
 Can be any (reasonable) length
 There are some reserved words which you cannot use as a variable name because Python
uses them for other things.
>>> Item_name = "Computer" #A String
>>> Item_qty = 10 #An Integer
>>> Item_value = 1000.23 #A floating point
>>> print(Item_name)
Computer
>>> print(Item_qty)
10
>>> print(Item_value)
1000.23

Multiple Assignment

The basic assignment statement works for a single variable and a single expression. You can also
assign a single value to more than one variables simultaneously.
var1=var2=var3...varn= = <expr>
>>> x = y = z = 1

Swap variables

Python swap values in a single line and this applies to all objects in python.
Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10
>>> y = 20
>>> print(x)
10
>>> print(y)
20
>>> x, y = y, x
>>> print(x)
20
>>> print(y)
10
>>>

Local and global variables in Python

In Python, variables that are only referenced inside a function are implicitly global. If a variable is
assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly
declared as global.
Example:

var1 = "Python"
def func1():

var1 = "PHP"
print("In side func1() var1 = ",var1)

def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Output:
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword :
Example:

def func1():
global var1
var1 = "PHP"
print("In side func1() var1 = ",var1)

def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Output:
In side func1() var1 = PHP
In side func2() var1 = PHP

Python Data Type


Type represents the kind of value and determines how the value can be used. All data values in
Python are encapsulated in relevant object classes. Everything in Python is an object and every
object has an identity, a type, and a value. Like another object-oriented language such as Java or C+
+, there are several data types which are built into Python. Extension modules which are written in C,
Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects
can be changed. Objects whose value can be changed are called mutable and objects whose value is
unchangeable (once they are created) are called immutable. Here are the details of Python data types

Numbers

Numbers are created by numeric literals. Numeric objects are immutable, which means when an
object is created its value cannot be changed.
Python has three distinct numeric types: integers, floating point numbers, and complex numbers.
Integers represent negative and positive integers without fractional parts whereas floating point
numbers represents negative and positive numbers with fractional parts. In addition, Booleans are a
subtype of plain integers. See the following statements in Python shell.

Floats and Integers


>>> x = 8
>>> y = 7
>>> x+y
>>> x-y
>>> x/y
>>> x*y
Output:
15
1
1.1428571428571428
56
Exponent
>>> 4**3
>>> 3**4
Output:
64
81
inter division
>>> 12/3
>>> 64//4
>>> 15//3
Output:
4.0
16
5
Remainder
>>> 15 % 4
Output:
3
Mathematically, a complex number (generally used in engineering) is a number of the form A+Bi
where i is the imaginary number. Complex numbers have a real and imaginary part. Python supports
complex numbers either by specifying the number in (real + imagJ) or (real + imagj) form or using a
built-in method complex(x, y). See the following statements in Python Shell.
Self-assignment
>>> count = 0
>>> count +=2
>>> count
Output:
2
>>> count -=2
>>> count
Output:
0
>>> count +=2
>>> count *=4
>>> count

Output:

8
>>> count **=4

>>> count

Output:

4096
>>> count /=4

>>> count

Output:

1024.0
>>> count//=4

>>> count

Output:

256.0
>>> 15.0 //2

Output:

7.0
Order of operations

>>> (3+12) / 3

>>> 15 / (3 + 2)

Output:

5.0
3.0
Boolean (bool)

The simplest build-in type in Python is the bool type, it represents the truth values False and True.
See the following statements in Python shell.

Strings
In Python, a string type object is a sequence (left-to- right order) of characters. Strings start and end
with single or double quotes Python strings are immutable. Single and double quoted strings are
same and you can use a single quote within a string when it is surrounded by double quote and vice
versa. Declaring a string is simple, see the following statements.
Special characters in strings
The backslash (\) character is used to introduce a special character. See the following table.
Escape sequence Meaning

\n Newline

\t Horizontal Tab

\\ Backslash

\' Single Quote

\" Double Quote

See the following statements on special characters.

String indices and accessing string elements


Strings are arrays of characters and elements of an array can be accessed using indexing.
Indices start with 0 from left side and -1 when starting from right side.
string1 ="PYTHON TUTORIAL"
Character P Y T H O N T U T O R I A L

Index (from 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
left)

Index (from -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


right)

See the following statements to access single character from various positions.
Strings are immutable

Strings are immutable character sets. Once a string is generated, you cannot change any
character within the string. See the following statements.

'in' operator in Strings

The 'in' operator is used to check whether a character or a substring is present in a string or
not. The expression returns a Boolean value. See the following statements.
String Slicing
To cut a substring from a string is called string slicing. Here two indices are used separated
by a colon (:). A slice 3:7 means indices characters of 3rd, 4th, 5th and 6th positions. The
second integer index i.e. 7 is not included. You can use negative indices for slicing. See the
following statements.

Conversion
>>> float("4.5")
>>> int("25")
>>> int(5.625)
>>> float(6)
>>> int(True)
>>> float(False)
>>> str(True)
>>> bool(0)
>>> bool('Hello world')
>>> bool(223.5)
Output:
4.5
25
5
6.0
1
0.0
'True'
False
True
True
Tuples

A tuple is a container which holds a series of comma-separated values (items or elements) between
parentheses. Tuples are immutable (i.e. you cannot change its content once created) and can hold
mix data types.

Creating Tuples

To create an empty tuple or create a tuple with single element use the following commands.
Elements of a tuple are indexed like other sequences. The tuple indices start at 0. See the
following statements.

Tuples are immutable which means it's items values are unchangeable. See the following
statements.
Slicing a tuple
Like other sequences like strings, tuples can be sliced. Slicing a tuple creates a new tuple
but it does not change the original tuple.

Using + and * operators in Tuples


Use + operator to create a new tuple that is a concatenation of tuples and use * operator to
repeat a tuple. See the following statements.
Lists
A list is a container which holds comma-separated values (items or elements) between
square brackets where Items or elements need not all have the same type.

Creating Lists

A list without any element is called an empty list. See the following statements.
List indices
List indices work the same way as string indices, list indices start at 0. If an index has a
positive value it counts from the beginning and similarly it counts backward if the index has a
negative value. As positive integers are used to index from the left end and negative integers
are used to index from the right end, so every item of a list gives two alternatives indices. Let
create a list called color_list with four items.

color_list=["RED", "Blue", "Green", "Black"].

Item RED Blue Green Black

Index (from left) 0 1 2 3

Index (from right) -4 -3 -2 -1

If you give any index value which is out of range then interpreter creates an error message.
See the following statements.
List Slices
Lists can be sliced like strings and other sequences. The syntax of list slices is easy :
sliced_list = List_Name[startIndex:endIndex]

This refers to the items of a list starting at index startIndex and stopping just before index
endIndex. The default values for list are 0 (startIndex) and the end (endIndex) of the list. If
you omit both indices, the slice makes a copy of the original list. See the following
statements.

Lists are Mutable


Items in the list are mutable i.e. after creating a list you can change any item in the list. See
the following statements.
Using + and * operators in List
Use + operator to create a new list that is a concatenation of two lists and use * operator to
repeat a list. See the following statements.

Sets
A set is an unordered collection of unique elements. Basic uses include dealing with set theory (which
support mathematical operations like union, intersection, difference, and symmetric difference) or
eliminating duplicate entries. See the following statements.
Python Operators

Operators and Operands

In computer programming languages operators are special symbols which represent


computations, conditional matching etc. The values the operator uses are called operands.
c = a + b
Here a and b are called operands and '+' is an operator
Python supports following operators.
Contents:

 Operators commands
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Assignment Operators
 Bitwise Operator
 Conditional Operators
Operator: Commands
Module of functions that provide the functionality of operators.
from operator import add, sub, mul, truediv, floordiv, mod, pow,
neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, not_
from operator import itemgetter, attrgetter, methodcaller
import operator as op
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' :
op.or_})
last_el = op.methodcaller('pop')(<list>)

Python Arithmetic Operators

Operator Name Example Result

+ Addition x+y Sum of x and y.

- Subtraction x-y Difference of x and y.

* Multiplication x*y Product of x and y.

/ Division x/y Quotient of x and y.

% Modulus x%y Remainder of x divided by y.


** Exponent x**y x**y will give x to the power y

// Floor Division x/ y The division of operands where the result is the quotient in which
the digits after the decimal point are removed.

See the following statements in Python Shell.

Python Comparison Operators


Operator Name Example Result

== Equal x==y True if x is exactly equal to y.

!= Not equal x!=y True if x is exactly not equal to y.

> Greater than x>y True if x (left-hand argument) is greater than y


(right-hand argument).

< Less than x<y True if x (left-hand argument) is less than y


(right-hand argument).

>= Greater than or x>=y True if x (left-hand argument) is greater than or


equal to equal to y (left-hand argument).

<= Less than or x<=y True if x (left-hand argument) is less than or


equal to equal to y (right-hand argument).

See the following statements in Python Shell.

Python Logical Operators

Operator Example Result

and (x and y) is True if both x and y are true.

or (x or y) is True if either x or y is true.

not (x not y) If a condition is true then Logical not operator will make false.

See the following statements in Python Shell.


Python Assignment Operators

Operator Shorthand Expression Description

+= x+=y x=x+y Adds 2 numbers and assigns the result to left operand.

-= x-= y x = x -y Subtracts 2 numbers and assigns the result to left operand.

*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.

/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.

%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result
to left operand.

**= x**=y x = x**y Performs exponential (power) calculation on operators and


assign value to the equivalent to left operand.

//= x//=y x = x//y Performs floor division on operators and assign value to
the left operand.

See the following statements in Python Shell.


Python Bitwise Operators

Operator Shorthand Expression Description

& And x&y Bits that are set in both x and y are set.

| Or x|y Bits that are set in either x or y are set.

^ Xor x^y Bits that are set in x or y but not both are set.

~ Not ~x Bits that are set in x are not set, and vice versa.

<< Shift left x <<y Shift the bits of x, y steps to the left

>> Shift right x >>y Shift the bits of x, y steps to the right.
# Each step means 'multiply by two'
* Each step means 'divide by two'

Conditional Operators

Conditional expressions or ternary operator have the lowest priority of all Python operations. The
expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value
is returned; otherwise, y is evaluated and its value is returned.

Python if elif else

if..elif..else
The if-elif-else statement is used to conditionally execute a statement or a block of
statements. Conditions can be true or false, execute one thing when the condition is true, something
else when the condition is false.

Contents:

 if statement

 if .. else statement

 if .. elif .. else statement

 Nested if .. else

 Use the and operator in an if statement

 Use the in operator in an if statement

 Write an if-else in a single line of code

 Define a negative if

if statement

The Python if statement is same as it is with other programming languages. It executes a set of
statements conditionally, based on the value of a logical expression.
Here is the general form of a one way if statement.
Syntax:

if expression :
statement_1
statement_2
....
In the above case, expression specifies the conditions which are based on Boolean
expression. When a Boolean expression is evaluated it produces either a value of true or
false. If the expression evaluates true the same amount of indented statement(s) following if
will be executed. This group of the statement(s) is called a block.

if .. else statement

In Python if .. else statement, if has two blocks, one following the expression and other following the
else clause. Here is the syntax.

Syntax:

if expression :
statement_1
statement_2
....
else :
statement_3
statement_4
....
In the above case if the expression evaluates to true the same amount of indented statements(s)
following if will be executed and if the expression evaluates to false the same amount of indented
statements(s) following else will be executed. See the following example. The program will print the
second print statement as the value of a is 10.

a=10
if(a>10):
print("Value of a is greater than 10")
else :
print("Value of a is 10")
Output:
Value of a is 10
Flowchart:
if .. elif .. else statement

Sometimes a situation arises when there are several conditions. To handle the situation Python allows
adding any number of elif clause after an if and before an else clause. Here is the syntax.

Syntax:

if expression1 :
statement_1
statement_2
....
elif expression2 :
statement_3
statement_4
....
elif expression3 :
statement_5
statement_6
....................
else :
statement_7
statement_8
In the above case Python evaluates each expression (i.e. the condition) one by one and if a true
condition is found the statement(s) block under that expression will be executed. If no true condition is
found the statement(s) block under else will be executed. In the following example, we have applied if,
series of elif and else to get the type of a variable.
var1 = 1+2j
if (type(var1) == int):
print("Type of the variable is Integer")
elif (type(var1) == float):
print("Type of the variable is Float")
elif (type(var1) == complex):
print("Type of the variable is Complex")
elif (type(var1) == bool):
print("Type of the variable is Bool")
elif (type(var1) == str):
print("Type of the variable is String")
elif (type(var1) == tuple):
print("Type of the variable is Tuple")
elif (type(var1) == dict):
print("Type of the variable is Dictionaries")
elif (type(var1) == list):
print("Type of the variable is List")
else:
print("Type of the variable is Unknown")
Output:
Type of the variable is Complex
Flowchart:
Nested if .. else statement

In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to true or
not. If a true condition is found the statement(s) block associated with the condition executes
otherwise it goes to next condition. Here is the syntax :

Syntax:

if expression1 :
if expression2 :
statement_3
statement_4
....
else :
statement_5
statement_6
....
else :
statement_7
statement_8
In the above syntax expression1 is checked first, if it evaluates to true then the program control goes
to next if - else part otherwise it goes to the last else statement and executes statement_7,
statement_8 etc.. Within the if - else if expression2 evaluates true then statement_3, statement_4 will
execute otherwise statement_5, statement_6 will execute. See the following example.

age = 38

if (age >= 11):

print ("You are eligible to see the Football match.")

if (age <= 20 or age >= 60):

print("Ticket price is $12")

else:

print("Tic kit price is $20")

else:

print ("You're not eligible to buy a ticket.")

Output :
You are eligible to see the Football match.
Tic kit price is $20
In the above example age is set to 38, therefore the first expression (age >= 11) evaluates to True
and the associated print statement prints the string "You are eligible to see the Football match". There
after program control goes to next if statement and the condition ( 38 is outside <=20 or >=60) is
matched and prints "Tic kit price is $12".

Flowchart:

Use the and operator in an if statement

#create two boolean objects


x = False
y = True
#The validation will be True only if all the expressions generate a value
True
if x and y:
print('Both x and y are True')
else:
print('x is False or y is False or both x and y are False')
Output:
x is False or y is False or both x and y are False

Use the in operator in an if statement


#create a string
s = 'jQuery'
#create a list
l = ['JavaScript', 'jQuery', 'ZinoUI']

# in operator is used to replace various expressions that use the or


operator
if s in l:
print(s + ' Tutorial')

#Alternate if statement with or operator

if s == 'JavaScript' or s == 'jQuery' or s == 'ZinoUI':


print(s + ' Tutorial')
Copy
Output:
jQuery Tutorial
jQuery Tutorial

Write an if-else in a single line of code


#create a integer
n = 150
print(n)

#if n is greater than 500, n is multiplied by 7, otherwise n is divided by


7
result = n * 7 if n > 500 else n / 7
print(result)
Copy
Output:
150
21.428571428571427

Define a negative if
If a condition is true the not operator is used to reverse the logical state, then logical not operator will
make it false.

#create a integer
x = 20
print(x)
#uses the not operator to reverse the result of the logical expression
if not x == 50:
print('the value of x different from 50')
else:
print('the value of x is equal to 50')

Output:
20
the value of x different from 50

Python for loop

for loop

Like most other languages, Python has for loops, but it differs a bit from other like C or Pascal. In
Python for loop is used to iterate over the items of any sequence including the Python list, string, tuple
etc. The for loop is also used to access elements from a container (for example list, string, tuple)
using built-in function range().

Syntax:
for variable_name in sequence :
statement_1
statement_2
....
Parameter:

Name Description

variable_name It indicates target variable which will set a new value for each iteration of
the loop.

sequence A sequence of values that will be assigned to the target variable


variable_name. Values are provided using a list or a string or from the built-
in function range().

statement_1, Block of program statements.


statement_2 .....

Example: Python for loop


>>> #The list has four elements, indices start at 0 and end at 3
>>> color_list = ["Red", "Blue", "Green", "Black"]
>>> for c in color_list:
print(c)

Red
Blue
Green
Black
>>>
In the above example color_list is a sequence contains a list of various color names. When the for
loop executed the first item (i.e. Red) is assigned to the variable c. After this, the print statement will
execute and the process will continue until we reach the end of the list.

Python for loop and range() function

The range() function returns a list of consecutive integers. The function has one, two or three
parameters where last two parameters are optional. It is widely used in for loops. Here is the syntax.

range(a)
range(a,b)
range(a,b,c)
range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1.
Syntax:
for <variable> in range(<number>):
Example:
>>> for a in range(4):
print(a)

0
1
2
3
>>>
range(a,b): Generates a sequence of numbers from a to b excluding b, incrementing by 1.
Syntax:
for "variable" in range("start_number", "end_number"):
Example:
>>> for a in range(2,7):
print(a)
2
3
4
5
6
>>>
range(a,b,c): Generates a sequence of numbers from a to b excluding b, incrementing by c.
Example:
>>> for a in range(2,19,5):
print(a)
2
7
12
17
>>>

Python for loop: Iterating over tuple, list, dictionary


Example: Iterating over tuple
The following example counts the number of even and odd numbers from a series of
numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if x % 2:
count_odd+=1
else:
count_even+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Output:
Number of even numbers:4
Number of odd numbers: 5
In the above example a tuple named numbers is declared which holds the integers 1 to 9. The best
way to check if a given number is even or odd is to use the modulus operator (%). The operator
returns the remainder when dividing two numbers. Modulus of 8 % 2 returns 0 as 8 is divided by 2,
therefore 8 is even and modulus of 5 % 2 returns 1 therefore 5 is odd.

The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item in
the tuple and the process will continue until we rich the end of the tuple. When it is true count_even
increase by one otherwise count_odd is increased by one. Finally, we print the number of even and
odd numbers through print statements.

Example: Iterating over list

In the following example for loop iterates through the list "datalist" and prints each item and its
corresponding Python type.

datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],

{"class":'V', "section":'A'}]

for item in datalist:

print ("Type of ",item, " is ", type(item))


Output:

Type of 1452 is <class 'int'>


Type of 11.23 is <class 'float'>
Type of (1+2j) is <class 'complex'>
Type of True is <class 'bool'>
Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
Type of [5, 12] is <class 'list'>
Type of {'section': 'A', 'class': 'V'} is <class 'dict'>
Example: Iterating over dictionary

In the following example for loop iterates through the dictionary "color" through its keys and prints
each key.

>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}

>>> for key in color:

print(key)

c2

c1

c3

>>>

Following for loop iterates through its values :


>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}

>>> for value in color.values():

print(value)

Green

Red

Orange

>>>

You can attach an optional else clause with for statement, in this case, syntax
will be -
for variable_name in sequence :
statement_1
statement_2
....
else :
statement_3
statement_4
....
The else clause is only executed after completing the for loop. If a break
statement executes in first program block and terminates the loop then the
else clause does not execute.

Python while loop

While loop

Loops are used to repeatedly execute a block of program statements. The basic loop structure in
Python is while loop. Here is the syntax.

Syntax:

while (expression) :
statement_1
statement_2
....

The while loop runs as long as the expression (condition) evaluates to True and execute the program
block. The condition is checked every time at the beginning of the loop and the first time when the
expression evaluates to False, the loop stops without executing any remaining statement(s). The
following example prints the digits 0 to 4 as we set the condition x < 5.

x = 0;

while (x < 5):

print(x)

x += 1

Output:

0
1
2
3
4
One thing we should remember that a while loop tests its condition before the body of the loop (block
of program statements) is executed. If the initial test returns false, the body is not executed at all. For
example the following code never prints out anything since before executing the condition evaluates
to false.

x = 10;
while (x < 5):

print(x)

x += 1

Flowchart:

The following while loop is an infinite loop, using True as the condition:

x = 10;

while (True):

print(x)

x += 1

Flowchart:
Python: while and else statement

There is a structural similarity between while and else statement. Both have a block of statement(s)
which is only executed when the condition is true. The difference is that block belongs to if statement
executes once whereas block belongs to while statement executes repeatedly.

You can attach an optional else clause with while statement, in this case, syntax will be -

while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
......

The while loop repeatedly tests the expression (condition) and, if it is true, executes the first block of
program statements. The else clause is only executed when the condition is false it may be the first
time it is tested and will not execute if the loop breaks, or if an exception is raised. If a break
statement executes in first program block and terminates the loop then the else clause does not
execute. In the following example, while loop calculates the sum of the integers from 0 to 9 and after
completing the loop, else statement executes.

x = 0;

s = 0

while (x < 10):

s = s + x

x = x + 1

else :

print('The sum of first 9 integers : ',s)

Output:

The sum of first 9 integers: 45


Flowchart:
Example: while loop with if-else and break statement

x = 1;

s = 0

while (x < 10):

s = s + x

x = x + 1

if (x == 5):

break

else :

print('The sum of first 9 integers : ',s)

print('The sum of ',x,' numbers is :',s)

Output:

The sum of 5 numbers is : 10


In the above example the loop is terminated when x becomes 5. Here we use break statement to
terminate the while loop without completing it, therefore program control goes to outside the while -
else structure and execute the next print statement.

Flowchart:

Python break, continue statement

break statement

The break statement is used to exit a for or a while loop. The purpose of this statement is to end the
execution of the loop (for or while) immediately and the program control goes to the statement after
the last statement of the loop. If there is an optional else statement in while or for loop it skips the
optional clause also. Here is the syntax.

Syntax:
while (expression1) :
statement_1
statement_2
......
if expression2 :
break
for variable_name in sequence :
statement_1
statement_2
if expression3 :
break
Example: break in for loop

In the following example for loop breaks when the count value is 5. The print statement after the for
loop displays the sum of first 5 elements of the tuple numbers.

numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple

num_sum = 0

count = 0

for x in numbers:

num_sum = num_sum + x

count = count + 1

if count == 5:

break

print("Sum of first ",count,"integers is: ", num_sum)

Output:

Sum of first 5 integers is: 15

Example: break in while loop

In the following example while loop breaks when the count value is 5. The print statement after the
while loop displays the value of num_sum (i.e. 0+1+2+3+4).

num_sum = 0

count = 0

while(count<10):

num_sum = num_sum + count

count = count + 1
if count== 5:

break

print("Sum of first ",count,"integers is: ", num_sum)

Output:

Sum of first 5 integers is : 10

continue statement

The continue statement is used in a while or for loop to take the control to the top of the loop without
executing the rest statements inside the loop. Here is a simple example.

for x in range(7):

if (x == 3 or x==6):

continue

print(x)

Output:

0
1
2
4
5
In the above example, the for loop prints all the numbers from 0 to 6 except 3 and 6 as the continue
statement returns the control of the loop to the top

Python String

String

Python has a built-in string class named "str" with many useful features. String literals can be
enclosed by either single or double, although single quotes are more commonly used.

Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \". A
double quoted string literal can contain single quotes without any fuss (e.g. "I wouldn't be a painter")
and likewise single quoted string can contain double quotes.

A string literal can span multiple lines, use triple quotes to start and end them. You can use single
quotes too, but there must be a backslash \ at the end of each line to escape the newline.
Contents :

 String commands

 Initialize string literals in Python

 Access character(s) from a string

 Python strings are immutable

 Python string concatenation

 Using '*' operator

 String length

 Traverse string with a while or for loop

 String slices

 Search a character in a string

 Python Data Types: String - Exercises, Practice, Solution

String: Commands

# Strips all whitespace characters from both ends.


<str> = <str>.strip()
# Strips all passed characters from both ends.
<str> = <str>.strip('<chars>')

# Splits on one or more whitespace characters.


<list> = <str>.split()
# Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.split(sep=None, maxsplit=-1)
# Splits on line breaks. Keeps them if 'keepends'.
<list> = <str>.splitlines(keepends=False)
# Joins elements using string as separator.
<str> = <str>.join(<coll_of_strings>)

# Checks if string contains a substring.


<bool> = <sub_str> in <str>
# Pass tuple of strings for multiple options.
<bool> = <str>.startswith(<sub_str>)
# Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>)
# Returns start index of first match or -1.
<int> = <str>.find(<sub_str>)
# Same but raises ValueError if missing.
<int> = <str>.index(<sub_str>)

# Replaces 'old' with 'new' at most 'count' times.


<str> = <str>.replace(old, new [, count])
# True if str contains only numeric characters.
<bool> = <str>.isnumeric()
# Nicely breaks string into lines.
<list> = textwrap.wrap(<str>, width)

 Also: 'lstrip()', 'rstrip()'.

 Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.

Char

# Converts int to unicode char.


<str> = chr(<int>)
# Converts unicode char to int.
<int> = ord(<str>)
>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
ord('a'), ord('z')
(97, 122)
Initialize string literals in Python:

>>> s = "Python string"

>>> print(s)

Python string

>>> #using single quote and double quote

>>> s = "A Poor Woman's Journey."

>>> print(s)

A Poor Woman's Journey.

>>> s = "I read the article, 'A Poor Woman's Journey.'"

>>> print(s)

I read the article, 'A Poor Woman's Journey.'

>>> s = 'dir "c:\&temp\*.sas" /o:n /b > "c:\&temp\abc.txt"'

>>> print(s)

dir "c:\&temp\*.sas" /o:n /b > "c:\&tempbc.txt"

>>> #print multiple lines

>>> s = """jQuery exercises

JavaScript tutorial

Python tutorial and exercises ..."""

>>> print(s)

jQuery exercises
JavaScript tutorial

Python tutorial and exercises ...

>>> s = 'jQuery exercises\n JavaScript tutorial\n Python tutorial and


exercises ...'

>>> print(s)

jQuery exercises

JavaScript tutorial

Python tutorial and exercises ...

>>>

Access character(s) from a string:

Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python
uses zero-based indexing, so if str is 'hello' str[2] is 'l'. If the index is out of bounds for the string,
Python raises an error.

>>> a = "Python string"

>>> print (a)

Python string

>>> b = a[2]

>>> print(b)

>>> a[0]

'P'

>>>

Explanation :

 The above statement selects character at position number 2 from a and assigns it to b.

 The expression in brackets is called an index that indicates which character we are
interested.

 The index is an offset from the beginning of the string, and the offset of the first letter is zero.

We can use any expression, including variables and operators, as an index

>>> a = "Python string"


>>> b = a[4+3]

>>> print(b)

>>>

The value of the index has to be an integer.

>>> a = "Python string"

>>> a[2.3]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: string indices must be integers

>>>

Negative indices:

Alternatively, we can use negative indices, which count backward from the end of the

Index -1 gives the last character.

>>> a = "Python string"

>>> a[-2]

'n'

>>> a[-8]

'n'

>>>

Python strings are immutable:

 Python strings are "immutable" which means they cannot be changed after they are created

 Therefore we can not use [ ] operator on the left side of an assignment.

 We can create a new string that is a variation of the original.


>>> a = "PYTHON"

>>> a[0] = "x"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>


TypeError: 'str' object does not support item assignment

>>> a = "PYTHON"

# Concatenates a new first letter on to a slice of greeting.

>>> b = "X" + a[1:]

>>> print(b)

XYTHON

# It has no effect on the original string.

>>> print(a)

PYTHON

>>>

Python String concatenation:

The '+' operator is used to concatenate two strings.

>>> a = "Python" + "String"

>>> print(a)

PythonString

>>>

You can also use += to concatenate two strings.

>>> a = "Java"

>>> b = "Script"

>>> a+=b

>>> print(a)

JavaScript

Using '*' operator:

>>> a = "Python" + "String"

>>> b = "<" + a*3 + ">"

>>> print(b)

<PythonStringPythonStringPythonString>

>>>
String length:

len() is a built-in function which returns the number of characters in a string:

>>> a = "Python string"

>>> len(a)

13

>>> a[13]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

>>> a[12]

'g'

Traverse string with a while or for loop

 A lot of computations involve processing a string character by character at a time.

 They start at the beginning, select each character, in turn, do something to it, and continue
until the end.

 This pattern of processing is called a traversal.

 One can traverse string with a while or for loop:

Code:

a = "STRING"

i = 0

while i < len(a):

c = a[i]

print(c)

i = i + 1

Output:

>>>
S
T
R
I
N
G
>>>
Traversal with a for loop :

Print entire string on one line using for loop.

Code:

a = "Python"

i = 0

new=" "

for i in range (0,len(a)):

b=a[i]

# + used for concatenation

new = new+b

i = i + 1

# prints each char on one line

print(b)

print(new)

Output:

>>>
P
P
y
Py
t
Pyt
h
Pyth
o
Pytho
n
Python
>>>
String slices:

A segment of a string is called a slice. The "slice" syntax is used to get sub-parts of a string. The slice
s[start:end] is the elements beginning at the start (p) and extending up to but not including end (q).

 The operator [p:q] returns the part of the string from the pth character to the qth character,
including the first but excluding the last.
 If we omit the first index (before the colon), the slice starts at the beginning of the string.

 If you omit the second index, the slice goes to the end of the string:

 If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks.

Example-1
>> s = "Python"

 s[1:4] is 'yth' -- chars starting at index 1 and extending up to but not including index 4

 s[1:] is 'ython' -- omitting either index defaults to the start or end of the string

 s[:] is 'Python' -- Copy of the whole thing

 s[1:100] is 'ython' -- an index that is too big is truncated down to the string length

Python uses negative numbers to give easy access to the chars at the end of the string. Negative
index numbers count back from the end of the string:

 s[-1] is 'n' -- last char (1st from the end)

 s[-4] is 't' -- 4th from the end

 s[:-3] is 'pyt' -- going up to but not including the last 3 chars

 s[-3:] is 'hon' -- starting with the 3rd char from the end and extending to the end of the string.

Example-2

>>> a = "Python String"

>>> print (a[0:5])

Pytho

>>> print(a[6:11])

Stri

>>> print(a[5:13])

n String
>>>

>>> a = "Python String"

>>> print(a[:8])

Python S

>>> print(a[4:])

on String

>>> print(a[6:3])

Example-3

>>> a = "PYTHON"

>>> a[3]

'H'

>>> a[0:4]

'PYTH'

>>> a[3:5]

'HO'

>>> # The first two characters

...

>>> a[:2]

'PY'

>>> # All but the first three characters

...

>>> a[3:]

'HON'

>>>

Search a character in a string:

Code:

def search(char,str):

L=len(str)

print(L)
i = 0

while i < L:
if str[i]== char:
return 1
i = i + 1
return -1

print(search("P","PYTHON"))
Output:
>>>
6
1
>>>

 It takes a character and finds the index where that character appears in a string.
 If the character is not found, the function returns -1.

Another example

def search(char,str):
L=len(str)
print(L)
i = 0
while i < L:
if str[i]== char:
return 1
i = i + 1
return -1

print(search("S","PYTHON"))

Output:

>>>
6
-1
>>>
Python String Formatting

String Formatting

The format() method is used to perform a string formatting operation. The string on which this method
is called can contain literal text or replacement fields delimited by braces {}. Each replacement field
contains either the numeric index of a positional argument or the name of a keyword argument.

Syntax:

str.format(*args, **kwargs)
Returns a copy of the string where each replacement field is replaced with the string value of the
corresponding argument.

Contents:
 Basic formatting

 Value conversion

 Padding and aligning strings

 Truncating long strings

 Combining truncating and padding

 Numbers

 Padding numbers

 Signed numbers

 Named placeholders

 Datetime

Basic formatting:

Example-1:

>>> '{} {}'.format('Python', 'Format')

'Python Format'

>>>

>>> '{} {}'.format(10, 30)

'10 30'

>>>

This following statement allows re-arrange the order of display without changing the arguments.

Example-2:
>>> '{1} {0}'.format('Python', 'Format')
'Format Python'
>>>

Value conversion:

The new-style simple formatter calls by default the __format__() method of an object for its
representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r
conversion flags.

In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.
Setup:

class Data(object):

def __str__(self):
return 'str'

def __repr__(self):
return 'repr'
Example-1:

class Data(object):

def __str__(self):

return 'str'

def __repr__(self):

return 'repr'

x='{0!s} {0!r}'.format(Data())

print (x)
Output:
str repr
In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...)
instead.
Example-2:
class Data(object):

def __repr__(self):
return 'räpr'
x='{0!r} {0!a}'.format(Data())
print(x)
Output:
räpr r\xe4pr
Padding and aligning strings:
A value can be padded to a specific length. See the following examples where the value '15' is
encoded as part of the format string.
Note: The padding character can be spaces or a specified character.
Example:
Align right:
>>> '{:>15}'.format('Python')
' Python'
>>>
Align left:
>>> '{:15}'.format('Python')
'Python '
>>>
By argument:
In the previous example, the value '15' is encoded as part of the format string. It is also possible to
supply such values as an argument.
Example:
>>> '{:<{}s}'.format('Python', 15)
'Python '
>>>
Copy
In the following example we have used '*' as a padding character.
Example:

>>> '{:*<15}'.format('Python')

'Python*********'

>>>
Align center:
Example:

>>> '{:^16}'.format('Python')

' Python '

>>>

Truncating long strings:

In the following example, we have truncated ten characters from the left side of a specified string.
Example:
>>> '{:.10}'.format('Python Tutorial')
'Python Tut'
>>>
By argument:
Example:
>>> '{:.{}}'.format('Python Tutorial', 10)
'Python Tut'
>>>
Combining truncating and padding

In the following example, we have combined truncating and padding.

Example:
>>> '{:10.10}'.format('Python')
'Python '
>>>
Numbers:

Integers:
>>> '{:d}'.format(24)
'24'
>>>
Floats:

>>> '{:f}'.format(5.12345678123)
'5.123457'
>>>
Padding numbers:

Similar to strings numbers.

Example-1:
>>> '{:5d}'.format(24)
' 24'
>>>
The padding value represents the length of the complete output for floating points. In the following
example '{:05.2f}' will display the float using five characters with two digits after the decimal point.

Example-2:
>>> '{:05.2f}'.format(5.12345678123)
'05.12'
>>>
Signed numbers:

By default only negative numbers are prefixed with a sign, but you can display numbers prefixed with
the positive sign also.

Example-1:

>>> '{:+d}'.format(24)
'+24'
>>>
You can use a space character to indicate that negative numbers (should be prefixed with a minus
symbol) and a leading space should be used for positive numbers.

Example-2:

>>> '{: d}'.format((- 24))

'-24'

>>>
Example-3:

>>> '{: d}'.format(24)

' 24'

>>>

You can control the position of the sign symbol relative to the padding.

Example-4:

>>> '{:=6d}'.format((- 24))

'- 24'

>>>

Named placeholders:

Both formatting styles support named placeholders. Here is an example:

Example-1:

>>> data = {'first': 'Place', 'last': 'Holder!'}

>>> '{first} {last}'.format(**data)

'Place Holder!'

>>>

.format() method can accept keyword arguments.

Example-2:

>>> '{first} {last}'.format(first='Place', last='Holder!')

'Place Holder!'

>>>

Datetime:

You can format and print datetime object as per your requirement.

Example:

>>> from datetime import datetime

>>> '{:%Y-%m-%d %H:%M}'.format(datetime(2016, 7, 26, 3, 57))

'2016-07-26 03:57'
>>>

Python List

List

A list is a container which holds comma-separated values (items or elements) between square
brackets where items or elements need not all have the same type.

In general, we can define a list as an object that contains multiple data items (elements). The contents
of a list can be changed during program execution. The size of a list can also change during
execution, as elements are added or removed from it.

Note: There are much programming languages which allow us to create arrays, which are objects
similar to lists. Lists serve the same purpose as arrays and have many more built-in capabilities.
Traditional arrays can not be created in Python.

Examples of lists:

 numbers = [10, 20, 30, 40, 50]

 names = ["Sara", "David", "Warner", "Sandy"]

 student_info = ["Sara", 1, "Chemistry"]

Contents:

 List commands
 Create a Python list

 List indices

 Add an item to the end of the list

 Insert an item at a given position

 Modify an element by using the index of the element

 Remove an item from the list

 Remove all items from the list

 Slice Elements from a List

 Remove the item at the given position in the list, and return it

 Return the index in the list of the first item whose value is x

 Return the number of times 'x' appear in the list

 Sort the items of the list in place

 Reverse the elements of the list in place

 Return a shallow copy of the list

 Search the Lists and find elements

 Lists are mutable

 Convert a list to a tuple in python

 How to use the double colon [ : : ]?

 Find largest and the smallest items in a list

 Compare two lists in Python?

 Nested lists in Python

 How can I get the index of an element contained in the list?

 Using Lists as Stacks

 Using Lists as Queues

 Python Code Editor

 Python List Exercises

Lists: Commands
<list> = <list>[from_inclusive : to_exclusive : ±step_size]

<list>.append(<el>)
# Or: <list> += [<el>]
<list>.extend(<collection>)
# Or: <list> += <collection>

<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)

sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
list_of_chars = list(<str>)

# Returns number of occurrences. Also works on strings.


<int> = <list>.count(<el>)
# Returns index of first occurrence or raises ValueError.
index = <list>.index(<el>)
# Inserts item at index and moves the rest to the right.
<list>.insert(index, <el>)
# Removes and returns item at index or from the end.
<el> = <list>.pop([index])
# Removes first occurrence of item or raises ValueError.
<list>.remove(<el>)
# Removes all items. Also works on dictionary and set.
<list>.clear()

Create a Python list

Following list contains all integer values:


>>> my_list1 = [5, 12, 13, 14] # the list contains all integer values
>>> print(my_list1)
[5, 12, 13, 14]
>>>
Following list contains all string:
>>> my_list2 = ['red', 'blue', 'black', 'white'] # the list contains all
string
values
>>> print(my_list2)
['red', 'blue', 'black', 'white']
>>>
Following list contains a string, an integer and a float values:
>>> my_list3 = ['red', 12, 112.12] # the list contains a string, an integer
and
a float values
>>> print(my_list3)
['red', 12, 112.12]
>>>
A list without any element is called an empty list. See the following statements.
>>> my_list=[]
>>> print(my_list)
[]
>>>
Use + operator to create a new list that is a concatenation of two lists and use * operator to repeat a
list. See the following statements.
>>> color_list1 = ["White", "Yellow"]
>>> color_list2 = ["Red", "Blue"]
>>> color_list3 = ["Green", "Black"]
>>> color_list = color_list1 + color_list2 + color_list3
>>> print(color_list)
['White', 'Yellow', 'Red', 'Blue', 'Green', 'Black']
>>> number = [1,2,3]
>>> print(number[0]*4)
4
>>> print(number*4)
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>

List indices

List indices work the same way as string indices, list indices start at 0. If an index has a positive value
it counts from the beginning and similarly it counts backward if the index has a negative value. As
positive integers are used to index from the left end and negative integers are used to index from the
right end, so every item of a list gives two alternatives indices. Let create a list called color_list with
four items.
color_list=["RED", "Blue", "Green", "Black"]

Item RED Blue Green Black

Index (from left) 0 1 2 3

Index (from right) -4 -3 -2 -1

If you give any index value which is out of range then interpreter creates an error message. See the
following statements.
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
indices start at 0 and end at 3
>>> color_list[0] # Return the First Element
'Red'
>>> print(color_list[0],color_list[3]) # Print First and Last Elements
Red Black
>>> color_list[-1] # Return Last Element
'Black'
>>> print(color_list[4]) # Creates Error as the indices is out of range
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

Add an item to the end of the list

See the following statements:

>>> color_list=["Red", "Blue", "Green", "Black"]


>>> print(color_list)
['Red', 'Blue', 'Green', 'Black']
>>> color_list.append("Yellow")
>>> print(color_list)
['Red', 'Blue', 'Green', 'Black', 'Yellow']
>>>

Insert an item at a given position


See the following statements:

>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.insert(2, "White") #Insert an item at third position

>>> print(color_list)

['Red', 'Blue', 'White', 'Green', 'Black']

>>>

Modify an element by using the index of the element


See the following statements:

>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list[2]="Yellow" #Change the third color

>>> print(color_list)

['Red', 'Blue', 'Yellow', 'Black']

>>>

Remove an item from the list


See the following statements:

>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.remove("Black")

>>> print(color_list)

['Red', 'Blue', 'Green']


Copy

Remove all items from the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.clear()

>>> print(color_list)

[]

>>>

Copy

List Slices
Lists can be sliced like strings and other sequences.

Syntax:
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the
end (endIndex) of the list. If you omit both indices, the slice makes a copy of
the original list.

Cut first two items from a list:

See the following statements:


>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements

indices start at 0 and end at 3

>>> print(color_list[0:2]) # cut first two items

['Red', 'Blue']

>>>

Copy
Cut second item from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements

indices start at 0 and end at 3

>>> print(color_list[1:2])

['Blue']

>>> print(color_list[1:-2])

['Blue']

>>>

Copy
Cut second and third elements from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements

indices start at 0 and end at 3

>>> print(color_list[1:-1])

['Blue', 'Green']

>>>

Copy
Cut first three items from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements

indices start at 0 and end at 3

>>> print(color_list[:3]) # cut first three items

['Red', 'Blue', 'Green']

>>>

Copy
Creates copy of original list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements

indices start at 0 and end at 3

>>> print(color_list[:]) # Creates copy of original list

['Red', 'Blue', 'Green', 'Black']

>>>

Copy

Remove the item at the given position in the list, and

return it
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.pop(2) # Remove second item and return it

'Green'

>>> print(color_list)

['Red', 'Blue', 'Black']

>>>

Copy

Return the index in the list of the first item whose value

is x
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.index("Red")

>>> color_list.index("Black")

>>>

Copy

Return the number of times 'x' appear in the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list=["Red", "Blue", "Green", "Black", "Blue"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black', 'Blue']

>>> color_list.count("Blue")

>>>

Copy

Sort the items of the list in place


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.sort(key=None, reverse=False)

>>> print(color_list)

['Black', 'Blue', 'Green', 'Red']

>>>

Copy

Reverse the elements of the list in place


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.reverse()

>>> print(color_list)
['Black', 'Green', 'Blue', 'Red']

>>>

Copy

Return a shallow copy of the list


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.copy()

['Red', 'Blue', 'Green', 'Black']

>>>

Copy

Search the Lists and find Elements


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.index("Green")

>>>

Copy

Lists are Mutable


Items in the list are mutable i.e. after creating a list you can change any item
in the list. See the following statements.
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list[0])

Red
>>> color_list[0]="White" # Change the value of first item "Red" to "White"

>>> print(color_list)

['White', 'Blue', 'Green', 'Black']

>>> print(color_list[0])

White

>>>

Copy

Convert a list to a tuple in Python


>>> listx = [1, 2, 3, 4]

>>> print(listx)

[1, 2, 3, 4]

>>> tuplex = tuple(listx)

>>> print(tuplex)

(1, 2, 3, 4)

>>>

Copy

How to use the double colon [ : : ]?


>>> listx=[1, 5, 7, 3, 2, 4, 6]

>>> print(listx)

[1, 5, 7, 3, 2, 4, 6]

>>> sublist=listx[2:7:2] #list[start:stop:step], #step specify an increment

between the elements to cut of the list.

>>> print(sublist)

[7, 2, 6]

>>> sublist=listx[::3] #returns a list with a jump every 2 times.

>>> print(sublist)

[1, 3, 6]
>>> sublist=listx[6:2:-2] #when step is negative the jump is made back

>>> print(sublist)

[6, 2]

>>>

Copy

Find the largest and the smallest item in a list


>>> listx=[5, 10, 3, 25, 7, 4, 15]

>>> print(listx)

[5, 10, 3, 25, 7, 4, 15]

>>> print(max(listx)) # the max() function of built-in allows to know the


highest

value in the list.

25

>>> print(min(listx)) #the min() function of built-in allows to know the


lowest

value in the list.

>>>

Copy

Compare two lists in Python


>>> listx1, listx2=[3, 5, 7, 9], [3, 5, 7, 9]

>>> print (listx1 == listx2)

True

>>> listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9] #create two lists equal, but
unsorted.

>>> print(listx1 == listx2)

False

>>> listx1, listx2 =[2, 3, 5, 7], [3, 5, 7, 9] #create two different


list
>>> print(listx1 == listx2)

False

>>> print(listx1.sort() == listx2.sort()) #order and compare

True

>>>

Copy

Nested lists in Python


>>> listx = [["Hello", "World"], [0, 1, 2, 3, 4, 5]]

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 4, 5]]

>>> listx = [["Hello", "World"], [0, 1, 2, 3, 3, 5]]

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 3, 5]]

>>> print(listx[0][1]) #The first [] indicates the index of the


outer list.

World

>>> print(listx[1][3]) #the second [] indicates the index nested


lists.

>>> listx.append([True, False]) #add new items

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 3, 5], [True, False]]

>>> listx[1][2]=4

>>> print(listx)

[['Hello', 'World'], [0, 1, 4, 3, 3, 5], [True, False]]


#update value items

>>>

Copy
How can I get the index of an element contained in the

list?
>>> listy = list("HELLO WORLD")

>>> print(listy)

['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']

>>> index = listy.index("L") #get index of the first item whose value is
passed as parameter

>>> print(index)

>>> index = listy.index("L", 4) #define the index from which you


want to search

>>> print(index)

>>> index = listy.index("O", 3, 5) #define the segment of the list to


be searched

>>> print(index)

>>>

Copy

Using Lists as Stacks


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.append("White")

>>> color_list.append("Yellow")

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow']

>>> color_list.pop()
'Yellow'

>>> color_list.pop()

'White'

>>> color_list.pop()

'Black'

>>> color_list

['Red', 'Blue', 'Green']

>>>

Copy

Using Lists as Queues


>>> from collections import deque

>>> color_list = deque(["Red", "Blue", "Green", "Black"])

>>> color_list.append("White") # White arrive

>>> print(color_list)

deque(['Red', 'Blue', 'Green', 'Black', 'White'])

>>> color_list.append("Yellow") # Yellow arrive

>>> print(color_list)

deque(['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow'])

>>> color_list.popleft() # The first to arrive now leaves

'Red'

>>> print(color_list)

deque(['Blue', 'Green', 'Black', 'White', 'Yellow'])

>>> color_list.popleft() # The second to arrive now leaves

'Blue'

>>> print(color_list)

deque(['Green', 'Black', 'White', 'Yellow'])

>>> print(color_list) # Remaining queue in order of arrival

deque(['Green', 'Black', 'White', 'Yellow'])


>>>

Python Dictionary

Dictionary
Python dictionary is a container of the unordered set of objects like lists. The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python
data type.

Each object or value accessed by key and keys are unique in the dictionary.
As keys are used for indexing, they must be the immutable type (string,
number, or tuple). You can create an empty dictionary using empty curly
braces.
Contents :

 Dictionary commands

 Create a new dictionary in Python

 Get value by key in Python dictionary

 Add key/value to a dictionary in Python

 Iterate over Python dictionaries using for loops

 Remove a key from a Python dictionary

 Sort a Python dictionary by key

 Find the maximum and minimum value of a Python dictionary


 Concatenate two Python dictionaries into a new one

 Test whether a Python dictionary contains a specific key

 Find the length of a Python dictionary

 Python Dictionary - Exercises, Practice, Solution

Dictionary: Commands
# Coll. of keys that reflects changes.
<view> = <dict>.keys()
# Coll. of values that reflects changes.
<view> = <dict>.values()
# Coll. of key-value tuples.
<view> = <dict>.items()

# Returns default if key is missing.


value = <dict>.get(key, default=None)
# Returns and writes default if key is missing.
value = <dict>.setdefault(key, default=None)
# Creates a dict with default value of type.
<dict> = collections.defaultdict(<type>)
# Creates a dict with default value 1.
<dict> = collections.defaultdict(lambda: 1)

<dict>.update(<dict>)
# Creates a dict from coll. of key-value pairs.
<dict> = dict(<collection>)
# Creates a dict from two collections.
<dict> = dict(zip(keys, values))
# Creates a dict from collection of keys.
<dict> = dict.fromkeys(keys [, value])

# Removes item or raises KeyError.


value = <dict>.pop(key)
# Filters dictionary by keys.
{k: v for k, v in <dict>.items() if k in keys}

Counter

>>> from collections import Counter


>>> colors = ['blue', 'red', 'blue', 'red', 'blue']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
Create a new dictionary in Python
>>> #Empty dictionary

>>> new_dict = dict()

>>> new_dict = {}

>>> print(new_dict)

{}

>>> #Dictionary with key-vlaue

>>> color = {"col1" : "Red", "col2" : "Green", "col3" : "Orange" }

>>> color

{'col2': 'Green', 'col3': 'Orange', 'col1': 'Red'}

>>>

Copy
Get value by key in Python dictionary
>>> #Declaring a dictionary

>>> dict = {1:20.5, 2:3.03, 3:23.22, 4:33.12}

>>> #Access value using key

>>> dict[1]

20.5

>>> dict[3]

23.22

>>> #Accessing value using get() method

>>> dict.get(1)

20.5

>>> dict.get(3)

23.22

>>>

Copy
Add key/value to a dictionary in Python
>>> #Declaring a dictionary with a single element

>>> dic = {'pdy1':'DICTIONARY'}

>>>print(dic)
{'pdy1': 'DICTIONARY'}

>>> dic['pdy2'] = 'STRING'

>>> print(dic)

{'pdy1': 'DICTIONARY', 'pdy2': 'STRING'}

>>>

>>> #Using update() method to add key-values pairs in to dictionary

>>> d = {0:10, 1:20}

>>> print(d)

{0: 10, 1: 20}

>>> d.update({2:30})

>>> print(d)

{0: 10, 1: 20, 2: 30}

>>>

Copy
Iterate over Python dictionaries using for loops

Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}

for color_key, value in d.items():

print(color_key, 'corresponds to ', d[color_key])

Copy
Output:
>>>
Green corresponds to 2
Red corresponds to 1
Blue corresponds to 3
>>>
Remove a key from a Python dictionary

Code:
myDict = {'a':1,'b':2,'c':3,'d':4}

print(myDict)

if 'a' in myDict:
del myDict['a']

print(myDict)

Copy
Output:
>>>
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}
>>>
Sort a Python dictionary by key

Code:
color_dict = {'red':'#FF0000',

'green':'#008000',

'black':'#000000',

'white':'#FFFFFF'}

for key in sorted(color_dict):

print("%s: %s" % (key, color_dict[key]))

Copy
Output:
>>>
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
>>>
Find the maximum and minimum value of a Python dictionary

Code:
my_dict = {'x':500, 'y':5874, 'z': 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))

key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

print('Maximum Value: ',my_dict[key_max])


print('Minimum Value: ',my_dict[key_min])

Copy
Output:
>>>
Maximum Value: 5874
Minimum Value: 500
>>>
Concatenate two Python dictionaries into a new one

Code:
dic1={1:10, 2:20}

dic2={3:30, 4:40}

dic3={5:50,6:60}

dic4 = {}

for d in (dic1, dic2, dic3): dic4.update(d)

print(dic4)

Copy
Output:
>>>
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
>>>
Test whether a Python dictionary contains a specific key

Code:
fruits = {}

fruits["apple"] = 1

fruits["mango"] = 2

fruits["banana"] = 4

# Use in.

if "mango" in fruits:

print("Has mango")

else:

print("No mango")
# Use in on nonexistent key.

if "orange" in fruits:

print("Has orange")

else:

print("No orange")

Copy
Output
>>>
Has mango
No orange
>>>
Find the length of a Python dictionary

Code:
fruits = {"mango": 2, "orange": 6}

# Use len() function to get the length of the dictionary

print("Length:", len(fruits))

Copy
Output:
>>>
Length: 2
>>>

Python Tuples

Tuples
A tuple is a container which holds a series of comma-separated values (items
or elements) between parentheses such as an (x, y) co-ordinate. Tuples are
like lists, except they are immutable (i.e. you cannot change its content once
created) and can hold mix data types. Tuples play a sort of "struct" role in
Python -- a convenient way to pass around a little logical, fixed size bundle of
values.

Contents:

 Tuple commands

 Create a tuple

 How to get an item of the tuple in Python?

 How to know if an element exists within a tuple in Python?

 List to tuple

 Unpack a tuple in several variables

 Add item in Python tuple!

 Clone a tuple

 In Python how to know the number of times an item has repeated

 Remove an item from a tuple

 Slice a tuple

 How to get the index of an item of the tuple in Python?

 The size of a tuple

 How operators + and * are used with a Python tuple?

 Slice of a tuple using step parameter.

 Modify items of a tuple

 Python Data Types: Tuple - Exercises, Practice, Solution

Tuple: Commands

Tuple is an immutable and hashable list.


<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2> [, ...])
Named Tuple

Tuple's subclass with named elements.


>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields # Or: Point._fields
('x', 'y')
Create a tuple?

To create a tuple, just list the values within parenthesis separated by commas.
The "empty" tuple is just an empty pair of parenthesis
>>> #create an empty tuple

>>> tuplex = ()

>>> print (tuplex)

()

>>> #create a tuple with different data types

>>> tuplex = ('tuple', False, 3.2, 1)

>>> print (tuplex)

('tuple', False, 3.2, 1)

>>> #create a tuple with numbers, notation without parenthesis

>>> tuplex = 4, 7, 3, 8, 1

>>> print (tuplex)

(4, 7, 3, 8, 1)

>>> #create a tuple of one item, notation without parenthesis

>>> tuplex = 4,

>>> print (tuplex)

(4,)

>>> #create an empty tuple with tuple() function built-in Python

>>> tuplex = tuple()

>>> print (tuplex)

()
>>> #create a tuple from a iterable object

>>> tuplex = tuple([True, False])

>>> print (tuplex)

(True, False)

>>>

Copy
How to get an item of the tuple in Python?
>>> #create a tuple

>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")

>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #get item (4th element)of the tuple by index

>>> item = tuplex[3]

>>> print(item)

>>> #get item (4th element from last)by index negative

>>> item1 = tuplex[-4]

>>> print(item1)

>>>

Copy
How to know if an element exists within a tuple in Python?
>>> #create a tuple

>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")

>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #use in statement

>>> print("r" in tuplex)

True

>>> print(5 in tuplex)


False

>>>

Copy
List to tuple
>>> #create list

>>> listx = [5, 10, 7, 4, 15, 3]

>>> print(listx)

[5, 10, 7, 4, 15, 3]

>>> #use the tuple() function built-in Python, passing as parameter the
list

>>> tuplex = tuple(listx)

>>> print(tuplex)

(5, 10, 7, 4, 15, 3)

>>>

Copy
Unpack a tuple in several variables
>>> #create a tuple

>>> tuplex = 4, 8, 3

>>> print(tuplex)

(4, 8, 3)

>>> n1, n2, n3 = tuplex

>>> #unpack a tuple in variables

>>> print(n1 + n2 + n3)

15

>>> #the number of variables must be equal to the number of items of the
tuple

>>> n1, n2, n3, n4 = tuplex

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: need more than 3 values to unpack

>>>
Copy
Add item in Python tuple!
>>> #create a tuple

>>> tuplex = (4, 6, 2, 8, 3, 1)

>>> print(tuplex)

(4, 6, 2, 8, 3, 1)

>>> #tuples are immutable, so you can not add new elements

>>> #using merge of tuples with the + operator you can add an element and
it will create a new tuple

>>> tuplex = tuplex + (9,)

>>> print(tuplex)

(4, 6, 2, 8, 3, 1, 9)

>>> #adding items in a specific index

>>> tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]

>>> print(tuplex)

(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)

>>> #converting the tuple to list

>>> listx = list(tuplex)

>>> #use different ways to add items in list

>>> listx.append(30)

>>> tuplex = tuple(listx)

>>> print(tuplex)

(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)

>>>

Copy
Clone a tuple
>>> from copy import deepcopy

>>> #create a tuple

>>> tuplex = ("HELLO", 5, [], True)

>>> print(tuplex)
('HELLO', 5, [], True)

>>> #make a copy of a tuple using deepcopy() function

>>> tuplex_clone = deepcopy(tuplex)

>>> tuplex_clone[2].append(50)

>>> print(tuplex_clone)

('HELLO', 5, [50], True)

>>> print(tuplex)

('HELLO', 5, [], True)

>>>

Copy
In Python how to know the number of times an item has repeated
>>> #create a tuple

>>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7

>>> print(tuplex)

(2, 4, 5, 6, 2, 3, 4, 4, 7)

>>> #return the number of times it appears in the tuple.

>>> count = tuplex.count(4)

>>> print(count)

>>> count = tuplex.count(7)

>>> print(count)

>>> count = tuplex.count(5)

>>> print (count)

>>>

Copy
Remove an item from a tuple
>>> #create a tuple
>>> tuplex = "w", 3, "d", "r", "e", "s", "l"

>>> print(tuplex)

('w', 3, 'd', 'r', 'e', 's', 'l')

>>> #tuples are immutable, so you can not remove elements

>>> #using merge of tuples with the + operator you can remove an item and
it will create a new tuple

>>> tuplex = tuplex[:2] + tuplex[3:]

>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'l')

>>> #converting the tuple to list

>>> listx = list(tuplex)

>>> #use different ways to remove an item of the list

>>> listx.remove("l")

>>> #converting the tuple to list

>>> tuplex = tuple(listx)

>>> print(tuplex)

('w', 3, 'r', 'e', 's')

>>>

Copy
Slice a tuple
>>> #create a tuple

>>> tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)

>>> #used tuple[start:stop] the start index is inclusive and the stop index

>>> _slice = tuplex[3:5]

#is exclusive.

>>> print(_slice)

(5, 4)

>>> #if the start index isn't defined, is taken from the beg inning of the
tuple.

>>> _slice = tuplex[:6]

>>> print(_slice)
(2, 4, 3, 5, 4, 6)

>>> #if the end index isn't defined, is taken until the end of the tuple

>>> _slice = tuplex[5:]

>>> print(_slice)

(6, 7, 8, 6, 1)

>>> #if neither is defined, returns the full tuple

>>> _slice = tuplex[:]

>>> print(_slice)

(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)

>>> #The indexes can be defined with negative values

>>> _slice = tuplex[-8:-4]

>>> print(_slice)

(3, 5, 4, 6)

>>>

Copy
Find the index of an item of the tuple
>>> #create a tuple

>>> tuplex = tuple("index tuple")

>>> print(tuplex)

('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')

>>> #get index of the first item whose value is passed as parameter

>>> index = tuplex.index("p")

>>> print(index)

>>> #define the index from which you want to search

>>> index = tuplex.index("p", 5)

>>> print(index)

>>> #define the segment of the tuple to be searched

>>> index = tuplex.index("e", 3, 6)


>>> print(index)

>>> #if item not exists in the tuple return ValueError Exception

>>> index = tuplex.index("y")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: tuple.index(x): x not in tuple

>>>

Copy
The size of a tuple
>>> tuplex = tuple("w3resource") #create a tuple

>>> print(tuplex)

('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #use the len() function to known the length of tuple.

>>> print(len(tuplex))

10

>>>

Copy
How operators + and * are used with a Python tuple?
>>> #create a tuple

>>> tuplex = 5, #create a tuple

>>> #The * operator allow repeat the items in the tuple

>>> print(tuplex * 6)

(5, 5, 5, 5, 5, 5)

>>> #create a tuple with repeated items.

>>> tuplex = (5, 10, 15) * 4

>>> print(tuplex)

(5, 10, 15, 5, 10, 15, 5, 10, 15, 5, 10, 15)

>>> #create three tuples

>>> tuplex1 = (3, 6, 9, 12, 15)


>>> tuplex2 = ("w", 3, "r", "s", "o", "u", "r", "c", "e")

>>> tuplex3 = (True, False)

>>> #The + operator allow create a tuple joining two or more tuples

>>> tuplex = tuplex1 + tuplex2 + tuplex3

>>> print(tuplex)

(3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False)

>>>

Copy
Slice of a tuple using step parameter
>>> #create a tuple

>>> tuplex = tuple("HELLO WORLD")

>>> print(tuplex)

('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')

>>> #step specify an increment between the elements to cut of the tuple.

>>> _slice = tuplex[2:9:2] #tuple[start:stop:step]

>>> print(_slice)

('L', 'O', 'W', 'R')

>>> #returns a tuple with a jump every 3 items.

>>> _slice = tuplex[::4]

>>> print(_slice)

('H', 'O', 'R')

>>> #when step is negative the jump is made back

>>> _slice = tuplex[9:2:-4]

>>> print(_slice)

('L', ' ')

>>> #when step is negative the jump is made back

>>> _slice = tuplex[9:2:-3]

>>> print(_slice)

('L', 'W', 'L')

>>>
Copy
Modify items of a tuple
>>> #create a tuple

>>> tuplex = ("w", 3, "r", [], False)

>>> print(tuplex)

('w', 3, 'r', [], False)

>>> #tuples are immutable, so you can not modify items which are also
immutable, as str, boolean, numbers etc.

>>> tuplex[3].append(200)

>>> print(tuplex)

('w', 3, 'r', [200], False)

>>>

Python Sets

Sets
A set object is an unordered collection of distinct hashable objects. It is
commonly used in membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union,
difference, and symmetric difference.

Sets support x in the set, len(set), and for x in set like other collections. Set is
an unordered collection and does not record element position or order of
insertion. Sets do not support indexing, slicing, or other sequence-like
behavior.

There are currently two built-in set types, set, and frozenset. The set type is
mutable - the contents can be changed using methods like add() and
remove(). Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set. The frozenset type is
immutable and hashable - its contents cannot be altered after it is created; it
can, therefore, be used as a dictionary key or as an element of another set.

Contents:
 Set commands

 Create a set in Python

 Iteration Over Sets

 Add member(s) in Python set

 Remove item(s) from Python set

 Intersection of sets

 Union of sets

 set difference in Python

 Symmetric difference

 issubset and issuperset

 Shallow copy of sets

 Clear sets

 Python Data Types: Sets - Exercises, Practice, Solution

Set: Commands
<set> = set()

<set>.add(<el>)
# Or: <set> |= {<el>}
<set>.update(<collection>)
# Or: <set> |= <set>
<set> = <set>.union(<coll.>)
# Or: <set> | <set>
<set> = <set>.intersection(<coll.>)
# Or: <set> & <set>
<set> = <set>.difference(<coll.>)
# Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>)
# Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>)
# Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>)
# Or: <set> >= <set>

<el> = <set>.pop()
# Raises KeyError if empty.
<set>.remove(<el>)
# Raises KeyError if missing.
<set>.discard(<el>)
# Doesn't raise an error.
Frozen Set

 Is immutable and hashable.

 That means it can be used as a key in a dictionary or as an element in a set.


<frozenset> = frozenset(<collection>)

Create a set in Python:


>>> #A new empty set

>>> setx = set()

>>> print(setx)

set()

>>> #A non empty set

>>> n = set([0, 1, 2, 3, 4, 5])

>>> print(n)

{0, 1, 2, 3, 4, 5}

>>>

Copy

Iteration Over Sets:


We can move over each of the items in a set using a loop. However, since
sets are unordered, it is undefined which order the iteration will follow.
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> for n in num_set:

print(n)

2
3

>>>

Copy

Add member(s) in Python set:


>>> #A new empty set

>>> color_set = set()

>>> #Add a single member

>>> color_set.add("Red")

>>> print(color_set)

{'Red'}

>>> #Add multiple items

>>> color_set.update(["Blue", "Green"])

>>> print(color_set)

{'Red', 'Blue', 'Green'}

>>>

Copy

Remove item(s) from Python set:


pop(), remove() and discard() functions are used to remove individual item
from a Python set. See the following examples :

pop() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.pop()

>>> print(num_set)
{1, 2, 3, 4, 5}

>>> num_set.pop()

>>> print(num_set)

{2, 3, 4, 5}

>>>

Copy
remove() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.remove(0)

>>> print(num_set)

{1, 2, 3, 4, 5}

>>>

Copy
discard() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.discard(3)

>>> print(num_set)

{0, 1, 2, 4, 5}

>>>

Copy

Intersection of sets:
In mathematics, the intersection A ∩ B of two sets A and B is the set that
contains all elements of A that also belong to B (or equivalently, all elements
of B that also belong to A), but no other elements.
>>> #Intersection

>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> setz = setx & sety


>>> print(setz)

{'blue'}

>>>

Copy

Union of sets:
In set theory, the union (denoted by ∪) of a collection of sets is the set of all
distinct elements in the collection. It is one of the fundamental operations
through which sets can be combined and related to each other.
>>> #Union

>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> seta = setx | sety

>>> print (seta)

{'yellow', 'blue', 'green'}

>>>

Copy

Set difference:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> setz = setx & sety

>>> print(setz)

{'blue'}

>>> #Set difference

>>> setb = setx - setz

>>> print(setb)

{'green'}

>>>
Copy

Symmetric difference:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> #Symmetric difference

>>> setc = setx ^ sety

>>> print(setc)

{'yellow', 'green'}

>>>

Copy

issubset and issuperset:


>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> issubset = setx <= sety

>>> print(issubset)

False

>>> issuperset = setx >= sety

>>> print(issuperset)

False

>>>

Copy
More Example:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "green"])

>>> issubset = setx <= sety

>>> print(issubset)

True
>>> issuperset = setx >= sety

>>> print(issuperset)

True

>>>

Copy

Shallow copy of sets:


>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "green"])

>>> #A shallow copy

>>> setd = setx.copy()

>>> print(setd)

{'blue', 'green'}

>>>

Copy

Clear sets:
>>> setx = set(["green", "blue"])

>>> #Clear AKA empty AKA erase

>>> sete = setx.copy()

>>> sete.clear()

>>> print(sete)

set()

>>>

Python: user defined functions

ntroduction
In all programming and scripting language, a function is a block of program
statements which can be used repetitively in a program. It saves the time of a
developer. In Python concept of function is same as in other languages. There
are some built-in functions which are part of Python. Besides that, we can
defines functions according to our need.

User defined function

 In Python, a user-defined function's declaration begins with the keyword def and followed
by the function name.
 The function may take arguments(s) as input within the opening and closing parentheses,
just after the function name followed by a colon.
 After defining the function name and arguments(s) a block of program statement(s) start
at the next line and these statement(s) must be indented.

Here is the syntax of a user defined function.

Syntax:
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
Inside Function Call
<function>(<positional_args>)
# f(0, 0)
<function>(<keyword_args>)
# f(x=0, y=0)
<function>(<positional_args>, <keyword_args>)
# f(0, y=0)

Inside Function Call


def f(<nondefault_args>):
# def f(x, y):
def f(<default_args>):
# def f(x=0, y=0):
def f(<nondefault_args>, <default_args>):
# def f(x, y=0):

Call a function
Calling a function in Python is similar to other programming languages, using
the function name, parenthesis (opening and closing) and parameter(s). See
the syntax, followed by an example.

Syntax:

function_name(arg1, arg2)
Argument combinations:
def f(a, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, b=3) | f(1, 2, 3)
def f(*, a, b, c): # f(a=1, b=2, c=3)
def f(a, *, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, b, *, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)

def f(*args): # f(1, 2, 3)


def f(a, *args): # f(1, 2, 3)
def f(*args, c): # f(1, 2, c=3)
def f(a, *args, c): # f(1, 2, c=3)

def f(**kwargs): # f(a=1, b=2, c=3)


def f(a, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(*, a, **kwargs): # f(a=1, b=2, c=3)

def f(*args, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,


c=3) | f(1, 2, c=3) | f(1, 2, 3)
def f(a, *args, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3) | f(1, 2, 3)
def f(*args, b, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, *args, c, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)
Example:
def avg_number(x, y):

print("Average of ",x," and ",y, " is ",(x+y)/2)

avg_number(3, 4)

Copy
Output:
Average of 3 and 4 is 3.5
Explanation:
1. Lines 1-2 : Details (definition) of the function.
2. Line 3 : Call the function.
3. Line 1 : Pass parameters : x = 3, y = 4
4. Line 2 : Print the value of two parameters as well as their average value.

Function without arguments:

The following function has no arguments.

def function_name() :
statement_1
statement_2
....

Example:
def printt():

print("This is Python 3.2 Tutorial")

print("This is Python 3.2 Tutorial")

print("This is Python 3.2 Tutorial")

printt()

Copy
Output:
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
Explanation:

1. Lines 1-4 : Details (definition) of the function.


2. Line 5 : Call the function.
3. Line 1 : No parameter passes.
4. Line 2-4 : Execute three print statements.

The Return statement in function

In Python the return statement (the word return followed by an expression.) is


used to return a value from a function, return statement without an expression
argument returns none. See the syntax.
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
return expression

function_name(arg1, arg2)

Example:

The following function returns the square of the sum of two numbers.
def nsquare(x, y):

return (x*x + 2*x*y + y*y)

print("The square of the sum of 2 and 3 is : ", nsquare(2, 3))

Copy
Output:
The square of the sum of 2 and 3 is : 25
Explanation:

1. Lines 1-2 : Details (definition) of the function.


2. Line 3 : Call the function within a print statement.
3. Line 1 : Pass the parameters x = 2, y = 3
4. Line 2 : Calculate and return the value of (x + y)2

Default Argument Values

In function's parameters list we can specify a default value(s) for one or more
arguments. A default value can be written in the format "argument1 = value",
therefore we will have the option to declare or not declare a value for those
arguments. See the following example.

Example:

The following function returns the square of the sum of two numbers, where
default value of the second argument is 2.
def nsquare(x, y = 2):

return (x*x + 2*x*y + y*y)


print("The square of the sum of 2 and 2 is : ", nsquare(2))

print("The square of the sum of 2 and 3 is : ", nsquare(2,4))

Copy
Output:
The square of the sum of 2 and 2 is: 16
The square of the sum of 2 and 4 is : 36
Explanation:

Lines 1-2 : Details (definition) of the function.

For first print statement [ Line no 3]


Line 3 : Call the function without a second argument, within a print statement.
Line 1 : Pass the parameters x = 2, default value.
Line 2 : Calculate and return the value of (x + y)2

For second print statement [ Line no 4]


Line 3 : Call the function with all arguments, within a print statement.
Line 1 : Pass the parameters x = 2, y = 4.
Line 2 : Calculate and return the value of (x + y)2

Keyword Arguments:

We have already learned how to use default arguments values, functions can
also be called using keyword arguments. Arguments which are preceded with
a variable name followed by a '=' sign (e.g. var_name=") are called keyword
arguments.

All the keyword arguments passed must match one of the arguments
accepted by the function. You may change the order of appearance of the
keyword. See the following example.

Example:
def marks(english, math = 85, science = 80):

print('Marks in : English is - ', english,', Math - ',math, ', Science -


',science)

marks(71, 77)

marks(65, science = 74)

marks(science = 70, math = 90, english = 75)


Copy
Output:
Marks in : English is - 71 , Math - 77 , Science - 80
Marks in : English is - 65 , Math - 85 , Science - 74
Marks in : English is - 75 , Math - 90 , Science - 70
Explanation:

Line 1: The function named marks has three parameters, there is no default
value in the first parameter (english) but remaining parameters have default
values (math = 85, science = 80).
Line 3: The parameter english gets the value of 71, math gets the value 77
and science gets the default value of 80.
Line 4: The parameter english gets the value of 65, math gets the default
value of 85 and science gets the value of 74 due to keyword arguments.
Line 5: Here we use three keyword arguments and the parameter english gets
the value 75, math gets the value 90 and science gets the value 70.

Arbitrary Argument Lists:

The 'arbitrary argument' list is an another way to pass arguments to a function.


In the function body, these arguments will be wrapped in a tuple and it can be
defined with *args construct. Before this variable, you can define a number of
arguments or no argument.

Example:
def sum(*numbers):

s = 0

for n in numbers:

s += n

return s

print(sum(1,2,3,4))

Copy
Output:
10
Lambda Forms:
In Python, small anonymous (unnamed) functions can be created with lambda
keyword. Lambda forms can be used as an argument to other function where
function objects are required but syntactically they are restricted to a single
expression. A function like this:
def average(x, y):

return (x + y)/2

print(average(4, 3))

Copy
may also be defined using lambda

print((lambda x, y: (x + y)/2)(4, 3))

Copy
Output:
3.5
Python Documentation Strings

In Python, a string literal is used for documenting a module,


function, class, or method. You can access string literals by __doc__ (notice
the double underscores) attribute of the object (e.g. my_function.__doc__).

Docstring Conventions :

- String literal literals must be enclosed with a triple quote. Docstring should
be informative

- The first line may briefly describe the object's purpose. The line should
begin with a capital letter and ends with a dot.

- If a documentation string is a muti-line string then the second line should be


blank followed by any detailed explanation starting from the third line.

See the following example with multi-line docstring.


def avg_number(x, y):

"""Calculate and Print Average of two Numbers.

Created on 29/12/2012. python-docstring-example.py


"""

print("Average of ",x," and ",y, " is ",(x+y)/2)

Copy

Python: Built-in Functions

Built-in Functions
The Python interpreter has a number of functions and types built into it that
are always available. They are listed here in alphabetical order.

Name Description

abs() The abs() function is used to get the absolute (positive) value of a given number.

all() The all() function is used to test whether all elements of an iterable are true or not.

any() The any() function returns True if any element of the iterable is true. The function
returns False if the iterable is empty.

ascii() The ascii() function returns a string containing a printable representation (escape
the non-ASCII characters ) of an object.
bin() The bin() function is used to convert an integer number to a binary string. The
result is a valid Python expression.

bool() The bool() function is used to convert a value to a Boolean.

bytearray() The bytearray() function is used to get a bytearray object.

bytes() The bytes() function is used to get a new 'bytes' object.

callable() The callable() function returns True if the object argument appears callable, False if
not.

chr() The chr() function returns the string representing a character whose Unicode
codepoint is the integer.

classmethod() The classmethod() function is used to convert a method into a class method.

complie() The compile() function is used to compile the source into a code.

complex() The complex() function is used to create a complex number or convert a string or
number to a complex number.

delattr() The delattr() function is used to delete the specified attribute from the specified
object.

dict() The dict() function is used to create a new dictionary.

dir() The dir() function returns all properties and methods of the specified object,
without the values. The function will return all the properties and methods, even
built-in properties which are default for all object.

divmod() The divmod() function takes two non complex numbers as arguments and return a
pair of numbers consisting of their quotient and remainder when using integer
division. With mixed operand types, the rules for binary arithmetic operators
apply.
enumerate() The enumerate() function returns an enumerate object. iterable must be a
sequence, an iterator, or some other object which supports iteration.

eval() The eval() function is used to evaluate the specified expression. If the expression is
a correct Python statement, it will be executed.

exec() The exec() function is used to execute the specified Python code. object must be
either a string or a code object.

filter() The filter() function construct an iterator from those elements of iterable for which
function returns true.

float() The float() function is used to convert the specified value into a floating point
number.

format() The format() function is used to format a specified value into a specified format.

frozenset() The frozenset() function returns a new frozenset object, optionally with elements
taken from iterable.

getattr() The getattr() function returns the value of the named attribute of object and name
must be a string

globals() The globals() function returns a dictionary representing the current global symbol
table.

hash() The hash() function returns the hash value of the object (if it has one).

help() The help() function is used to execute the built-in help system.

hex() The hex() function converts an integer number to a lowercase hexadecimal string
prefixed with "0x".

id() The id() function is used to get the identity of an object.


input() The input() function allows user input. If the prompt argument is present, it is
written to standard output without a trailing newline.

int() The int() function converts the specified value into an integer number.

isinstance() The isinstance() function returns true if the object argument is an instance of the
classinfo argument, or of a subclass thereof.

issubclass() The issubclass() function returns true if the specified object is a subclass of the
specified object, otherwise false. A class is considered a subclass of itself.

iter() The iter() function returns an iterator object.

len() The len() function is used to get the length of an object.

list() The list() function is used to create a list object (list is actually a mutable sequence
type).

locals() The locals() function is used to get the local symbol table as a dictionary. Free
variables are returned by locals() when it is called in function blocks, but not in
class blocks.

map() The map() function is used to execute a specified function for each item in a
inerrable.

max() The max() function is used to find the item with the largest value in an iterable.

memoryview() The memoryview() function is used to get a memory view object from a specified
object.

min() The min() function is used to find the item with the smallest value in an iterable.

next() The next() function is used to get the next item in an iterator.

object() The object() function is used to create an empty object.


oct() The oct() function is used to convert an integer number to an octal string.

open() The open() function is used to open a file and returns it as a file object.

ord() The ord() function is used to get an integer representing the Unicode code point of
that character.

pow() The pow() function is used to get the value of x to the power of y (xy). If z is
present, return x to the power y, modulo z (computed more efficiently than pow(x,
y) % z).

print() The print() function is used to print objects to the text stream file, separated by
sep and followed by end. sep, end and file, if present, must be given as keyword
arguments.

property() The property() function return a property attribute.

range() The range() function is used to get a sequence of numbers, starting from 0 by
default, and increments by 1 by default, and ends at a specified number.

repr() The repr() function returns a string containing a printable representation of an


object.

reversed() The reversed() function is used to get a reverse iterator.

round() The round() function returns the rounded floating point value number, rounded to
ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero.

set() The set() function is used to create a set object.

setattr() The setattr() function is used to set the value of the specified attribute of the
specified object.
slice() The slice() function is used to get a slice object representing the set of indices
specified by range(start, stop, step).

sorted() The sorted() function is used to get a new sorted list from the items in iterable.

str() The str() function is used to convert the specified value into a string.

sum() The sum() function is used to get the sum of all items in an iterable.

tuple() The tuple() function is used to create a tuple in Python. Iterable may be a
sequence, a container that supports iteration, or an iterator object.

type() The type() function is used to get the type of an object.

vars The vars() function is used to get the __dict__ attribute of the given object.

zip() The zip() function is used to make an iterator that aggregates elements from each
of the iterables.

Python Classes

Introduction
The basic idea behind an object-oriented programming (OOP) is to combine
both data and associated procedures (known as methods) into a
single unit which operate on the data. Such a unit is called an object.

Python is an object-oriented language, everything in Python is an object.

We have already worked with some objects in Python, (See Python data type
chapter) for example strings, lists are objects defined by the string and list
classes which are available by default into Python. Let's declare two objects a
string and a list and test their type with type() function.
As string1 is an object, strings "Good Morning" can produce an uppercase or
lowercase version of themselves calling upper() and lower() methods
associated with the string. Check it in the Python IDLE.

Note : To see the list of string methods execute the following command in Python IDLE
>>>help(str)

Before introducing classes we must discuss something about local variables,


global statement, and a nonlocal statement as well as Namespaces and
scope rules.

Local Variables:

When a variable is declared inside a function, that variable is accessible only


from that function or statements block where it is declared. The variable has
no relation with any other variable with the same name declared outside the
function, therefore the variable is local to the function. See the following
example.
# python-local-variable.py

def function_local(a):

print('a is -> ',a)

a = 50

print('After new value within the function a is -> ',a)

a = 100

function_local(40)

print('Value of a is ->',a)

Copy

Output:
a is -> 40
After new value within the function a is -> 50
Value of a is -> 100
Explanation:

Line No.- 2 : Declared a function function_local(a) with a parameter


Line No.- 3 : Print 'a' uses the value of the parameter. [The value of a is now
100 as we assign a to 100 (Line No. 6) before executing the function (Line No.
7).]
Line No.- 4 : Assign the value 50 to 'a'.
Line No.- 5 : Again print 'a', as a is local within the function, therefore, the
value of a is now 50.
Line No.- 8 : This is the last print statement and 'a' becomes 100. So far what
we have done within the function which has no effect on the function. This is
called the scope of the variable.

global statement:

The purpose of the global statement is to assign a value to a variable which is


declared outside the function. Free variables (See Line No. 06 in the previous
example) may refer to global without declaring global. The syntax of global
statement is -> global var_name1, var_name2, ..
See the following example:
# python-global-variable.py

def function_local():

global a

print('a is -> ',a)

a = 50

print('After new value within the function a is -> ',a)

a = 100

function_local()

print('Value of a is ->',a)

Copy

Output:
a is -> 100
After new value within the function a is -> 50
Value of a is -> 50
Explanation:

Line No.- 3 : The variable 'a' is declared as a global variable, therefore the
value of a is now 100.
Line No.- 5 : Assign the value 50 to 'a' and it will hold same value inside and
outside the function unless we assign a new value.

nonlocal statement

The nonlocal statement is used to rebind variables found outside of the


innermost scope. See the following example without a nonlocal statement.
def outside():

a = 10

def inside():

a = 20

print("Inside a ->", a)

inside()

print("outside a->", a)
outside()

Copy

In the above example the first print() statement simply print the value of 'a',
which is 20 as 'a' is local within inside() function. The second print() statement
prints the value 'a', which is 10 as the inside() function has no effect. Now we
introduce a nonlocal statement in inside() function and the code will be:

def outside():

a = 10

def inside():

nonlocal a

a = 20

print("The value of a in inside() function - ", a)

inside()

print("The value of a in outside() function - ", a)

outside()

Copy
The second print() statement prints the value 'a', which is 20 as the variable 'a'
is rebound..

Python Scopes and Namespaces:

In general, a namespace is a naming system to create unique names. In daily


experience, we see railway stations, airports, the capital of various states, the
directory structure of filesystems have unique names. As of other
programming language Python uses namespaces for identifiers.

A namespace is a mapping from names to objects.

- For example 'a' maps to [1, 2, 3] or 'a' maps to the value 25.

- Most namespaces currently implemented as Python dictionaries (containing


the names and values of the objects).

- Names in different namespaces have absolutely no relationship (e.g. the


variable 'a' can be bound to different objects in different namespaces).

- Examples of the namespace : The global name of a module, local names in


a function invocation, built-in names (containing functions such as min()),
attributes of an object.

Python creates namespaces at different times.

- The built-in namespace is created when Python interpreter starts and is


never deleted.

- The global namespace for a module is created when the module is called
and last until the interpreter quits.
- The local namespace for a function is created when the function is called
and deleted when the function returns.

A scope is a textual region of a Python program where a namespace is


directly accessible. The scopes in python are as follows:

- The local scope, searched first, contains the local name.

- Enclosing scope (in an enclosing function) contains non-local and non-


global names.

- The current module's global names.

- The outermost scope is the namespace containing built-in names.

Defining a class:

In object oriented programming classes and objects are the main features. A
class creates a new data type and objects are instances of a class which
follows the definition given inside the class. Here is a simple form of class
definition.
class Student:
Statement-1
Statement-1
....
....
....
Statement-n

A class definition started with the keyword 'class' followed by the name of the
class and a colon.

The statements within a class definition may be function definitions, data


members or other statements.

When a class definition is entered, a new namespace is created, and used as


the local scope.

Creating a Class:

Here we create a simple class using class keyword followed by the class
name (Student) which follows an indented block of segments (student class,
roll no., name).
#studentdetails.py

class Student:

stu_class = 'V'

stu_roll_no = 12

stu_name = "David"

Copy

Class Objects:

There are two kind of operations class objects supports : attribute references
and instantiation. Attribute references use the standard syntax, obj.name for
all attribute references in Python. Therefore if the class definition (add a
method in previous example) look like this
#studentdetails1.py

class Student:

"""A simple example class"""

stu_class = 'V'

stu_roll_no = 12

stu_name = "David"

def messg(self):

return 'New Session will start soon.'

Copy

then Student.stu_class, Student.stu_roll_no, Student.stu_name are valid


attribute reference and returns 'V', 12, 'David'. Student.messg returns a
function object. In Python self is a name for the first argument of a method
which is different from ordinary function. Rather than passing the object as a
parameter in a method the word self refers to the object itself. For example if a
method is defined as avg(self, x, y, z), it should be called as a.avg(x, y, z).
See the output of the attributes in Python Shell.
__doc__ is also a valid attribute which returns the docstring of the class.

__init__ method:

There are many method names in Python which have special importance. A
class may define a special method named __init__ which does some
initialization work and serves as a constructor for the class. Like other
functions or methods __init__ can take any number of arguments. The
__init__ method is run as soon as an object of a class is instantiated and class
instantiation automatically invokes __init__() for the newly-created class
instance. See the following example a new, initialized instance can be
obtained by:
#studentdetailsinit.py

class Student:

"""A simple example class"""

def __init__(self, sclass, sroll, sname):

self.c = sclass

self.r = sroll

self.n = sname

def messg(self):
return 'New Session will start soon.'

Copy

Operators
Addition:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

class Subject:

def __add__(self, other):

return School(self, other)

F1, F2 = Subject(), Subject()

F1 + F2

Copy

Output:
<__main__.School object at 0x0000000008B82470>
from pathlib import Path

path = Path('.').parent / 'data'


path.absolute()

Copy

Output:
WindowsPath('C:/Users/User/AppData/Local/Programs/Python/
Python37/data')
Greater / Equality:
class Person:

'''person entity'''

def __init__(self, first_name, surname, age):

self.first_name = first_name

self.surname = surname

self.age = age

def __repr__(self):

return f'Person(first_name={self.first_name},
surname={self.surname}, age={self.age})'

def __lt__(self, other):

return self.age < other.age

data = [

{'first_name':"John", 'surname':'Smith', 'age':13},

{'first_name':"Anne", 'surname':'McNell', 'age':11},

{'first_name':'Mary', 'surname': 'Brown', 'age':14}

results = [Person(**row) for row in data]

print(results)

Copy

Output:
[Person(first_name=John, surname=Smith, age=13),
Person(first_name=Anne, surname=McNell, age=11),
Person(first_name=Mary, surname=Brown, age=14)]
Length:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

def __len__(self):

return len(self.subjects)

Sub = School(Subject(), Subject())

print(len(Sub))

Copy

Output:
2
Getitem:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

def __getitem__(self, i):

return self.subjects[i]

Sub = School(Subject(), Subject())

print(Sub[0])

Copy

Output:
<__main__.Subject object at 0x0000000007ACC5F8>
Inheritance:

The concept of inheritance provides an important feature to the object-


oriented programming is reuse of code. Inheritance is the process of creating
a new class (derived class) to be based on an existing (base class) one where
the new class inherits all the attributes and methods of the existing class.
Following diagram shows the inheritance of a derived class from the parent
(base) class.

Like other object-oriented language, Python allows inheritance from a parent


(or base) class as well as multiple inheritances in which a class inherits
attributes and methods from more than one parent. See the single and
multiple inheritance syntaxes :
class DerivedClassName(BaseClassName):
Statement-1
Statement-1
....
....
....
Statement-n
class DerivedClassName(BaseClassName1, BaseClassName2, BaseClassName3):
Statement-1
Statement-1
....
....
....
Statement-n

Example:

In a company Factory, staff and Office staff have certain common properties -
all have a name, designation, age etc. Thus they can be grouped under a
class called CompanyMember. Apart from sharing those common features,
each subclass has its own characteristic - FactoryStaff gets overtime
allowance while OfficeStaff gets traveling allowance for an office job. The
derived classes ( FactoryStaff & OfficeStaff) has its own characteristic and, in
addition, they inherit the properties of the base class (CompanyMember). See
the example code.
# python-inheritance.py

class CompanyMember:

'''Represents Company Member.'''

def __init__(self, name, designation, age):

self.name = name

self.designation = designation

self.age = age

def tell(self):

'''Details of an employee.'''

print('Name: ', self.name,'\nDesignation :


',self.designation, '\nAge : ',self.age)

class FactoryStaff(CompanyMember):

'''Represents a Factory Staff.'''

def __init__(self, name, designation, age, overtime_allow):

CompanyMember.__init__(self, name, designation, age)

self.overtime_allow = overtime_allow

CompanyMember.tell(self)

print('Overtime Allowance : ',self.overtime_allow)


class OfficeStaff(CompanyMember):

'''Represents a Office Staff.'''

def __init__(self, name, designation, age, travelling_allow):

CompanyMember.__init__(self, name, designation, age)

self.marks = travelling_allow

CompanyMember.tell(self)

print('Traveling Allowance : ',self.travelling_allow)

Copy

Now execute the class in Python Shell and see the output.

Programming using Python


Why Do People Use Python?
Python is a general-purpose programming language that blends procedural, functional, and
object-oriented paradigms. Its focus on readability, coherence, and software quality in
general sets it apart from other tools in the scripting world. Python code is designed to be
readable, and hence reusable and maintainable—much more so than traditional scripting
languages. The uniformity of Python code makes it easy to understand, even if you did not
write it. In addition, Python has deep support for more advanced software reuse
mechanisms, such as object-oriented (OO) and function programming.
Python programs are portable. For example, porting a Python program between Windows
and Linux runs unchanged. In Python programs there is less to type, less to debug, and less
to maintain. Python comes with a large collection of prebuilt and portable functionality,
known as the standard library. This library supports an array of application-level
programming tasks, from text pattern matching to network scripting.

Who uses Python Today?


Python is generally considered to be in the top 5 or top 10 most widely used programming
languages in the world today. Besides individual users, Python is used by real companies.
Some of them are mentioned here:
 Google makes extensive use of Python in its web search systems.
 The popular YouTube video sharing service is largely written in Python.
 The Dropbox storage service codes both its server and desktop client software
primarily in Python.
 The Raspberry Pi single-board computer promotes Python as its educational
language.
Every organization writing software is using Python, whether for short-term tactical tasks,
such as testing and administration, or for long-term strategic product development. Python
has proven to work well in both modes.

What Can I Do with Python?


As a general-purpose language, Python’s roles are virtually unlimited: you can use it for
everything from website development and gaming to robotics and spacecraft control.
Python can be used for:
 Systems Programming
 Internet Scripting
 Database Programming
 Graphical User Interfaces (GUIs) Programming
 Rapid Prototyping
 Numerical and Scientific Programming

Technical Strengths of Python:


 Its object oriented and functional
 It’s Portable
 Main things in Python’s toolbox:
o Dynamic Typing
o Automatic Memory Allotment
o Built-in object types
o Library utilities
 Python is mixable with other programming languages (used in building prototypes).

Variables:
Variables are the programming constructs used to store and name data of any type. The
name of a variable must start with an alphabet or an underscore. A variable is created by
assigning it a value. Ex: x=5. The name of variable is ‘x’ and it stores an integer ‘5’ in it.

Input and Output:


The variables in a python program can be output to the screen using the ‘print(output)’
statement. The output can be a string, number or any other data type.
Input to the program can be given using the statement ‘input(“Enter the input:”)’ . If no data
type is mentioned the input is treated as a string. For any other data type the statement
should be: ‘(data_type(input(“Enter the input:”))’.

Indentation in Python:
Indentation in python is similar to the use of ‘{…}’ in C/C++. The opening and closing of
control loops, conditional statements, functions, objects and classes is done with
indentation only. Within a function only the statements or expressions indented w.r.t to its
definition will be evaluated. Indentation also makes the programs easy to read and
understand.

Data Types in Python:


Integers, Floating point numbers, Boolean values and Strings are the data types which are
represented by ‘int’, ‘float’, ‘complex’, ‘bool’ and ‘str’ respectively.

The types int, float and complex:


In the data type int only the integers are considered and are accurately stored whereas the
type float considers the decimal and fractional parts of numbers as well. The complex
number is of the form a+bj, where a and b are real and imaginary parts respectively. Ex: x=3
is an int type, but x=3.0 is a float type number. The operations of addition, subtraction,
multiplication, exponentiation(**) are same on all numbers. When two integers are divided
the resulting quotient may be either of the data types. Ex: 8/4 = 2.0 and 8//4 = 2. The
division of float type numbers always returns a floating number. Ex: 9.0/2 = 4.5 and 9.0//2 =
4.0. If any number is complex, then resulting quotient will be complex.
The type bool:
The type bool has only two values, True and False. This type is used in conditional
statements, control loops and also used as flags. Ex: 8 >= 5 returns true, ‘not True’ returns
False.

Strings:
Strings are the data types that store characters. The strings can be initialised to a variable in
either single quotes or double quotes. Ex: x = ‘hi’ and x = “hi” are same.

Operations on Strings and String Formatting:


 Strings can be indexed i.e., ‘name’[1] returns ‘a’. Ex: x = ‘python’, then x[2] returns
‘t’. The index of a string starts from 0.
 Strings are immutable i.e. some part of the string cannot be changed.
 Concatenation of strings can be done using addition operator. Ex: ‘Hello’ + ‘World’ =
‘Hello World’.
 Extension of same string repeatedly can be done using multiplication operator.
Example: 2* ‘Hello’ = ‘HelloHello’.
 The function len(string) returns the length of the string. Ex: len(‘Hello’) returns 5.
 The string can be sliced using: str[a:b:n]. starting index=a, ending index=b-1, step
size=5. ‘Hello’[1:4] returns ‘ell’, ‘Hello’[:4] returns ‘Hell’, ‘Hello’[1:] returns ‘ello’,
‘Hello’[:] returns ‘Hello’, ‘Hello’[0:5:2] returns ‘Hlo’ and ‘Hello’[::-1] returns ‘olleH’.
 Entire/some-part of the string can be converted to completely upper or lower case
letters using the functions str.upper() and str.lower() respectively.
 The string can be split into parts w.r.t a char or word using the function str.split(‘x’).
Ex: str= ‘Hello World’, str.split() returns ‘Hello’, ‘World’ whereas str.split(‘o’) returns
‘Hell’, ‘ W’, ‘rld’.

Data Structures in Python:


The data structures make the programs simpler and efficient. The programmer can
manipulate the data easily using data structures. The data structures used in Python are
Lists, Tuples, Sets and Dictionaries.

Lists:
Lists are Python objects which store ordered sequence of information, which can be
accessed by list name and index. A list is denoted by [ ]. The elements of the list are usually
homogeneous but, they can be of mixed data types as well. Unlike strings, lists are mutable
i.e., some part of the list can be changed without changing the other part. Two lists can be
concatenated like that of strings. The elements of list can be accessed using their index.
When a list is multiplied by an integer, then the list is concatenated at the end that many
no. of times.
List Operations:
Let L be a list containing elements of any data type.
The table shown here describes different functions and their operations on the lists with
examples wherever required.

Serial Name of Operation performed by the function


No.: function
1 L.append(x) Appends x at the end of the list L.

2 L.extend([a,b]) Adds the list [a,b] at the end of L

3. L.remove(x) Removes x from the list L if it is present otherwise gives an


error.
4. del(L[index]) Deletes the element with the given index

5. L.pop() Pops the last element of the list and returns it

6. L.sort() The list L is updated with all its elements sorted (L must have
only numbers)
7. sorted(L) Returns the sorted list but ‘L’ remains same

8. L.reverse() The list ‘L’ is reversed.Ex: [1,2] becomes [2,1]

9. ‘_’.join(L) Joins all the elements of L with an ‘_’. (The character joining
can be anything.
10. L.index(x) Returns the index of the element ‘x’ in the list if it exists.

11. L.insert(index,x) Inserts an element ‘x’ at position ‘index’

12. L.clear() Clears all the elements in the list

A string can be converted to a list by using L=list(string). Every character in string is


converted to an element in L. All the slicing operations done on strings are applicable to lists
as well.
Lists can be nested. For example, warm = [‘red’, ‘blue’] and hot = [‘green’]. Now, colours =
[warm] => colours = [[‘red’, ‘blue’]].
Tuples:
Tuple is a data structure which is similar to the list. The main difference between a list and a
tuple is mutability. Like strings, Tuples are also immutable. A tuple is represented within
parentheses. Ex: t = (2, ‘one’, 3). A tuple can have different types of elements in it.
Concatenation can be done like that of strings and lists.
Main use of tuples in python:
 Used to swap variables without a temporary variable. Ex: (x,y) = (y,x) swaps x and y.
 Used to return more than one value in a function. The statement return (x,y) returns
a tuple (x,y).
 A tuple can contain tuples and/or other data structures in it. A tuple ( (), (), …()) is
valid. Ex: words = [], no = (), tuple = (words, no) is valid.
 Tuples can be indexed as well. All the operations mentioned in the lists which
doesn’t mutate the list are applicable to tuple as well.

Mutation, Aliasing and Cloning in lists (Side effects):


1. Aliasing is a side effect in lists. When one list is assigned to the other, a change in either of
the list changes both the lists. This can affect the result of a program unless we do it
purposely. This is a side effect of lists. Ex: warm = [‘red’, ‘green’]; hot=warm. Here ‘hot’ is an
alias for warm – changing one changes the other.
2. Always avoid mutating a list while you are iterating over it. The effect is shown in the
example below:
Program and Output:

The expected output is [3,4]. As the element of list L1 is removed in first iteration, its length
gets changed but the index count does not change. As-a-result element ‘2’ is in position ‘0’
and never seen by the iterator.
3. Cloning is the method of copying the elements of the lists so that it can avoid the side
effects due to mutation and aliasing. This is done by the statement: L_copy = L[ : ]. Now, a
change in one of them does not change the other list.
Dictionaries:
A dictionary is an unordered collection of data values which holds key: value pair unlike
other data structures. The dictionary in python works similar to the dictionary in real world.
An empty dictionary can be created using the statement: a_dict = {}.
The conditions on values of the dictionary are:
 They can be of any type (mutable or not).
 They can be lists, tuples, even other dictionaries as well.
The keys must be unique and they must be of immutable type (int, string, tuple). Let us take
an example: grades = {‘X’: ‘A’, ‘Y’: ‘B’, ‘Z’: ‘A+’}. grades[‘W’] = ‘A’ adds to the dictionary,
hence they are mutable.

Some operations:
 ‘X in grades’ returns True and ‘K in grades’ returns False.
 An empty dictionary can be initialized using the statement: d = dict{}.
 del(grades[‘Z’]) deletes ‘Z’ and its value from the dictionary.
 grades.keys() gives all the keys in the dictionary.
 grades.values() gives all the values in the dictionary.
 grades.items() gives all the keys and respective values in the dictionary.
 grades.pop(‘X’) removes the element with key ‘X’.
 grades.update(d) adds the dictionary ‘d’ at the end of ‘grades’.
Example: This example shows the advantage of use of a dictionary in computing
Fibonacci(n). In normal computation, we compute Fibonacci(n-1) and Fibonacci(n-2) using
recursion. And, in Fibonacci(n-1) we again compute Fibonacci(n-2) and Fibonacci(n-3), this
increases the no. of function calls as we are computing the known value again and again.
When ‘n’ is more than 10, number of function calls will be in millions. To avoid this, we store
the value we compute in a dictionary, so that we can directly get those values from the
dictionary.
Program:
Output when n=20, 30, 34:

As we can see from the output of the example, the number of recursive calls in the first
function are 1.66 million for n=30, whereas in second function we only require 57 recursive
calls as we are using a dictionary. From 3 rd output sample it is clear that with slight increase
in ‘n’, recursive calls in first function reached 10 million. So, use of dictionary improves the
efficiency of computation to a large extent.

Sets:
Set is an unordered and unindexed collection of unique elements. Sets can be initialized
within curly brackets as shown:
new = {‘x’, ‘y’}
Unlike dictionaries, sets are immutable. Some basic operations that can be performed on
sets are shown below:
 new.add(‘z’) adds the item ‘z’ into the set. Only one item can be added at a time.
 To add more than one item we use, new.update(‘a’, ‘b’).
 len(new) returns the value of number of items in the set.
 new.remove(‘x’) removes the item ‘x’ from the set.
 new.pop() removes the last item from the set. As sets are unordered any item may
get removed.
 del new deletes the entire set.
Whenever, we need the collection of unique elements/objects sets can be used. The
disadvantage of using sets is that they are unordered, as a result they can’t be accessed with
the index.
Example:

This example shows that sets are unordered and unique collection of items.

Control Structures:
Conditional Statements:
if statement:
Syntax: if condition:
expression
If the condition is True the expression is evaluated.
if-else statement:
Syntax: if condition:
expression-1
else:
expression-2
If the condition is True the expression-1 is evaluated, otherwise expression-2 is evaluated.
if-elif-…else statement: (Multiway Branching)
Syntax: if condition1:
expression-1
elif condition2
expression-2
else:
expression-3
If the condition1 is True the expression-1 is evaluated, else-if condition2 is True expression-2
is evaluated otherwise expression-3 is evaluated.
Example:
Control loops:
While loop:
The expressions inside the while loop are evaluated as long as the condition is True. The
conditional variable must be changed within the loop to prevent the occurrence of an
infinite loop. All the expressions are evaluated in every iteration. Initialization of variable
determining the condition must be done before the loop.
Syntax: while condition:
expression1
expression2

expression-n
Example: (Sum of first 5 whole numbers)

For loop:
While ‘i’ runs from ‘0’ to ‘n-1’ all the expressions within the loop are evaluated. Instead of
range, we can use a list, dictionary, string etc… As shown in the slicing function of strings the
range function can also be given the arguments (start, stop, step). By default, start = 0 and
step = 1.
Syntax: for i in range(n):
expression-1

expression-n
Example: (The sum of all even numbers from 2 to 10 (both included).)
Functions in Python:
Function definition and structure:
A function in Python is a black box that returns a value when it is called in expressions with
required arguments. This black box contains the program (algorithm) to do the required
operations and return the output. In python, functions are defined using the ‘def’
statement. The def statement creates a function object and assigns it to a name. Its general
format is as follows:
def name(arg1, arg2,... argN):
statements
return value
Here, def consists of a header line followed by a block of statements. The statement block
becomes the function’s body i.e., the code Python executes each time the function is later
called. In the header line of def, the name and arguments of the function are specified.
Function bodies often contain a return statement. When the function reaches the return
statement it ends the function and returns the value to the caller. If there is no return
statement, then the function returns ‘None’.

Function Call:
A function call is an expression consisting of the function name followed by arguments
enclosed in parentheses. If there is more than one argument, the arguments are separated
by commas. A function call is an expression that can be used like any other expression of the
type specified for the value returned by the function.
SYNTAX
Function_Name ( Argument_List )
where the Argument_List is a comma-separated list of arguments: Argument_1 ,
Argument_2 , . . . , Argument_Last
Example: x = max(5,10)
Here, the built-in function ‘max(a,b)’ is called and the value returned is assigned to x. This
function returns the maximum value of 5 and 10. So, x = 10.

Why Use Functions?


Whenever a part of the code needs to be used more than once in a program functions are
used. They allow us to group and generalize code to be used arbitrarily many times later.
Thus, functions maximize code reuse and minimize code redundancy.
It’s easier to implement the smaller tasks in isolation than it is to implement the entire
process at once. Functions allow us to split a problem/algorithm into pieces which can be
integrated after implementing these small pieces.
Example: Euclid’s algorithm to find GCD of two numbers

Defining a function using the expression lambda:


Functions may also be created with the expression ‘lambda’. Wherever the function
definition can’t be used this is used. It will contain only one expression and no return
statement is required. The function returns the value evaluated by the expression. An
example shown here gives a clear idea of syntax and the use of ‘lambda’.
Example: (Here, ‘x’ is an argument to the function and it returns ‘x + y’)

Scope of Variables:
All the code we write in Python which is not inside a ‘def’ block, is said to be global to the
program. Global means that all the variables in this scope can be accessed and used
anywhere in the program. Functions define a local scope and modules define a global scope.
By default, all the names assigned inside a function definition are put in the local scope i.e.,
those variables which are assigned in the function can’t be used outside it.
Functions can be nested: Unlike to ‘C/C++’, a function can be enclosed within another
function or a loop or a conditional statement. The variables declared in an enclosing
function can be used in all the functions enclosed within it.
In order to use a global variable in a function, it must be declared as a global variable within
the function. All the changes made will be in global scope. If we need to assign a name that
lives in an enclosing def, we can do so by declaring it in a nonlocal statement.
The LEBG Rule: (Within a def statement)
 Name assignments create or change local names by default.
 Name references search at most four scopes: local, then enclosing functions (if any),
then global, then built-in.
 Names declared in global and nonlocal statements map assigned names to enclosing
module and function scopes, respectively.
An Example:

Fig: The LEBG scope lookup rule


In the above example, the local variable S is converted to non-local as shown. Also, P is
changed to a global variable and hence any changes within the function affects the value
globally.

Recursive functions:
Functions that call themselves either directly or indirectly in order to loop are called
Recursive functions. Recursion allows programs to traverse structures that have arbitrary
and unpredictable shapes and depths like travelling routes etc… Recursion is an alternative
to loops but may not be the efficient one. Always, a condition must be provided to stop the
recursion
Analysis of problems becomes easier with recursion. For example, computing sum of first n
natural numbers using recursion won’t differ much w.r.t iterative method. While solving
arbitrary structures like Towers of Hanoi, becomes handy. In Towers of Hanoi, it becomes
difficult to solve the problem using stacks. Recursion, makes this problem easy.
1. If there is one CD then directly move it.
2. If they are ‘n’, move ‘n-1’ to auxiliary tower and repeat step 1.
3. Repeat steps 1 and 2 for remaining CDs until all CDs are moved to the required
tower.
Program: (Towers of Hanoi)

You might also like