python (1)

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 323

PYTHON

Introduction

 Necessity of Programming
 What is Python ?
 Why to learn Python ?
 Important Features
Why Programming?
 There are more than 700 languages available in today’s
programming world.

 Every language is designed to fulfil a particular


requirement.

 To communicate with digital machines and make them


work accordingly.
What is Python ?
 Python is most widely used powerful, general purpose,
high level programming language.
 Python provides over 137,000 python libraries.

Libraries are a set of useful functions that eliminate the


need for writing codes from scratch.
Applications
Web application in Python

 Python can be used to create


 web applications.

 There are python frameworks


 like Django, Flask and Pyramid
 for this purpose.
Data Analysis in Python
 Python is the leading language
 f of choice for many data scientists.

 It has grown in popularity due to


 excellent libraries like:
Numpy
Pandas
Matplotlib

A data scientist is a professional responsible for


collecting, analyzing and interpreting extremely
large amounts of data.
Machine Learning in Python
Machine learning is
about making
predictions with data.

It is mainly used in
Face Recognition,
Music recommendation,
Medical Data etc

Python has many libraries to implement ML algorithms like


Scikit-Learn, Tensorflow (neural networks), Keras (Deep Learning)
Raspberry Pi in Python

 We can build Home Automation System and even robots


using Raspberry-Pi
 The coding on a Raspberry-Pi can be performed using
Python.
Game Development in Python
 We can write whole games in Python using PyGame
 Popular games developed in Python are:
Bridge Commander
Civilization IV
Battlefield 2
Eve Online
Freedom Force
Who created Python?
 Developed by Guido van Rossum,
a Dutch Scientist and first released
on February 20, 1991
 The name Python is inspired from
Guido’s favourite Comedy TV
show “Monty Python’s Flying
Circus”
Features of Python
 Easy-to-learn: Python has few keywords, simple structure,
and a clearly defined syntax. Python code is comparatively
3 to 5 times smaller than C/C++/Java.
In C:
#include<stdio.h>
int main()
{
print(“Hello World!”);
}
In Python:
print(“Hello World!”)
Swap 2 numbers:

In C:
int a=10, b=20, temp;
temp = a;
a = b;
b = temp;
In Python:
a, b = 10,20
a, b = b, a
 Dynamically typed:

Dynamically Typed - Statically Typed –


Python C/C++/Java
No need to declare variable Need to declare variable type
type before using it
Can change variable type at Cannot change variable type at
runtime runtime
Variable can hold different Variable can hold only one type
types of value through its of value throughout its lifetime
lifetime
Dynamically Typed:
In C:
int a;
a = 10;
a = “Goa”;

In Python:
>>> spam = 'Hello'
>>> spam
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye‘

Note:
When a new value is assigned to a variable, the old one is forgotten.
 Compiled as well as interpreted:

 Python uses both a compilers as well as interpreter for


converting our source and running it.
 Interpret: To execute a program in a high-level

language by translating it one line at a time.


 Compile: To translate a program written in a high-level

language all at once, in preparation for later execution.


 Portability: Python can run on a wide variety of

hardware platforms and has the same interface on all


platforms.
 Support Multiple Programming Paradigms

 Python supports both procedure-oriented and


object-oriented programming which is one of the
key python features.
 In procedure-oriented languages, the program is

built around procedures or functions which are


nothing but reusable pieces of programs.
 In object-oriented programming languages, the

program is built around objects which combine data


and functionality.
 Cross Platform

 Suppose we’ve written a Python code for Windows


machine.
 Now, if we want to run it on a Mac, no need to make

any changes.
 We can take one code and run it on any machine,

there is no need to write different code for different


machines.
 This makes Python a cross platform language.
 A broad standard library: Python’s bulk of the library
is very portable and cross-platform compatible
 Interactive Mode: Python has support for an interactive
mode which allows interactive testing and debugging of
snippets of code.
 Databases: Python provides interfaces to all major
commercial databases.
 GUI Programming: Python supports GUI applications
that can be created and ported to many system calls,
libraries and windows systems
Key Words
Downloading and Installing Python
 https://anaconda.org/  Download Anaconda
 Jupyter Notebook: It is a web based IDE.

 https://colab.research.google.com/ (Google Colab)


Colaboratory, or Colab for short, is a Google Research product, which
allows developers to write and execute Python code through their browser.
Colab is a free Jupyter notebook environment that runs entirely in the cloud.
It does not require a setup and the notebooks that you create can be
simultaneously edited by your team members - just the way you edit
documents in Google Docs.
 https://www.python.org/

 We can use Python in 2 ways:


 Without any IDE, i.e., by simply using Notepad for writing the code and
running it on command prompt.

 With an IDE like PyCharm, Spyder, Visual Studio Code


Difference between Jupyter and Colab
Jupyter Notebook- Anaconda Google Colab
Runs on your local hardware Runs on Google server
You have to install library manually Most of the required library are pre-
installed
Can’t be shared with others without Can be shared with others without
downloading it downloading
Need to be installed in your No need to install anything, can be
computer through anaconda or used through browser
python
Can’t access your notebook files Can be accessed from anywhere
without your hard-drive without hard-drive since it’s stored
in your Google drive.
Interacting with Python

Python can be used in two modes:

 Interactive Mode

 Script Mode
Interactive Mode
 In Interactive Mode, Python waits for user to enter
command.
 When we type command, Python interpreter goes ahead
and executes the command, and then it waits again for
next command.
 Python interpreter in interactive mode is commonly
known as Python Shell.
 To start the Python Shell enter the following command in
the command prompt.
◦ Python
◦ This will activate the Python Shell and we can use it for
running python statements or commands.
Script Mode
 In Script Mode, Python interpreter runs a program from
the source file.
 Python Shell is great for testing small chunks of code but
there is one problem – the statements we enter in the
Python shell are not saved anywhere.
 So if we want to execute same set of statements multiple
times we will have to write them multiple times which is
a difficult task.
 In this case it is better to write the code in a File, Save it
and then Run it
 This is called Script Mode.
Script Mode
In this mode we take following steps for developing and running
a Python code:
1. Write the source code
Remember the file can have any name but the extension
must compulsorily be .py
2. Compile it ( Generation of bytecode )
This bytecode is stored in RAM and not visible to
us.
3. Run it ( Execution of the bytecode)

We have to perform step 1 and step 3, step 2 is hidden from


the programmer and is internally performed by Python itself.
Python Data types

Perform Operations using


Data Types
(Strings, Numbers, Bool, Collections) and
Operators (Operators Precedence)
Perform Operations using Data Types and
Operators (20-25%)

 Evaluate an expression to identify the data type Python


will assign to each variable
 identify str, int, float, and bool data types Perform
data and data type operations
 convert from one data type to another type; construct
data structures; perform indexing and slicing
operations
 Determine the sequence of execution based on
operator precedence
 assignment; comparison; logical; arithmetic; identity
(is); containment (in) Select the appropriate operator
to achieve the intended result
Variable Definition and Declaration
 In any programming language, Variables are used to give a
name to a memory location.

 Variables are the reserved memory locations to store values.


This means that when you create a variable you reserve some
space in memory.

 The value declared may or may not change in future.

 In python, a variable is created, once we assign a value to it. It


does not need any commands unlike other programming
languages like C.
Assigning Values to Variables:

 The declaration happens automatically when you assign a value to


a variable. The equal sign (=) is used to assign values to variables.

counter = 100 # An integer assignment


miles = 1000.4 # A floating point
name = "John" # A string

 You can also assign a single value to several variables


simultaneously.
 For example:
a=b=c=1
a, b, c = 1, 2, "john"
Rules for declaring variable
 Variable name should start with an alphabet or underscore(‘_’)

followed by any number of alphabets, digits and underscores.

 Variable names are case sensitive.


Example: number is different from Number and NUMBER

 Variable name cannot contain any special character other than


underscore.

 No space is allowed.

 Variable name cannot be a reserved name like keywords. All the


keywords except True, False and None are in the lowercase.
Example: print, input, type …..
Assignment operator

• a=1 means assigning a value 1 to a variable ‘a’


◦ Assignment combined with operations
• a+=1 , assigning value to variable ‘a’ and adding a value 1
to it (i.e., a= a+1).
• Similarly we can perform,
 a-=1
 a*=1
 a/=1
• Perform arithmetic operations(+, - ,* ,/ ,// )
Python Operator Precedence
Highest precedence at top, lowest at bottom.
Operators in the same box evaluate left to right.
Example:
10*6/3+9//(3*2)
10*6/3+9//6
60/3+9//6
20+9//6
20+1
21
Comparison Operators

Comparison operators, also called relational operators, compare


two values and evaluate down to a single Boolean value.

 The == operator (equal to) asks whether two values are the same as each
other.
 The = operator (assignment) puts the value on the right into the variable on
the left.
Logical Operators

 Logical operators are used to combine conditional


statements.
 x=5

Operator Description Example Output


and Returns True if both x < 5 and x < 10 False
statements are true
or Returns True if one of x < 5 or x < 8 True
the statements is true
not Reverse the result, not(x < 5 and x < 10) True
returns False if the result
is true
Logical AND - and
 If the first value is False , then Logical ‘and’ returns first
value , otherwise it returns the second value.
 In case of and if both or any one of the operands is 0 then the

result is 0.
 If both the values are true (valid numerical) it will return 2nd

value irrespective of which no is greater


Example:
 12 and 13

Output: 13
 5 and 0 # first value of 5 is true , it returns second value

Output: 0
 0 and 3 # first value of 0 is false , it returns first value

Output: 0
Logical OR -or
 If the first value is True , then Logical ‘or’ returns first value , otherwise
it returns the second value
 In case of or if any one the operand is 0 , it will consider the other value

as output.
 If both the values are true (valid numerical) it will return 1st value

irrespective of which no is greater


Example:
 12 or 1890

Output: 12
 0 or 12

 Output: 12

NOT- not
 When we use not operator on non boolean types ,
 it returns True if it’s operand is False( in any form) and False if it’s
operand is True ( in any form)
Bitwise Operators

 Bitwise operators are used to compare binary numbers.


Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is
1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the
shift right and let the leftmost bits fall off
>> Signed right Shift right by pushing copies of the
shift leftmost bit in from the left, and let the
rightmost bits fall off
x = 10 (0000 1010 in binary)
y = 4 (0000 0100 in binary)
Left shift << means multiply by 2
Right shift >> means divide by 2

Operator Meaning Example


& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Bitwise AND operator
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
&
0100

0000 = 0 (Decimal)
Bitwise or operator
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010
|
0100

1110 = 14 (Decimal)
Bitwise not operator
a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
Bitwise xor operator:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
^
0100

= 1110 = 14 (Decimal)
Bitwise right shift:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

a = -10 = 1111 0110 (Binary)


a >> 1 = 1111 1011 = -5
Bitwise left shift:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20

b = -10 = 1111 0110 (Binary)


b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
and OPERATOR
The and operator evaluates an expression to
 True if both Boolean values are True otherwise, it evaluates to

False.
 >>> True and True

True
>>> True and False
False
or OPERATOR
or operator evaluates an expression to True if either of the two
Boolean values is True. If both are False, it evaluates to False.
>>> False or True
True
>>> False or False
False
The not Operator
 The not operator operates on only one Boolean value (or

expression). The not operator simply evaluates to the opposite


Boolean value.

not True - False


not False - True

>>> not True


False
>>> not not not not True
True
Mixing Boolean and Comparison Operators

>>> (4 < 5) and (5 < 6)


True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.

 Comments can be used to prevent execution when testing

code.
Single line comment
Comments starts with a #, and Python will ignore them.
# This is a comment
print("Hello, World!")

In-line comment

print("Hello, World!") #This is a inline comment


Multi-line comment
 To add a multiline comment you could insert a # for each line
or, not quite as intended, you can use a multiline string.
 add a multiline string (single or double triple quotes) in your
code, and place your comment inside it:

"""
This is a comment
# This is a comment
written in
# written in
more than just one line
# more than just one line
"""
print("Hello, World!")
print("Hello, World!")
Question:
 You need to ensure that the function is documented with
comments. You create the following code. Line numbers are
included for reference only.
01 # The calc_power function calculates exponents
02 # x is the base
03 # y is the exponent
04 # The value of x raised to the y power is return
05 def calc_power(x, y):
06 comment =”#Return the value”
07 return x**y #raise x to the y power
 For each of the following statements, select Yes if the

statement is true. Otherwise, select No.


Numbers:

Int(signed integers): They are positive or negative whole numbers with no


decimal point.

Long(long integers): They are integers of unlimited size, written like


integers and followed by uppercase or lowercase L.

Float(floating point real values): They represent real numbers and are
written with a decimal point. Floats may also be in scientific notation
with E or e indicating power of 10.
Example: 2.5e2 = 2.5 x 10^2 = 2.5 x 100 = 250

Complex(complex numbers): are written in the form a+bj. The real part of
number is a and the imaginary part is b.
Letter j should appear only in suffix, not in prefix.
Example: 3+5j
Lines 01 through 04 will be ignored for syntax checking.
A. Yes
B. No
Answer: A

The pound sign (#) is optional for lines 02 and 03.


A. Yes
B. No
Answer: B

The string in line 06 will be interpreted as a comment.


A. Yes
B. No
Answer: B
Python Data Types:
 Numbers
 String
 Bool
 List
 Tuple
 Dictionary
 Set
A data type is a category for values, and every value
belongs to exactly one data type.

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, set, range
Mapping Type: dict (dictionary)
Boolean Type: bool
Bool
 Data type Boolean is used to store 2 values which is True or False.
 All the comparators used will result in True/False

 The three Boolean operators (and, or, and not) are used to compare

Boolean values.
 Like comparison operators, they evaluate these expressions down to

a Boolean value.
 After any math and comparison operators evaluate, Python evaluates

the not operators first, then the and operators, and then the or
operators.
>>> 42 == 42 >>> 2 != 3
True True
>>> 2 != 2 >>> 42 == 99
False False
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
>>> 42 == '42'
False
>>> Bool(n) # any non zero number will be true
True
>>> Bool()
False
>>> Bool(‘’)
False
>>> b = False + 5 –True +5//4
5
Note:
 Internally Python stores True and False as integers with the

value 1 and 0 respectively.


 In calculations False is treated as 0 and True is treated as 1.
Question:

 float
 float
 str
 bool
Question:

 int
 bool
 str
 float
 str
Question: What is the correct order of operations for the six classes of
operations ordered from first to last in order of precedence?

 Parenthesis
 Exponents
 Unary positive, negative, not
 Multiplication and Division
 Addition and Subtraction
 And
Question:
You are writing a Python program that evaluates an arithmetic
formula. The formula is described as b equals a multiplied by
negative one, then raised to the second power, where a is the
value that will be input and b is the result.

b= (- a) **2
Question:
You are writing a Python program to perform arithmetic operations.
You create the following code:
a=11
b=4
What is the result of each arithmetic expression?
Q1: 2
A. Print(a/b)
B. Print(a//b)
C. Print(a%b)
Answer: B

Q1: 3
A. Print(a/b)
B. Print(a//b)
C. Print(a%b)
Answer: C
Q1: 2.75
A. Print(a/b)
B. Print(a//b)
C. Print(a%b)
Answer: A
Question:
Evaluate the following Python arithmetic expression:
(3*(1+2)**2 – (2**2)*3)
What is the result?
A. 3

B. 13

C. 15

D. 69

Answer: C
Question:
 You develop a Python application for your company.
 A list named employees contains 200 employee names, the

last five being company management. You need to slice the


list to display all employees excluding management.
 Which two code segments should you use? Each correct

answer presents a complete solution. Choose two.


A. employees [1:-4]
B. employees [:-5]
C. employees [1:-5]
D. employees [0:-4]
E. employees [0:-5]
Answer: B,E
Question:
 You develop a Python application for your company.
 You want to add notes to your code so other team members
will understand it. What should you do?

A. Place the notes after the # sign on any line.


B. Place the notes after the last line of code separated by a
blank line.
C. Place the notes before the first line Of code separated by a
blank line.
D. Place the notes inside of parentheses on any line.

Answer: A
# Take a number as input and check whether the number is
divisible by 5 and 7

num = int(input("enter a number"))

if(num % 5 ==0 and num % 7 == 0):


print("number is divisible by 5 and 7")
else:
print("number is not divisible by 5 and 7")
String:

 Strings are a collection of characters. A string can group any type of


known characters i.e. letters ,numbers and special characters. They are
enclosed in single quote, double quote, triple (literal) quote or raw string.
 Example: ‘Hi’ , “hello” , ‘1234’

 Strings are immutable. i.e., string object does not support item
assignment.

 Subsets of strings can be taken using the slice operator ([ ] and [ : ])


with indexes starting at 0 in the beginning of the string.
 Indexing is used to extract individual characters from a string.
 Slicing means taking subsets from a string.

 The plus ( + ) sign is the string concatenation operator, and the asterisk (
* ) is the repetition operator.
Example:
S1 = 'Mango'
S2 = "Hello"
S3 = "Hey, 'Good' Morning"
S4 = 'Hey, "Good" Morning‘
print(S3)
Hey, 'Good' Morning
print(S4)
Hey, "Good" Morning

S5 = "Hey, \"Good\" Morning“


print(S5)
Hey, "Good" Morning
 We can use double quote within single quote or single quote within double quote .

To use double quote within double quote and single quote within single quote use
escape character.
 Backslash ( \ ) can be used to escape quotes. The output string is enclosed in

quotes and special characters are escaped with backslashes.


 String literals(triple quote) can span multiple lines by using
triple-quotes: """...""" or '''...'''.
Example: S = '''hello
Good morning
Welcome'''
print(S)
Output: hello
Good morning
Welcome
 End of lines are automatically included in the string, but it’s
possible to prevent this by adding a \ at the end of the line.
Example: S = '''hello\
Good morning\
Welcome'''
print(S)
Output: hello Good morning Welcome
Raw Strings

 A raw string literal is preceded by r or R, which specifies that


escape sequences in the associated string are not translated.
The backslash character is left in the string:
>>> print('foo\nbar')
foo
bar
>>> print(r'foo\nbar')
foo\nbar
Raw strings don't treat the backslash as a special character at
all. Every character you put into a raw string stays the way
you wrote it:
print ('C:\\nowhere' )
This would print following result:
C:\nowhere
Now let's make use of raw string. We would put expression in
r'expression' as follows:
print (r'C:\\nowhere' )
This would print following result:
C:\\nowhere
String methods:

 string.upper()
 string.lower()
 string.strip()
rstrip()
lstrip()
 string.isdigit()
 string.find() : gives position of first occurrence of the string
passed
 string.split()
String Concatenation
 Concatenation means joining two or more strings together.
 To concatenate strings, we use + operator.
 When we work with numbers, + will be an operator for addition,
but when used with strings it is a joining operator.

Example:
s1 = “Hello”
s2 = “Good Morning!”
s3 = s1 + “ ” + s2
print(s3)

Output:
Hello Good Morning!
String repetition

 The * symbol used to represent multiplication, but when the


operand on the left side of the * is a list, it becomes the
repetition operator.
 The repetition operator makes multiple copies of a list and joins

them all together. Lists can be created using the repetition


operator, *.
Example:
 numbers = [1] * 5

 print(numbers)

Output: [1, 1, 1, 1, 1]
 n = [0, 1, 2] * 3

 print(n)

Output: [0, 1, 2, 0, 1, 2, 0, 1, 2]
Slicing Operator
 Slicing means pulling out a sequence of characters from a
string.
Syntax: s[x:y]
x denotes the start index of slicing
y denotes the end index. But Python ends slicing at y-1 index.
 String slicing can accept a third parameter also after the two

index numbers.
 The third parameter is called step value.

Syntax: s[start: end: step]


 Step value indicates how many characters to move forward

after the first character is retrieved from the string and it’s
default value is 1, but can be changed as per our choice.
String operations:
 A Python string is a sequence of characters and each character can be
accessed by its index either by forward indexing or by backward
indexing.

Example: subj=“Computer”
 subj[0]

 subj[0:3]

 subj[:4]

 subj[:]

To find a string exists in another string:


 ‘e’ in subj  returns True
len(): Returns length of the string passed as argument.
Syntax: len(string)

upper() : Returns a copy of calling string object with all letters converted to
uppercase.
Syntax: string.upper()

lower() : Returns a copy of calling string object with all letters converted to
lowercase.
Syntax: string.lower()

Example: S = "Bangalore"
print(len(S)); print(S.upper()); print(S.lower())
Output: 9
BANGALORE
bangalore
strip() : This method removes any whitespace from the beginning or the end
of the string.
str = " Mango "
str.strip()
 Output: 'Mango'

lstrip() : Removes the space on left hand side.


str.lstrip()
 Output: 'Mango '

rstrip() : Removes the space on right hand side.


str.rstrip()
 Output: ' Mango'

 We can define what we want to strip.


s = 'bbbb Mango bbbbb'
s.strip('b') # removes all ‘b’ and spaces at the end
 Output: ' Mango '
isdigit() : To check whether string is digit. To see what type of
value is there in a string.
x = 'hello'
x.isdigit()
 Output: False

y = '21321'
y.isdigit()
 Output: True

find() : Gives the position of the first occurrence of the specified


string. If specified string is not found it returns -1.
str = 'Hello Good morning have a nice day'
str.find('Good')
 Output: 6
split() : The split() method splits a string into a list. You can specify
the separator, default separator is any whitespace.
 It is used to count how many words are there in a document .

str = 'Hello Good morning have a nice day‘


str.split()
 Output:
['Hello', 'Good', 'morning', 'have', 'a', 'nice', 'day']

replace() : returns a copy of the string where all occurrences of a


substring are replaced with another substring. replace is a function
which is specifically defined only for strings.
s= "welcome"
s.replace('e','a',2)
Output: 'walcoma'
s = "Good morning and Good evening"
s.replace("Good", "Great",1)
Output: 'Great morning and Good evening‘

Syntax:
string.replace(oldvalue, newvalue, count)
 Count -A number specifying how many occurrences of the

old value you want to replace. Default is all occurrences.


Comparing Strings
 The built-in function ord() is used to return the UNICODE

(ASCII) value of the alphabet passed to it as an argument.


Example:
str1 = "Bangalore"
str2 = "Bhopal"
print(str1 == str2) ; print(str1 > str2); print(str1 == str1)
Output: False False True

 In str1 and str2 1st characters are compared, as they are equal
2nd characters are compared. Now h has a greater UNICODE
value than a so str2 is greater than str1 and so answer is False.
Comparison is vs. ==
a = "Hello"
b = 'Hello'
a==b
 True

a is b
 True

 == comparison compares the values of the two variables.

 The Equality operator (==) compares the values of both the operands and
checks for value equality.

 Whereas the 'is' (identity operator) operator checks whether both the operands
refer to the same object or not (present in the same memory location).
 To check the memory location we can use id() function returns an identity of
an object.
Question:
a = "abcdefghijklmnopqrstuvwxyz“
 a[3:15]

'defghijklmno‘
 a[3:15:3]

'dgjm‘
 a[3:15:-3]

‘‘
 a[15:3:-3]

'pmjg‘
 a[::-1]

'zyxwvutsrqponmlkjihgfedcba'
 a[::-3]

'zwtqnkheb‘
 a[15:3]

‘'
Question:

 list_1 = [1, 2]
 list_2 = [3, 4]
 list_3 = list_1 + list_2
 list_4 = list_3*3

 print(list_3)
[1, 2, 3, 4]

 print(list_4)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Question:
A list named colors contains 200 colors.
You need to slice the list to display every other color starting
with the second color.
Which code should you use?
 A. colors[1::2]

 B. colors[1:2]

 C. colors[2:2]

 D. colors[::2]
 Correct Answer: A
Question:
 You write the following code:
a='Configl'
print(a)
b=a
a + = Config2
print(a)
print(b)
 What is displayed after the first print?
Configl
 what is displayed after the second print?
ConfiglConfig2
 what is displayed after the third print?
Configl
Type Conversion
 The process of converting the value of one data type (like integer,
string, float etc.) to another data type is called Type Conversion.
 To get an input from users, you use the input() function.
 Since the input values are strings, you cannot apply the arithmetic
operator (+) to them.
 To solve this issue, you need to convert the strings to numbers before
performing calculations i.e., int(input())

 Type conversion functions

 int(str) – convert a string to a integer.


 float(str) – convert a string to a floating-point number.
 bool(val) – convert a value to a boolean value, either True or False.
 str(val) – return the string representation of a value.
Getting the type of a value
 To get the type of a value, you use the type(value) function.

Example:

>>> type(100)
<class 'int'>
>>> type(2.0)
<class 'float'>
>>> type('Hello')
<class 'str'>
>>> type(True)
<class 'bool'>
Question:
You are writing a function that returns the data type of the value that Is
passed in. You write the following code. Line numbers are included
for reference only.
01 def checkType(value):
02 dataType = type(value)
03 return dataType
04 print(checkType(True))
05 print(checkType(1.0))
06 print (checkType(1))
07 print(checkType("True"))

 Line 04 : <class'bool'>
 Line 05 : <class 'float'>
 Line 06 : <class'int'>
 Line 07 : <class'str'>
Question:
 You are writing a program that calculates a user’s year of birth. The
program asks users for their age and the current year, then outputs the
users year of birth, You write the following code.
 01 age = input(”Enter your age: “)
 02 year = input(”Enter the four digit year: “)
 03 born = eval(year) - eval(age)
 04 message = “You were born in "+ str(born)
 05 print(message)
 What data type is age in line 01?
 str
 what data type is born in line 03?
 int
 what data type is message in line 04?
 str
Question:
 You are creating a Python program that shows a congratulation message to
employees on their service anniversary. You need to calculate the number
of years of service and print a congratulatory message. You have written
the following code. Line numbers are included for reference only.

 01 Start = input(“How old were you on your start date?”)


 02 end = input(“How old are you today?" )
 03
 You need to complete the program. Which code should you use at line 03?
 A. print("congratulation on " + (int( end)-int(start )) + "years of service!")
 B. print("congratulation on" + str(int( end)-int(start )) + "years of
service!")
 C. print("congratulation on" + int( end-start ) + "years of service!")
 D. print("congratulation on" + str( end - int(start )) + "years of service!")
 Correct Answer: B
Question:
 Woodgrove Bank must generate a report that shows the average
balance for all customers each day. The report must truncate the
decimal portion of the balance.
 Which two code segments should you use? Each correct answer

presents a complete solution. Choose two.


A. average_ba1ance = total_deposits**number_of_customers

B. average_balance = int(total_deposits / number_of_customers)

C. average_balance = total_deposits // number_of_customers

D. average_balance = float(total_deposits//number_of_customers)
Answer: B, C
Format Function
 format() is technique of the string category permits to try and
do variable substitutions and data formatting. It enables to
concatenate parts of a string at desired intervals through point
data format.
 Formatters work by fixing one or a lot of replacement fields or
placeholders outlined by a pair of curly brackets “{}” — into a
string and calling the str.format() technique.
 Pass the format() method the value you wish to concatenate
with the string. This value will be printed in the same place
that your placeholder {} is positioned the moment you run the
program.
Single Formatter:
Single formatters can be defined as those where there is only one placeholder.

>>>print("today is {}".format('Monday'))
today is Monday

Multiple Formatter:
 Let’s say if there is another variable substitution required in a

sentence, this can be done by adding another set of curly brackets where we
want substitution and passing a second value into format().
 Python will then replace the placeholders by values that are passed as the

parameters.

>>>print("today is {} and its {}".format('Monday', 'raining'))


today is Monday and its raining
year = int(input("enter a year: "))
if(year % 4 == 0):
print(f"{year}, is a leap year")
else:
print(f"{year}, is not a leap year")
Output: enter a year: 2010
2010, is not a leap year
OR

year = int(input("enter a year: "))


if(year % 4 == 0):
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
Output: enter a year: 2020
2020 is a leap year
List:
 List is a container that holds many objects under a single name.
 List can be written as a list of comma-separated values (items)
between square brackets.
 List is a collection of arrays which is changeable and ordered.
 Lists are similar to arrays in C. One difference between them is that
all the items belonging to a list can be of different data type.
 They have indexes same as strings.
 Lists can be nested just like arrays, i.e., you can have a list of lists.
 Lists are mutable.
 Syntax:
List_name = [item1 , item2 , item3]
List_name = []
List_name[index]
list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
list2= [123, 'john']

Print(list1) # Prints complete list


print (list1[0] ) # Prints first element of the list
print (list1[1:3]) # Prints elements starting from 2nd till 3rd
print (list1[2:] ) # Prints elements starting from 3rd element
print (list2 * 2) # Prints list two times
print (list1 + list2) # Prints concatenated lists
list1[0]=7634 # Prints the new value 7634 in place of ‘abcd’
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
[7634, 786, 2.23, 'john', 70.2]
List predefined Methods:

list.append(‘item’) : adds item to the end


list.extend() : adds multiple items to the end of list
list.remove(‘item’) : removes first occurrence
list.insert(i , item) : adding single item at a index
list.sort() : sorts the list
list.pop(i) : remove the item at the given position
list.pop() : removes last item
list.index(‘item’) : gives index for first occurrence
list.clear() : removes all items from the list
list.count(item): return the no. of times item appeared in the list
list.reverse() : reverse the elements of the list in place
Example:
fruits = ['apple', 'banana', 'orange']
fruits.append('kiwi')
Output: ['apple', 'banana', 'orange', 'kiwi']
 append() function will add new element to the end of the string

fruits.append('apple')
Output: ['apple', 'banana', 'orange', 'kiwi', 'apple']

fruits.remove('apple')
Output: ['banana', 'orange', 'kiwi', 'apple']

 remove() function will remove the element from the beginning,


if the same element is repeated twice, the element at the
beginning of the list will be removed
fruits = ['banana', 'orange', 'kiwi', 'apple']
fruits.insert(2,'strawberry')
Output: ['banana', 'orange', 'strawberry', 'kiwi', 'apple']
 to add an element at a particular position use insert where we can

specify the index position where the element should be added

fruits.pop()
Output: 'apple‘
fruits.pop(2)
Output: 'strawberry‘
print(fruits)
Output: ['banana', 'orange', 'kiwi']
 pop will remove the last element by default, if we want to

remove particular element specify the index inside the pop


function
fruits = ['banana', 'orange', 'kiwi']
fruits.extend(['apple', 'strawberry'])
Output: ['banana', 'orange', 'kiwi', 'apple', 'strawberry']

 using append we can only add one element at a time to


append. but using extend function we can add multiple
elements at the same time
fruits.append(['apple', 'strawberry'])
Output: ['banana', 'orange', 'kiwi', ['apple', 'strawberry‘]]

fruits.count('banana')
Output: 1
 If item is not present count() will return 0.
 Functions which can be used in lists:

min(list)
max(list)
len(list)
sum(list)
Example:
L = [23,12,34,5,58,16,18]
len(L)
Output: 7

L.sort()
Output: [5, 12, 16, 18, 23, 34, 58]

L.sort(reverse=True)
Output: [58, 34, 23, 18, 16, 12, 5]

max(L)
Output: 58

min(L)
Output: 5
# nested list

l1=[1,2,3]
l2=[2,3,4]
l1.append(l2)
print(l1)
 Output: [1, 2, 3, [2, 3, 4]]

l1[3]
 Output: [2, 3, 4]

l1[3][2]
 Output: 4
Structure Code- Function And Method

 Methods are associated with the objects.


Example of string method:
fruit.lower()
# here, fruit is a string, lower converts the value to the object fruit
# lower is associated with the object fruit
fruit.upper()
fruit.swapcase()
fruit.capitalize()
fruit.strip()

 Functions are independent ,like example of adding two numbers.


It is not associated with any objects.
 We can pass any two numbers and we were getting results.
Difference between Python Methods vs Functions

 Methods are associated with the objects of the class they belong to.
 A method is called by its name but it is associated with an object

(dependent). It is implicitly passed to an object on which it is


invoked. It may or may not return any data. A method can operate the
data (instance variables) that is contained by the corresponding class.
 A Python method is a label that you can call on an object; it is a piece

of code to execute on that object.


class class_name :
def method_name():
…………
# method body
…………
 Functions are not associated with any object. We can invoke a function
just by its name. Functions operate on the data you pass to them as
arguments.
 A function can have different parameters or may not have any at all. If
any data (parameters) are passed, they are passed explicitly. It may or
may not return any data. The function does not deal with class and its
instance concept.
def function_name(arg1, arg2, ….):
………….. #function body …………..
Example: def Add(a,b):
return(a+b)
print(Add(50,70))
print(Add(150,50))
Output:
120
200
Tuple:
 A tuple is another sequence data type that is similar to the list.
 It is a collection of immutable objects.
 Tuple is ordered and cannot be changed.
 Duplicate values can be present.
 The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ), and their elements and
size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
 Tuples can be thought of as read-only lists.
 Tuples can be defined without brackets.
 Assign multiple values at a time.
t1 = ('abcd', 786 , 2.23, 'john', 70.2 )
t2 = (123, 'john')
print(t1) # Prints complete list
print(t1[0]) # Prints first element of the list
print(t1[1:3]) # Prints elements starting from 2nd till 3rd
print(t1[2:]) # Prints elements starting from 3rd element
print(t2 * 2) # Prints list two times
print(t1 + t2) # Prints concatenated lists
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john‘)
('abcd', 786, 2.23, 'john', 70.2, 123, 'john‘)
t1[0] = 7634

TypeError Traceback (most recent call last)


<ipython-input-103-33476bbf5b52> in <module> ----> 1
t1[0] = 7634
TypeError: 'tuple' object does not support item assignment

Only two methods are available in tuple : count and index

Example:
t = (1,2,3,2,1,2,4,5)
t.count(2)
Output: 3
t = (1,2,'hi')
t.index(1)
Output: 0
Dictionary:
 Dictionaries are enclosed by curly braces ( { } ) and values can
be assigned and accessed using square braces ( [] ).

 Dictionaries are unordered, changeable and can be indexed.

 Dictionary is a collection of key-value pairs.


Dictionary_name = {key1 : val1 , key2 : val2}

 Keys can be used as indexes and are unique but values in the
keys can be duplicate.
Example:
>>> camera = {'sony':200, 'nikon': 200}
>>> camera.update({'canon':500})
>>> print(camera)
Output: {'sony': 200, 'nikon': 200, 'canon': 500}
>>> camera['xyz'] = 1000
>>> print(camera)
Output: {'sony': 200, 'nikon': 200, 'canon': 750, 'xyz': 1000}
>>> camera.keys()
Output: dict_keys(['sony', 'nikon', 'canon', 'xyz'])
>>> camera.values()
Output: dict_values([200, 200, 750, 1000])
Sets:
 A set is an unordered collection with no duplicate elements.
 Basic uses include eliminating duplicate entries.
 Set object does not support indexing.
 Set objects also support mathematical operations like union,
intersection, difference, and symmetric difference.
 Curly braces or the built-in set() function can be used to create
sets.
 A set is mutable, but may not contain mutable items like a list,
set, or even a dictionary.
 A set may contain values of different types.
Set methods
 add(), clear(), discard(), pop(), remove(), and update().
More methods from a mathematical point of view:
union()
 performs the union operation on two or more Python sets, it

returns all the items that are in any of those sets.


intersection()
This method takes as argument sets, and returns the common
items in all the sets.

difference()
This method returns the difference of two or more sets.
symmetric_difference()
This method returns all the items that are unique to each set.

isdisjoint()
 This method returns True if two sets have a null intersection.

>>> {1,3,2}.isdisjoint({4,5,6})
Output:
True
issubset()
 This method returns true if the set in the argument contains this set.

>>> {1,2}.issubset({1,2,3})
Output
True

Membership operator

We can apply the ‘in’ and ‘not in’ python operators on items
for a set. This tells us whether they belong to the set.
>>> 'p' in {'a','p','p','l','e'}
Output
True
>>> 0 not in {'0','1'}
Output
True
Examples:
x = {12,3,4,45}
y = {2,4,6,78}

x.union(y)
{2, 3, 4, 6, 12, 45, 78}
x.intersection(y)
{4}
x.difference(y) # elements present in x but not in y
{3, 12, 45}
y.difference(x) # elements present in y but not in x
{2, 6, 78}
x.symmetric_difference(y) #returns unique elements in both
{2, 3, 6, 12, 45, 78}
Control Flow with Decisions
and Loops
Control Flow with Decisions and Loops (25-30%)

 Construct and analyze code segments that use


branching statements
if; elif; else; nested and compound conditional
expressions
 Construct and analyze code segments that perform

iteration
while; for; break; continue; pass; nested loops and
loops that include compound conditional
expressions
Branching statements
 Branching is a fundamental part of any programming. The
decision is taken based upon the action. This decision is
dependent on a condition.
Control Statements:
 Control statements are used to control the flow of execution

depending upon the specified condition/logic.


 There are three types of control statements.

1. Conditional Statements
2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)
Blocks of Code
 Lines of Python code can be grouped together in blocks.
You can tell when a block begins and ends from the
indentation of the lines of code.

 There are three rules for blocks.


 Blocks begin when the indentation increases.
 Blocks can contain other blocks.
 Blocks end when the indentation decreases to zero or to a
containing block’s indentation.
Conditional Statements
 It is used to control the flow of execution of program
depending upon the condition.
 Statements are executed only if a certain condition is met, else
it is skipped ahead to where the condition is satisfied.
 There are various types of conditional statements supported in
Python.
1. if
2. if-else
3. if-elif-else
Examples: These statements are always True
 If you don't ever water your plants, they die.

 If you jump in a lake, you get wet.

 If it gets below freezing, water turns into ice.

 If you stick your hand in a fire, it burns.


Example:
if raining:
print(“I will stay at home and watch movie”)
else:
print(“Go out for picnic”)
Output:
?????
Flowchart:
Syntax:

if <condition>:
Code block
elif <condition>:
Code block
else:
Code block
 An if statement is used to test a condition and execute certain
statements accordingly. A program can have many if statements.

 An else statement is used with an if statement. Else contains the block


of a code that is executed if the conditional expression in the 'if
statement' is FALSE.

 The elif statement is an “else if” statement that always follows an if or


another elif statement. The elif statement allows a number of
expression checks for TRUE and execute a block of code as soon as
one of the conditions returns TRUE.

 This means that if a condition is met, do something. Else go through


the remaining elif conditions and finally if no condition is met, execute
the else block. You can even have nested if-else statements inside the
if-else blocks.
Example:

>>>age = 25
>>>if age>=18:
>>> print("Adult")
>>>else:
>>> print("Minor")

Output:
Adult
>>>age = 2
>>>if age>=18:
>>> print("Adult")
>>>elif age<=2:
>>> print("Infant")
>>>else:
>>> print("Minor")

Output:
Infant
# Program to find largest of a number
>>>a = 50
>>>b = 55
>>>c = 58
>>>if a == b == c:
>>> print('They are equal' )
>>>elif a > b and a > c:
>>> print('a is largest' )
>>>elif b > a and b > c :
>>> print('b is largest' )
>>>else:
>>> print('c is largest')
Output:
c is largest
Example: Nested if conditions

>>>a = 14
>>>if a<=20:
>>> if a%2==0:
>>> print(" no. is even and it is less than 20")
>>> else:
>>> print("no. is odd and it is less than 20")
>>>else:
>>> print("no. is greater than 20")
Output:
no. is even and it is less than 20
Iteration Statements (Loops)
Loops allow us to execute a block of statements several times.
Loops can be of 2 kinds:
Finite: This loop works until a certain condition is met.
Infinite: This loop works infinitely and does not stop ever.

Loop test condition can be done either before or after the


statements :
Pre-Test Loop: Here, the condition is tested first and then
statements are executed subsequently.
Post-Test Loop: Here, the statement is executed at least once
and then the condition is checked.
Membership Operator

There are two membership operators.


 in

 not in

 Membership operators are operators used to validate the


membership of a value.
 It tests for membership in a sequence, such as strings, lists, or
tuples.
 The 'in' operator is used to check if a value exists in a
sequence or not.
For Loop
 This loop is used to execute a certain set of statements for a
given condition and continue until the condition has failed.
 It is used to access everything in list.

Syntax:
>>>for itemvariable in list_name:
# code block
 It is similar to range(a, b, c) > start, stop and step value

Syntax:
>>>for a in range(9):
print(“hello”)
Example:
>>>fruits= ['apple' ,'orange', 'pineapple', 'banana']
>>>for fruit in fruits:
>>> print(fruit, end=',')

for a in range(5):
print(a)

for i in range(2,10):
print(i)

for i in range(1,10,2):
print(i)
# Factorial program

>>>num = 6
>>>fact = 1
>>>for i in range(1,num+1):
>>> fact = fact*i
>>>print(fact)

Output:
720
While Loop
 This loop is used to iterate over a block of code or statements as
long as the test expression is true.
Syntax:
>>> while condition:
code block
Example:
>>>i=1
>>>while i<=10:
>>> print(i,end=',')
>>> i+=1
Output:
1,2,3,4,5,6,7,8,9,10,
# Factorial using while loop

>>>num = 6
>>>fact = 1
>>>i=1
>>>while i<=num:
>>> fact = fact*i
>>> i+=1
>>>print(fact)
Output:
720
# Sum of the digits of a number

num= int(input("enter num"))


res = 0
while(num>0):
rem = num % 10
res = res + rem
num = num//10
print(res)

Output:
enter num1234
10
Jump Statements (break, continue, pass)
Break
 Break clause is used to come out of the innermost loop

>>>for i in range(1,50):
>>> print(i)
>>> if i==5:
>>> break
Output:
1
2
3
4
5
Continue
 Continue makes the compiler run to the next iteration of the

loop. It will not break.


>>>for i in range(1,10):
>>> if i%2==0:
>>> continue
>>> print(i)
Output:
1
3
5
7
9
Pass
 Pass does nothing. Pass is like null statement
 It can be used when a statement is required syntactically but the
program requires no action.

>>>for i in range(1,10):
>>> if i%2==0:
>>> pass
>>> print( i,end=',')

Output:
123456789

Note: without pass statement we get an error.


IndentationError: expected an indented block
Example:

s = "welcome"
for i in s:
if i=='e':
break
print(i)

# Replace break by continue and pass. Observe the outputs in all


three cases
Question:
A classmate has asked you to debug the following code:

What is the output that is printed to the screen?


Options:

A. birthday, party, greeting, cake

B. party, greeting, birthday, cake

C. birthday, greeting, party, cake

D. party, birthday, birthday, cake

Answer: D
Functions
Document and Structure Code (15-20%)

 Document code segments using comments and


documentation strings
◦ use indentation, white space, comments, and
documentation strings; generate documentation by using
pydoc
 Construct and analyze code segments that include function
definitions
◦ call signatures; default values; return; def; pass
 A function is a reusable block of code that is used to
perform a specific action.
 In Python a function is some reusable code that takes
arguments(s) as input does some computation and then returns
a result.
 Functions "Encapsulate" a task i.e., they combine many
instructions into a single line of code. Functions are mostly a
part of a larger piece of code that solves the problem.
 Functions also increase the reusability of code. Values can be
passed to a function using variables – we call these parameters
or arguments.
Types of function:

1. Built-in Function: are provided as part of Python , there are


68 built-in functions.
 Example: int(), print(), sum() and so on

 Built in functions are those functions which are always

available for use. A function takes some input and produces an


output.

2. User-defined Function: Functions that we define ourselves


and then use. Here, def method is used to create a function.
 Once we have defined a function, we can call (or invoke) it as

many times as we like.


 How to define a function?
 The def method is used in python for defining function,
followed by function name, operation and the parameters
 Any input arguments need to be placed inside the parenthesis
while defining the function.

The code block within every function:


 Starts with colon (:)

 Follows indentation
General Syntax

# Let's define a function.


def function_name(parameter1,parameter2):
# Do whatever we want this function to do,
# using argument_1 and argument_2
function_name(argument_1, argument_2)
 def, tells Python that you are about to define a function.
 Give your function a name. A variable name tells you what kind of
value the variable contains; a function name should tell you what the
function does.
 Make sure the function definition line ends with a colon.
 Inside the function, write whatever code you need to make the
function do its work.
 To call your function, write its name followed by parentheses.
 Inside the parentheses, give the values you want the function to work
with.
Documentation string or Doc string
 It is first line in function
 for single line, use triple single quotes ''' '''
 for multiline, use triple double quotes """ """

Parameters:
 A parameter is a variable which we use in the function

definition that is a “handle” that allows the code in the function


to access the arguments for a particular function invocation.
Arguments:
 An argument is a value we pass into the function as its input

when we call the function


 We put the arguments in parenthesis after the name of the

function
 Example: with no arguments

def function1(): # Function definition


print("hello world!")

function1() # Calling a function

 Output:
hello world!
Example:
def add(): # add with no arguments
"""
(Docstring) This function takes no argument,
adds two numbers and prints the value
"""
a = int(input("enter no. a: "))
b = int(input("enter no. b: "))
c = a+b
print("result= ", c)

add()
Example: with arguments

def greet(first_name, last_name):


print(f" Hi {first_name} {last_name}")
#print using format function
print("Thank you")

greet("Guido", "van Rossum")

 Output:
Hi Guido van Rossum
Thank you

Note: A parameter is the input that we define for the function (here,
first_name and last_name are parameters)and argument is the actual value
for a given parameter.
def factorial(num):
import math
return math.factorial(num)
factorial(5)

 default argument - functions

def factorial(num=5):
import math
return math.factorial(num)
factorial()

## here we are calling function without argument. Here, argument


value is mentioned while defining function, num=5
def factorial(num=5):
import math
return math.factorial(num)

factorial(8)

Note: if we pass a argument (value) while calling, it will take


this number into consideration. num = 8 will be taken instead
of 5
 Function to add two numbers

def add(a=5, b=10):


return a+b
add(20,30)

def add(a=5, b=10):


return a+b
add(20) # 20 will be going to a

def add(a=5, b=10):


return a+b
add(b=40) # b value will replaced
In programming there are two types of functions:
1. Function, which perform a task
2. Function, which return a value
 return statement prints the result in the terminal
 *args : used to create a function that takes variable number
of arguments
 """ def (* ): Function body """
 As we can observe , to create a function with variable length
arguments we simply prefix the argument name with an
asterisk.

Example:
def addnos(*a):

 The function addnos() can now be called with as many number


of arguments as we want and all the arguments will be stored
inside the argument a which will be internally treated as tuple.
Example:

def product(*numbers):
total = 1
for number in numbers:
total *= number #augmented assignment operator
return total

print(product(4,5,6,7)) # passing arbitrary arguments

Output:
840
Example:
def addnos(*a):
sum =0
for x in a:
sum=sum+x
return sum
print(addnos(10,20))
print(addnos(10,20,30))
print(addnos(12,23,54,5645,5445,5465,43,234))

Output:
30
60
16921
**args : used to pass multiple key-word arguments or key-value
pair  python will automatically package them into dictionary
Example: function to save information about user
def save_user(**user):
print(user)
save_user(id=1445, name="John", age=22)
# passing arbitrary key-word arguments i.e., name =value

Output:
{'id': 1445, 'name': 'John', 'age': 22}

Note: the user object created , {'id': 1445, 'name': 'John', 'age': 22} in
the above example is called dictionary
 local and global variable
var = 123
def modify():
var = 5
var = var * 2
return var

modify()
Output: 10
# within modify the value of var = 5, is called local variable
var
Output: 123
# if i call value of var outside the modify function it takes the value
of var=123, global variable
QUESTION
You develop a Python application for your company..
You have the following code. Line numbers are included for reference only.

Use the drop-down menus to select the answer choice that answers each
question based on the information presented in the code segment.
Documentation generation using the pydoc module in Python

 pydoc module automatically generates documentation from


Python modules. The documentation can be saved as pages of
text on the console, displayed on the web browser, or even as
HTML files.
 To access pydoc import it using import pydoc
 The pydoc module comes packaged along with Python, which
means you don’t have to download and install it separately.
 You can access the interactive shell in pydoc using it’s help
function.
 To do this, launch your terminal, and enter the python interactive
shell.
 Now, import pydoc and then use the pydoc.help() command to
launch the interactive shell.
Accessing interactive shell using help() function

Now, enter name of the module, datatype, function, classes,


etc., to obtain its documentation from interactive script.
Viewing documentation from the browser

 We can view the documentation from the browser easily using


pydoc.
 This time, you need not run the command through python
shell. Rather you can provide arguments and launch it directly.
 To do so, launch your terminal and type the below command.
 python −m pydoc −b
 This should generate documentation for all the python
modules, functions, objects present on your local system on
the browser.
Exception Handling
Perform Troubleshooting and Error Handling (5-10%)

 Analyze, detect, and fix code segments that have errors


syntax errors; logic errors; runtime errors

 Analyze & construct code segments that handle


exceptions
try; except; else; finally; raise
Exception
 Exception are errors that occur at runtime.
 If our program encounters an abnormal situation

during it’s execution it raises an exception.


Example: a=10/0
will generate an exception because python cannot solve
division by 0.
 When an exception occurs:
◦ Python immediately terminates the code
◦ Python displays the error message related to the exception
Sample code:
a=int(input("Enter first no:"))
b=int(input("Enter second no:"))
c=a/b
print("Division is: ",c)
d=a + b
print("Sum is: ",d)
Output 1:
Enter first no:12
Enter second no:2
Division is 6.0
Sum is 14
Output 2:

In the output 2, the code generated exception because Python does not
know how to handle division by 0. Also, code did not even calculated
the sum of 2 and 0 which is possible.
How to handle errors?
 If we want our program to behave normally, even if
an exception occurs, then we have to apply Exception
Handling.

 Exception handling is a mechanism which allows us


to handle errors gracefully while the program is
running instead of abruptly ending the program
execution.
Exception Handling Keywords
Python provides 5 keywords to perform Exception
Handling:
 try
 except
 else
 raise
 finally
Exception Handling Syntax
try:
# do your operations here
except Exceptional1:
# If there is Exception-1, then execute this block.
except Exceptional2:
# If there is Exception-2, then execute this block
else:
# If there is no exception then execute this block

Note: In place of Exception1 and Exception2, use the


names of Exception classes in Python.
Syntax:
try:
code block
except exception_name(optional):
code block
else: (optional)
code block
finally:
code block
 The try block lets you test a block of code for errors.

 The except block lets you handle the error.


 The finally block lets you execute code, regardless of the result

of the try and except blocks. If we have a code which we want to


run in all situations then we write code inside the finally block.
Sample code with exception:

a=int(input("Enter first no:"))


b=int(input("Enter second no:"))
try:
c=a/b
print("Division is",c)
except ZeroDivisionError:
print("Denominator should not be 0")
d=a + b
print("Sum is",d)
Output 1:
Enter first no:4
Enter second no:0
Denominator should not be 0
Sum is 4

Output 2:
Enter first no:8
Enter second no:3
Division is 2.6666666666666665
Sum is 11
Exception Classes
Exception Class Description
Exception Base class for all exceptions
ArithmeticError Raised when numeric calculations fails
FloatingPointError Raised when floating point calculation
fails
ZeroDivisionError Raised when division or modulo by zero
takes place for all numeric types
OverflowError Raised when result of an arithmetic
operation is too large to be represented
ImportError Raised when the imported module is not
found in Python version <3.6
ModuleNotFoundError Raised when the imported module is not
found from Python version >=3.6
Exception Class Description
KeyError Raised when specified key is not found in
the dictionary
IndexError Raised when index of a sequence is out of
range
NameError Raised when an identifier is not found in
the local or global namespace
UnboundLocalError Raised when we use a local variable in a
function before declaring it
TypeError Raised when a function or operation is
applied to an object of incorrect type
ValueError Raised when a function gets argument of
correct type but improper value
Exception Class Description
FileNotFoundError Raised when a file is not present
FileExistsError Raised when we try to create a
directory which is already present
SyntaxError Raised when there is an error in
Python syntax
IndentationError Raised when indentation is not
specified properly
Note:
 Amongst all the exceptions in the previous slides, we cannot
handle SyntaxError exception, because it is raised by Python
even before the program starts execution.
Example:
a=int(input("Enter first no:"))
b=int(input("Enter second no:"))
try:
c=a/b
print("Div is",c))
except SyntaxError:
print("Wrong Syntax")
d=a + b
print("Sum is",d)
Handling Multiple Exception
 A try statement may have more than one except
clause for different exceptions.
 But at most one except clause will be executed
import math
try:
x=10/5
print(x)
ans=math.exp(3)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")

Output:
2.0
20.085536923187668

 The exp() function in Python allows users to calculate the exponential value with
the base set to e. Note: e is a Mathematical constant, with a value approximately
equal to 2.71828.
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Division by 0 exception occurred!
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Numeric calculation failed!
Handling all Exceptions
 We can write the keyword except without any
exception clause name also.
 In this case for every exception this except clause

will run.
 Here, the only problem will be that we will never

know the type of exception that has occurred.


Example-1 :

while(True):
try:
a = int(input("Enter first no.:"))
b = int(input("Enter second no.:"))
c = a/b
print("Division is:",c)
except:
print("Some problem occurred.. Try again")
# Example 2:
try:
a=5
b = int(input('enter the value'))
c = a/b
print(c)
except: # except block will run if there is an error
print('There is an error')
else: # if exception does not occur, it will run else block
print('no error')
finally: # finally block will run irrespective of error
print('program completed')
Output1:
enter the value2
2.5
no error
program completed

Output2:
enter the value0
There is an error
program completed
Exercise for practice:
 Write a program to ask the user to input 2 integers
and calculate and print their division. Your program
should behave as follows:
- If user enters a non integer value then ask him to
enter only integers
- If denominator is 0, then ask him to input non-zero
denominator
- Repeat the process until correct input is given
 Only if the inputs are correct then display their

division and terminate the code


Solution:

while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
Single except Multiple Exception
 If we want to write a single except clause to handle
multiple exceptions:
◦ We have to write names of all the exceptions within
parenthesis separated with comma after the keyword except
Example:
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except (ValueError, ZeroDivisionError ):
print("Either input is incorrect or denominator is
0… Try again!!!")
Raising an Exception
 We can force Python to generate an Exception using
the keyword raise.
 This is normally done in those situations where we

want Python to throw an exception in a particular


condition of our choice.

 Syntax:
raise ExceptionClassName
raise ExceptionClassName(message)
Example:
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
if a<=0 or b<0:
raise Exception("Negative numbers not allowed! Try again")
c=a/b
print("Div is ",c)
break
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
except Exception as e:
print(e)
Output:
Input first no:3
Input second no:-1
Negative numbers not allowed! Try again

Input first no:2


Input second no:0
Please input non-zero denominator

Input first no:5


Input second no:7
Div is 0.7142857142857143
Question:
 For each of the following statement ,select Yes if the statement
is true. Otherwise, select No.
 Answer Area
 A try statement can have one or more except clauses.
Yes
 A try statement can have a finally clause without an except
Clause.
Yes
 A try statement can have a finally clause and an except clause.
Yes
 A try statement can have one or more finally clauses
No
Perform Input and Output
Operations
Perform Input and Output Operations (20-25%)

 Construct and analyze code segments that perform file


input and output operations
◦ open; close; read; write; append; check existence; delete;
with statement

 Construct and analyze code segments that perform console


input and output operations
◦ read input from console; print formatted text; use of
command line arguments
File Handling
 File handling is a mechanism by which we can read data of disk files
in python program or write back data from python program to disk
files.
 File handling allows us to store data entered through python program
permanently in disk file and later we can read data back.
 Data files can be stored in 2 ways:
1. Text file: Stores information as a character. If data is “hello” it will
take 5 bytes and if data is floating value 12.45 it will take 5 bytes.
Each line is terminated by special character called EOL(‘\n’ or ‘\r’ or
combination of both.
2. Binary file: Data is stored according to its data type and hence no
translation occurs. It stores the information in the same format as in the
memory.
‘b’ appended to the mode opens the file in binary mode.
File input and output operations:
 To perform operation on file we have to perform the following

steps:
 Open file

 Use file to Read or Write

 Close file

Syntax:
Filevariable = open(filename, mode)
# Do read and write operations
Filevariable.close()
File - Modes
 ‘r’ : Default option. Used when the file will only be read
 ‘w’: used for only writing- an existing file with same name
will be erased.
 ‘a’: opens the file for appending. Data written to the file is
added to the end
 ‘a+’: same as ‘a’ but file position is at the beginning
 ‘r+’: opens the file for both reading and writing
 ‘w+’: opens for read and writing. Create files if does not exists
otherwise truncate
 ‘x’: creates a new file and open for writing
File- Read Methods
 read()
read is used to print the entire contents of file at a time
 readline()
The readline method reads one line from the file and returns it as
a string
 readlines()
The readlines method returns the contents of the entire file as a
list of strings, where each item in the list represents one line of
the file.
 seek(offset)
move cursor back to whichever position we want.
 tell()
determines current position of the file.
Perform Operations Using Modules and Tools (1-5%)

 Perform basic operations using built-in modules


◦ math;
◦ datetime;
◦ io; sys; os;
◦ os.path;
◦ random
 Solve complex computing problems by using built-in
modules
◦ math; datetime; random
 In Python, Modules are simply files with the “. py”
extension containing Python code that can be imported
inside another Python Program.
 Package consists of multiple modules inside it.
 There are several built-in modules in Python, which you can
import whenever you like.
 You can create an alias when you import a module, by using
the as keyword.
 You can choose to import only parts from a module, by using
the from keyword.
 from modname import * Example: from math import pi
 import modname Example: import math

Note: All the functions and constants can be imported using *


Math Module

 The most popular mathematical functions are defined in the


math module. These include trigonometric functions,
representation functions, logarithmic functions, angle
conversion functions, etc.
 In addition, two mathematical constants are also defined in

this module.
 Pi is a well-known mathematical constant and its value is

3.141592653589793.
Example: Getting Pi Value
import math
math.pi
Output: 3.141592653589793
 Another well-known mathematical constant defined in the
math module is e. It is called Euler's number and it is a base
of the natural logarithm. Its value is 2.718281828459045.
Example: e Value
import math
math.e
Output: 2.718281828459045

Note:
 dir() is a powerful inbuilt function in Python3, which

returns list of the attributes and methods of any object (say


functions , modules, strings, lists, dictionaries etc.)
Math functions
Example:
import math
x = math.sqrt(64)
y = math.ceil(1.4)
z = math.floor(1.4)

Output:
print(x) # returns 8
print(y) # returns 2
print(z) # returns 1
Question:
 You are creating a function that manipulates a number. The
function has the following requirements:
• A float is passed into the function
• The function must take the absolute value of the float
• Any decimal points after the integer must be removed
 Which two math functions should you use? Each correct answer is
part of the solution. Choose two.

A. Math.fmod(x)
B. Math.frexp(x)
C. Math.floor(x)
D. Math.ceil(x)
E. Math.fabs(x)
Answer: C , E
Question:
 You are writing an application that uses the sqrt function. The
program must reference the function using the name
squareRoot.
 You need to import the function. Which code segment should
you use?

A. import math.sqrt as squareRoot


B. import sqrt from math as squareRoot
C. from math import sqrt as squareRoot
D. from math.sqrt as squareRoot

Answer: C
Time

 The Python time module provides many ways of representing


time in code, such as objects, numbers, and strings.
 It also provides functionality other than representing time, like
waiting during code execution and measuring the efficiency of
your code.

Example:
 import time

 print(time.time())

Output:
 1639031471.9046035

 time.time() returns the number of seconds that have passed since the

epoch. The beginning of time is started measuring from 1 January,


12:00 am, 1970 and this very time is termed as “epoch” in Python.
Example:
import datetime
currentTime = datetime.datetime.now()
print(currentTime)
print(currentTime.hour)
print(currentTime.minute)
print(currentTime.second)

Output:
2021-12-09 12:15:41.587108
12
15
41
Datetime

 The datetime module has many methods to return information


about the date object.
 The date contains year, month, day, hour, minute, second, and

microsecond.
Example:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))

Output:
2021
Thursday
 strftime allows you to specify the date format
 print(currentDate.strftime('%d %b, %Y'))

◦ %d is the day of the month


◦ %b is the abbreviation for the month
◦ %Y is the 4 digit year
◦ %B is the full month name
◦ %y is 2 digit year
◦ %a is the day of the week abbreviated
◦ %A is the day of the week
Example:
Question:

 You write the following code:


You run the program.

import datetime
d = datetime.datetime(2017,4,7)
print('{:%B-%d-%y}'.format(d))
num=1234567.890
print('{:,.4f}'.format(num))

 What is the output?


A. Apr-07-2017
1,234,567.8900

B. April-07-17
1,234,567.8900

C. April-07-17
1234567.89

D. 2017-ApriI-07
1,234,567.890

Answer: B
Random
 The random module is a built-in module to generate the
pseudo-random variables.
 It can be used perform some action randomly such as to get a
random number, selecting a random elements from a list,
shuffle elements randomly, etc.

Generate Random Floats


 random.random() method returns a random float number

between 0.0 to 1.0. The function doesn't need any arguments.


Example: import random
random.random()
Output: 0.645173684807533
Generate Random Integers

 The random.randint() method returns a random integer


between the specified integers.

Example: # randint()  inclusive range,


# Both values are inclusive
import random
random.randint(1, 100)
Output: 95
random.randint(1, 100)
Output: 49
Generate Random Numbers within Range

 random.randrange() method returns a randomly selected element


from the range created by the start, stop and step arguments.
 The value of start is 0 by default.

 The value of step is 1 by default.

Example:
random.randrange(1, 10)
Output: 2
random.randrange(1, 10, 2)
Output: 5
random.randrange(0, 101, 10)
Output: 80
shuffle()
Example:
from random import *
fruits = ['mango', 'cherry', 'orange', 'apple']
shuffle(fruits) # used to shuffle the list
print(fruits)
Output: ['cherry', 'orange', 'apple', 'mango']
sample()
Example:
fruits = ['mango', 'cherry', 'orange', 'apple']
print(sample(fruits,2)) # to pick 2 samples from fruits
randomly
Output: ['mango', 'cherry']
Question:

 You need to write code that generates a random number that


meets the following requirements:

• The number is a multiple of 5.


• The lowest number is 5.
• The highest number is 100.

 Which two code segments will meet the requirements? Each


correct answer presents a complete solution. Choose two.

Note: In randint both numbers are inclusive


In randrange number start is inclusive , stop is exclusive
A. from random import randrange
print(randrange(5, 105, 5))

B. from random import randrange


print(randrange(0, 100, 5))

C. from random import randint


print(randint(0, 20)*5)

D. from random import randint


print(randint(1, 20)*5)
Answer: A, D
Question:

 You need to write code that generates a random float with a


minimum value of 0.0 and a maximum value of 1.0. Which
statement should you use?
 Answer Area

A. rando.randrange(0.0, 1.0)
B. random.randrange()
C. random.random()
D. random.randint(O, 1)

Answer: C
Question:

 You are writing code that generates a random integer with


a minimum value of 5 and a maximum value of 11.
 Which two functions should you use? Each correct
answer presents a complete solution. Choose two.

A. random.randint(5,12)
B. random.randint(5,11)
C. random.randrange(5,12,1)
D. random.randrange(5,11,1)

Answer: B,C
os and os.path package

 The OS module in Python provides functions for interacting


with the operating system.

 import os
 import os.path

 os.path.isfile('filename.txt')
# used to check if file exists etc
 os.path.getsize('filname.txt')
# Gives size of file
 os.remove('filename.txt')
# used to remove the file
Printing to the Screen
#!/usr/bin/python

print "Python is really a great language,", "isn't


it?“

Output
Python is really a great language, isn't it?
Reading Keyboard Input

 Python provides two built-in functions to


read a line of text from standard input, which
by default comes from the keyboard
◦ raw_input
◦ Input
The raw_input Function

Syntax:
raw_input([prompt])

reads one line from standard input and returns


it as a string
The raw_input Function

#!/usr/bin/python
str = raw_input("Enter your input: ")
print "Received input is : ", str

Output:
Enter your input: Hello Python Received input is : Hello
Python
The input Function

Syntax:
input([prompt])

equivalent to raw_input, except that it assumes


the input is a valid Python expression and
returns the evaluated result
The input Function
#!/usr/bin/python

str = input("Enter your input: ")


print "Received input is : ", str

Output:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Opening and Closing Files
The open Function
Syntax:
file object = open(file_name [, access_mode][, buffering])

 file_name − The file_name argument is a string value that contains


the name of the file that you want to access.
 access_mode − The access_mode determines the mode in which
the file has to be opened, i.e., read, write, append, etc. A complete
list of possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).
 buffering − If the buffering value is set to 0, no buffering takes
place. If the buffering value is 1, line buffering is performed while
accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system
default(default behavior).
Different modes of opening a file

Sr.No. Modes & Description


1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default
mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
Different modes of opening a file
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for writing.
10 ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.

11 a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in
the append mode. If the file does not exist, it creates a new file for reading and writing.

12 ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
The file Object Attributes
Sr.No. Attribute & Description
1 file.closed
Returns true if file is closed, false otherwise.
2 file.mode
Returns access mode with which file was opened.
3 file.name
Returns name of the file.
4 file.softspace
Returns false if space explicitly required with print, true otherwise.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
 The close() method of a file object flushes any
unwritten information and closes the file
object, after which no more writing can be
done.
 Python automatically closes a file when the

reference object of a file is reassigned to


another file. It is a good practice to use the
close() method to close a file.
Syntax:
fileObject.close()
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

OutPut:
Name of the file: foo.txt
Reading and Writing Files
The write() Method
 The write() method writes any string to an
open file. It is important to note that Python
strings can have binary data and not just text.
 The write() method does not add a newline

character ('\n') to the end of the string

Syntax:
fileObject.write(string)
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its
great!!\n")
# Close opend file
fo.close()

Output:
Python is a great language.
Yeah its great!!
The read() Method
 The read() method reads a string from an
open file. It is important to note that Python
strings can have binary data. apart from text
data.

Syntax
fileObject.read([count])
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

Output
Read String is : Python is
File Positions
tell()
tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the
beginning of the file.

seek(offset[, from])
changes the current file position. The offset argument indicates
the number of bytes to be moved. The from argument specifies
the reference position from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the


reference position and 1 means use the current position as the
reference position and if it is set to 2 then the end of the file
would be taken as the reference position.
#!/usr/bin/python
# Open a file

fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position


position = fo.tell() print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10) print "Again read String is : ", str

# Close opend file


fo.close()
Output

Read String is : Python is


Current file position : 10
Again read String is : Python is
Renaming and Deleting Files
 Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.

 To use this module you need to import it first


and then you can call any related functions.
The rename() Method

Syntax
os.rename(current_file_name, new_file_name)
#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )
The remove() Method
 You can use the remove() method to delete
files by supplying the name of the file to be
deleted as the argument.

Syntax:
os.remove(file_name)
#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")
Python - Object Oriented
Overview of OOP Terminology

 Python has been an object-oriented language


since it existed.
 Creating and using classes and objects are

downright easy.
 Class: A user-defined prototype for an object that defines a
set of attributes that characterize any object of the class. The
attributes are data members and methods.
 Class variable − A variable that is shared by all instances of a
class. Class variables are defined within a class but outside
any of the class's methods.
 Data member − A class variable or instance variable that
holds data associated with a class and its objects.
 Function overloading − The assignment of more than one
behavior to a particular function. The operation performed
varies by the types of objects or arguments involved.
 Instance variable − A variable that is defined inside a method
and belongs only to the current instance of a class.
 Inheritance − The transfer of the characteristics of a class to
other classes that are derived from it.
 Instance − An individual object of a certain class. An object
obj that belongs to a class Circle, for example, is an instance
of the class Circle.
 Instantiation − The creation of an instance of a class.
 Method − A special kind of function that is defined in a class
definition.
 Object − A unique instance of a data structure that's defined
by its class. An object comprises both data members and
methods.
 Operator overloading − The assignment of more than one
function to a particular operator.
Creating Classes
 class statement creates a new class definition
 class immediately follows the
keyword class followed by a colon

class ClassName:
'Optional class documentation string'
class_suite
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
 variable empCount is a class variable whose value is shared among all instances

of a this class.
 This can be accessed as Employee.empCount from inside the class or outside

the class.
 The first method __init__() is a special method, which is called class constructor

or initialization method that Python calls


 You declare other class methods like normal functions with the exception that

the first argument to each method is self.


 Python adds the self argument to the list for you; you do not need to include it

when you call the methods.


Creating Instance Objects
 you call the class using class name and pass
in whatever arguments its __init__ method
accepts.

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing Attributes
 access the object's attributes using the dot
operator with object.
 Class variable would be accessed using class

name

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


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

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

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

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Output
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
Other functions to access attributes

 __dict__ − Dictionary containing the class's namespace.


 __doc__ − Class documentation string or none, if undefined.
 __name__ − Class name.
 __module__ − Module name in which the class is defined.
This attribute is "__main__" in interactive mode.
 __bases__ − A possibly empty tuple containing the base
classes, in the order of their occurrence in the base class list.
class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


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

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

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

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
Output

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Destroying Objects (Garbage
Collection)
 Python deletes unneeded objects (built-in types or class instances)
automatically to free the memory space.
 The process by which Python periodically reclaims blocks of memory
that no longer are in use is termed Garbage Collection.
 Python's garbage collector runs during program execution and is
triggered when an object's reference count reaches zero.

a = 40 # Create object <40>


b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"

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

Output:
3083401324 3083401324 3083401324
Point destroyed
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it
from a preexisting class by listing the parent class in parentheses after
the new class name.
 child class inherits the attributes of its parent class

 can use those attributes as if they were defined in the child class

 A child class can also override data members and methods from the

parent

Syntax
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"

def parentMethod(self):
print 'Calling parent method'

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class


def __init__(self):
print "Calling child constructor"

def childMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
Output:

Calling child constructor


Calling child method
Calling parent method
Parent attribute : 200

you can drive a class from multiple parent classes as follows −

class A: # define your class A


.....

class B: # define your class B


.....

class C(A, B): # subclass of A and B


.....
 The issubclass(sub, sup) boolean function returns
true if the given subclass sub is indeed a subclass
of the superclass sup.

 The isinstance(obj, Class) boolean function returns


true if obj is an instance of class Class or is an
instance of a subclass of Class
Overriding Methods
 can always override your parent class methods.

 One reason for overriding parent's methods is


because you may want special or different
functionality in your subclass.
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method

Output:

Calling child method


Base Overloading Methods
Sr.No. Method, Description & Sample Call
1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
 Suppose you have created a Vector class to
represent two-dimensional vectors, what
happens when you use the plus operator to
add them?

 define the __add__ method in your class to


perform vector addition and then the plus
operator would behave as per expectation
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2

Output:

Vector(7,8)
Data Hiding
 An object's attributes may or may not be
visible outside the class definition.

 You need to name attributes with a double


underscore prefix, and those attributes then
are not be directly visible to outsiders.
class JustCounter:
__secretCount = 0

def count(self):
self.__secretCount += 1
print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

Output:
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python - MySQL Database
Access
 Python standard for database interfaces is the Python DB-API.
 choose the right database for your application.

Python Database API supports a wide range of database servers


 GadFly

 mSQL

 MySQL

 PostgreSQL

 Microsoft SQL Server 2000

 Informix

 Interbase

 Oracle

 Sybase
 The DB API provides a minimal standard for working with databases
using Python structures and syntax wherever possible.

This API includes the following


 Importing the API module.

 Acquiring a connection with the database.

 Issuing SQL statements and stored procedures.

 Closing the connection


What is MySQLdb?
 MySQLdb is an interface for connecting to a
MySQL database server from Python.

 It implements the Python Database API v2.0


and is built on top of the MySQL C API.
How do I Install MySQLdb?
 make sure you have MySQLdb installed on
your machine.

import MySQLdb

Error:
Traceback (most recent call last): File "test.py",
line 3, in <module> import MySQLdb
ImportError: No module named MySQLdb
To install MySQLdb module
 For Ubuntu, use the following command –
 $ sudo apt-get install python-pip python-dev libmysqlclient-
dev

 For Fedora, use the following command -


 $ sudo dnf install python python-devel mysql-devel redhat-
rpm-config gcc

 For Python command prompt, use the following command -


 pip install MySQL-python
Database Connection
 You have created a database TESTDB.

 You have created a table EMPLOYEE in TESTDB.

 This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and


INCOME.

 User ID "testuser" and password "test123" are set to access


TESTDB.

 Python module MySQLdb is installed properly on your machine.

 You have gone through MySQL tutorial to understand MySQL


Basics
import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()
print "Database version : %s " % data

# disconnect from server


db.close()

Output:

Database version : 5.0.45


Creating Database Table
 Once a database connection is established,
we are ready to create tables or records into
the database tables using execute method of
the created cursor.
Let us create Database table EMPLOYEE −

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement


sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""

cursor.execute(sql)

# disconnect from server


db.close()
INSERT Operation
 It is required when you want to create your records into a database
table.
The following example, executes SQL INSERT statement to create a record into EMPLOYEE table
import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Previous example can be written as follows to create SQL queries dynamically −

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Output:

..................................
user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \


(user_id, password))
..................................
READ Operation
 READ Operation on any database means to fetch
some useful information from the database.

 fetchone() − It fetches the next row of a query result set. A result


set is an object that is returned when a cursor object is used to
query a table.

 fetchall() − It fetches all the rows in a result set. If some rows


have already been extracted from the result set, then it retrieves
the remaining rows from the result set.

 rowcount − This is a read-only attribute and returns the number


of rows that were affected by an execute() method.
The following procedure queries all the records from EMPLOYEE table having salary more than 1000 −

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

sql = "SELECT * FROM EMPLOYEE \


WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"

# disconnect from server


db.close()
 Output

fname=Mac, lname=Mohan, age=20, sex=M,


income=2000
Update Operation
 UPDATE Operation on any database means to
update one or more records, which are
already available in the database.
 The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of
all the males by one year.

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
DELETE Operation
 DELETE operation is required when you want
to delete some records from your database.
Following is the procedure to delete all the records from EMPLOYEE where AGE is more than
20 −

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to DELETE required records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Performing Transactions
 Transactions are a mechanism that ensures data consistency.

 Atomicity − Either a transaction completes or nothing


happens at all.

 Consistency − A transaction must start in a consistent state


and leave the system in a consistent state.

 Isolation − Intermediate results of a transaction are not


visible outside the current transaction.

 Durability − Once a transaction was committed, the effects


are persistent, even after a system failure.
COMMIT Operation

Commit is the operation, which gives a green signal to database to finalize


the changes, and after this operation, no change can be reverted back.

db.commit()

ROLLBACK Operation

If you are not satisfied with one or more of the changes and you want to
revert back those changes completely, then use rollback() method.

db.rollback()

Disconnecting Database

To disconnect Database connection, use close() method.

db.close()
Handling Errors
Sr.No. Exception & Description
1 Warning
Used for non-fatal issues. Must subclass StandardError.
2 Error
Base class for errors. Must subclass StandardError.
3 InterfaceError
Used for errors in the database module, not the database itself. Must subclass Error.
4 DatabaseError
Used for errors in the database. Must subclass Error.
5 DataError
Subclass of DatabaseError that refers to errors in the data.
6 OperationalError
Subclass of DatabaseError that refers to errors such as the loss of a connection to the database.
These errors are generally outside of the control of the Python scripter.
7 IntegrityError
Subclass of DatabaseError for situations that would damage the relational integrity, such as
uniqueness constraints or foreign keys.
8 InternalError
Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no
longer being active.
9 ProgrammingError
Subclass of DatabaseError that refers to errors such as a bad table name and other things that can
safely be blamed on you.
10 NotSupportedError
Subclass of DatabaseError that refers to trying to call unsupported functionality.

You might also like