Pyt 1
Pyt 1
PYTHONPATH
PYTHONSTARTUP
PYTHONCASEOK
PYTHONHOME
Running PYTHON:
Interactive Translator
Python may be run on Unix, DOS, or any other operating system that has a command-line
interpreter or shell window.
$python # Unix/Linux
or
python%# Unix/Linux
or
or
or
You can also run Python from a Graphical User Interface (GUI) environment if you have a
GUI programme that supports Python on your system.
Python for Windows – PythonWin is the first Python interface for Windows, and it’s an IDE
with a graphical user interface.
Python Identifiers:
A Python identifier is a name that is used to identify a variable, function, class, module, or
another object in Python. An identifier actually begins with a letter from A to Z, or a to z, or
an underscore (_), followed by zero or more letters, underscores, or numbers (0 to 9).
In identifiers, punctuation marks like @, %, and $ are not accepted. Python is a programming
language that is case sensitive. As a consequence, in Python, ‘manpower’ and ‘Manpower’
are 2 distinct identifiers.
The name of the class begins with a capital letter. The commencement of all other
identifiers is a lowercase letter.
The idea of a single leading underscore in an identifier signifies that it is private.
An identification that begins with two leading underscores is considered to be very
secret.
The identifier is a language-defined special name if it also ends with two trailing
underscores.
Reserved Words:
The Python keywords are shown in the table below. You can’t use these terms as constants,
variables, or any other identifier names since they’re reserved. Only lowercase characters
appear in the Python keywords. Examples- and, exec, assert, break, finally, for, or, pass,
class, from, print, continue, global.
There are no braces in Python to indicate code blocks for class and function entries or flow
control. Line indentation, which is rigorously enforced, is used to denote code blocks.
The indentation could be any number of spaces, however, all statements in the block should
be indented the same amount. For instance,
if True:
print “True”
else:
print “false”
if True:
print “Answer”
print “True”
else:
print “Answer”
print “False”
Data types:
1. Numbers: Numeric values are stored using the Number data type.
2. String: The string data type is used to record a character sequence.
3. Tuple is an immutable data type that is used to hold a collection of multiple data kinds
of items.
4. List: The list data type is mutable and is used to hold a collection of distinct data
kinds of components.
5. Set: The set data type is used to hold a variety of element data types; it is changeable
and stores unique elements.
6. Dictionary: The dictionary data type is used to hold a collection of distinct data kinds
of components as key-value pairs. It is changeable and stores a unique key.
Code block:
In Python, a code block is a group of lines of code that are all in the same block or indent.
This can be encountered in a variety of places, including classes, functions, and loops.
2) Are not interrupted by other lines of code on the same indent, you can tell where code
blocks are.
Python code blocks are useful because they indicate which parts of a loop, class, or function
will be executed.
def code_block():
print (1)
print (2)
# Everything in this loop is part of the same code block print (i)
Variable
In Python, a variable is a container for storing a value. You can create a variable by
assigning a value to it using the “=” operator. The value can be of any data type, such
as a string, integer, or floating-point number. Once a variable is assigned a value, it
can be used throughout your program.
For example:
x=5
y = “Hello”
z = 3.14
In this example, x is assigned the value of 5, y is assigned the value “Hello”, and z is
assigned the value 3.14.
It’s important to note that variable names in Python must start with a letter or an
underscore, and can only contain letters, numbers and underscores. They are case-
sensitive.
You can also change the value of a variable by reassigning it to a new value. For
example:
x=5
x = 10
In this example, x is first assigned the value of 5 and then reassigned the value of 10.
Data Types
Python has several built-in data types, including strings, integers, and floating-point
numbers. In Python, data types refer to the type of value a variable holds. Python has
several built-in data types:
You can check the data type of a variable using the built-in type() function.
For example:
x=5
print(type(x))
# Output: <class ‘int’>;
y = “Hello”
print(type(y))
# Output: <class ‘str’>;
z = [1, 2, 3]
print(type(z))
# Output: <class ‘list’>;
Operators
1. Arithmetic operators:
2. Comparison operators:
These operators compare two values and return a Boolean value (True or
False) based on the comparison. Examples include equal to (==), not equal to
(!=), greater than (>), less than (<), greater than or equal to (>=), and less than
or equal to (<=).
3. Logical operators:
4. Assignment operators:
5. Membership operators:
These operators are used to test whether a value is in a sequence (e.g. a list or
string). Examples include in and not in.
6. Identity operators:
These operators are used to compare the identity of two objects. is and is not
are the identity operators in python.
For example:
x=5
y = 10
result = x + y
print(result) # Output: 15
result = x < y
print(result) # Output: True
# Using the *= operator to multiply x by 2
x *= 2
print(x) # Output: 10
In this example, the first print statement uses the + operator to add x and y, the
second print statement uses the < operator to check if x is less than y, and the
third print statement uses the *= operator to multiply x by 2.
Conditional Statements
if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
For example:
x=5
if x > 0:
print(“x is positive”)
else:
print(“x is not positive”)
In this example, the condition ‘x > 0’ evaluates to True, so the code in the if block is
executed and the output will be “x is positive”.
You can also use ‘elif’ statement which is short for “else if” it allows you to check
multiple conditions in the same if-else block.
x=5
if x > 0:
print(“x is positive”)
elif x == 0:
print(“x is zero”)
else:
print(“x is negative”)
In this example, the first condition ‘x > 0’ is True, so the code in the first if block is
executed and the output will be “x is positive”.
It’s important to note that the ‘condition’ in the if statement can be any expression
that evaluates to a Boolean value. You can use comparison operators, logical
operators, and even function calls that return a Boolean value.
Loops
Python has two types of loops: for loops and while loops. These allow you to
repeatedly execute a block of code. In Python, loops are used to repeatedly execute a
block of code. There are two types of loops: for loops and while loops.
1. For loops: A for loop is used to iterate over a sequence of items (e.g. a list,
string, or tuple) and execute a block of code for each item. The basic syntax of
a for loop is as follows:for variable in sequence:
# code to be executed for each item in the sequence
For example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
In this example, the for loop will iterate over the list of numbers and print each
number.
For example:
x=0
while x < 5:
print(x)
x += 1
In this example, the while loop will execute as long as ‘x < 5’ is true. The loop
will first print 0, then 1, then 2, and so on until x becomes 5. At that point, the
condition ‘x < 5’ becomes false and the loop stops.
It’s important to note that if the condition in the while loop never becomes
false, the loop will run indefinitely, causing an infinite loop. To avoid this,
make sure the condition will eventually be false.
You can also use ‘break’ and ‘continue’ statements inside the loop to control
the flow of the loop, ‘break’ statement is used to exit a loop and ‘continue’
statement is used to skip the current iteration and move on to the next one.
Functions
In Python, a function is a block of code that can be reused throughout your program.
Functions are useful for breaking down a complex program into smaller, more
manageable pieces.
def function_name(parameters):
# code to be executed
Here, function_name is the name of the function, and ‘parameters’ are the input
values that are passed to the function. The code inside the function is executed when
the function is called.
For example:
def greet(name):
print(“Hello, ” + name)
greet(“John”)
In this example, the function ‘greet’ takes one parameter ‘name’, and when called it
prints the string “Hello, ” followed by the value of the ‘name’ parameter.
Functions can also return a value by using the ‘return’ statement. This allows you to
pass data back to the calling code. For example:
In this example, the function ‘add’ takes two parameters ‘x and y’, and returns the
result of adding them together. The function is called with the values 3 and 4, and the
returned value is stored in the variable ‘result’, which is then printed.
Functions can also have default values for the parameters, these default values are
used when the caller does not provide a value for that parameter.
For example:
In this example, the function ‘greet’ has one mandatory parameter ‘name’ and one
optional parameter ‘greeting’ with a default value of “Hello”. When the function is
called without providing a value for the greeting parameter, it will use the default
value of “Hello”.
Libraries
A library is a collection of pre-written code that you can use to perform various tasks.
Libraries provide a way to add functionality to your program without having to write
the code yourself.
There are many libraries available for Python, some of the most popular ones include:
To use a library in Python, you first need to install it, then you can import it into your
program and start using its functions and classes. You can install a library using pip,
which is the package installer for Python. Once installed, you can import the library
and start using it.
For example, to use the NumPy library in your program, you would first need to
install it by running ‘pip install numpy’ in your command line. Then, in your Python
program, you would import it using the following line of code:
import numpy
You can also use an alias name when importing a library which makes it easier to call
its functions and classes by using the alias name instead of the full library name.
import numpy as np
Now you can use the library’s functions and classes by calling them with the np
prefix.
It’s important to note that some libraries may have multiple versions and you should
use the version that is compatible with your Python version or other libraries that you
are using.
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
Python programming language is being updated regularly with new features and supports.
There are lots of updations in python versions, started from 1994 to current release.
Python Features
Python is easy to learn and use. It is developer-friendly and high level programming
language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.
Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.
Python has a large and broad library and provides rich set of module and functions for rapid
application development.
10) Integrated
Speed
Python is slower than C or C++. But of course, Python is a high-level language, unlike C or
C++ it’s not closer to hardware.
Mobile Development
Python is not a very good language for mobile development . It is seen as a weak language
for mobile computing. This is the reason very few mobile applications are built in it like
Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-
types, Python’s memory consumption is also high.
Database Access
Python has limitations with database access . As compared to the popular technologies like
JDBC and ODBC, the Python’s database access layer is found to be bit underdeveloped and
primitive . However, it cannot be applied in the enterprises that need smooth interaction of
complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the language. Because the
language is dynamically typed , it requires more testing and has errors that only show up at
runtime .
If you’ve installed Python in Windows using the default installation options, the path to the
Python executable wasn’t added to the Windows Path variable. The Path variable lists the
directories that will be searched for executables when you type a command in the command
prompt. By adding the path to the Python executable, you will be able to
access python.exe by typing the python keyword (you won’t need to specify the full path to
the program).
Consider what happens if we enter the python command in the command prompt and the
path to that executable is not added to the Path variable:
C:\>python
As you can see from the output above, the command was not found. To run python.exe,
you need to specify the full path to the executable:
C:\>C:\Python34\python –version
Python 3.4.3
To add the path to the python.exe file to the Path variable, start the Run box and
enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and click
the Environment Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to
the python.exe file, preceeded with the semicolon character (;). In our example, we have
added the following value: ;C:\Python34
Close all windows. Now you can run python.exe without specifying the full path to the file:
C:>python –version
Python 3.4.3
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a
new project, click on “Create New Project”.
1. You can select the location where you want the project to be created. If you don’t want to
change location than keep it as it is but at least change the name from “untitled” to
something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give
“HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
Step 7) You can see the output of your program at the bottom of the screen.
The python help function is used to display the documentation of modules, functions, classes,
keywords etc.
The help function has the following syntax:
help([object])
If the help function is passed without an argument, then the interactive help utility starts up
on the console.
1. Python programs are generally expected to run slower than Java programs.
2. Python supports a programming style that uses simple functions and variables.
3. Python development is much quicker than having to write and debug a C or C++.
4. Python shines as a glue language, used to combine components written in C++
5. Python is one of the popular high-level programming languages used in an extensive variety
of application domains.
6. Python provides the ability to ‘write once, run anywhere’ that enables it to run on all the
operating systems which have Python installed.
7. Python has inbuilt garbage collection and dynamic memory allocation process that enables
efficient memory management.
8. Python is used as a scripting language, and at times it is also used for the non-scripting
purpose.
9. It is easier to write a code in Python as the number of lines is less comparatively.
10. Python is an interpreted language and it runs through an interpreter during compilation.
1.Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is
an assignment statement. if statement, for statement, while statement etc. are other kinds
of statements which will be discussed later.
2.Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
1. a = 1 + 2 + 3 + \
2. 4 + 5 + 6 + \
3. 7 + 8 + 9
This is explicit line continuation. In Python, line continuation is implied inside parentheses
( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement
as
1. a = (1 + 2 + 3 +
2. 4 + 5 + 6 +
3. 7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
1. colors = [‘red’,
2. ‘blue’,
3. ‘green’]
We could also put multiple statements in a single line using semicolons, as follows
1. a = 1;
2. b = 2; c = 3
3.if statement
4.while statement
5for statement
6.input statement
7.print Statement ‘
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
Python Comments
Comments are very important while writing a program. It describes what’s going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month’s time. So taking
time to explain these concepts in form of comments is always fruitful.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
For Example
Python Keywords
We cannot use a keyword as a variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it
is. The list of all the keywords is given below.
Keywords in Python
as elif if Or yield
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think
of variables as a container that holds data which can be changed later throughout
programming. For example,
1. number = 10
As you can see from the above example, you can use the assignment operator = to assign a
value to a variable.
website = “String”
print(website)
a, b, c = 5, 3.2, “Hello”
print (a)
print (b)
print (c)
Constants
Create a constant.py
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
3.14
9.8
Python supports integers, floating point numbers and complex numbers. They are defined as
int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of a decimal point. 5 is
integer whereas 5.0 is a floating point number.
a=5
print(a)
# Output: 5
2. 2. Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
1. # list of integers
2. my_list = [1, 2, 3]
output
[1,2,3]
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
# set of integers
my_set = {1, 2, 3}
print(my_set)
6.Python Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming.
1. int(a) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
2. float() : This function is used to convert any data type to a floating point number
.
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
Python provides numerous built-in functions that are readily available to us at the Python
prompt.Some of the functions like input() and print() are widely used for standard input and
output operations respectively.
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given
below.
a=5
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into
the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the
input() function to allow this. The syntax for input() is
input([prompt])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter
in Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
= x=5 x=5
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Python Expressions:
Expressions are representations of value. They are different from statement in the fact that
statements do something while expressions are representation of value. For example any
string is also an expressions since it represents the value of the string as well. X+y,x-y,x*y
A=c+b
If(a>b):
While(a<=10):
Python has some advanced constructs through which you can represent values and hence
these constructs are also called expressions.
1. List comprehension
For example, the following code will get all the number within 10 and put them in a list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and will keep
the corresponding squares of those numbers as the values.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.Generator expression
For example, the following code will initialize a generator object that returns the values
within 10 when the object is called.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4.Conditional Expressions
Example:
>>> x
‘1’
Python has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a +
(b * c), and a * b + c is treated as (a * b) + c.(BODMAS)
Associativity
When two operators share an operand and the operators have the same precedence, then the
expression is evaluated according to the associativity of the operators. For example, since
the ** operator has right-to-left associativity, a * b * c is treated as a * (b * c). On the other
hand, since the / operator has left-to-right associativity, a / b / c is treated as (a / b) / c.
Some operators like assignment operators and comparison operators do not have associativity
in Python. There are separate rules for sequences of this kind of operator and cannot be
expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x <
y and y < z, and is evaluates from left-to-right.
Unit-2
Control Structures
Types
If statements
If-else statements
elif statements
Nested if and if ladder statements
elif ladder
2.Iteration Statements
While loop
For loop
3.break,Continue Statements
#1) If statements
If statement is one of the most commonly used conditional statement in most of the
programming languages. It decides whether certain statements need to be executed or not. If
statement checks for a given condition, if the condition is true, then the set of code present
inside the if block will be executed.
The If condition evaluates a Boolean expression and executes the block of code only when
the Boolean expression becomes TRUE.
Syntax:
flow chart
If you observe the above flow-chart, first the controller will come to an if condition and
evaluate the condition if it is true, then the statements will be executed, otherwise the code
present outside the block will be executed.
Example: 1
1 Num = 5
2.if else
The statement itself tells that if a given condition is true then execute the statements present
inside if block and if the condition is false then execute the else block.
Else block will execute only when the condition becomes false, this is the block where you
will perform some actions when the condition is not true.
If-else statement evaluates the Boolean expression and executes the block of code present
inside the if block if the condition becomes TRUE and executes a block of code present in the
else block if the condition becomes FALSE.
Syntax:
if(Boolean expression):
else:
Here, the condition will be evaluated to a Boolean expression (true or false). If the condition
is true then the statements or program present inside the if block will be executed and if the
condition is false then the statements or program present inside else block will be executed.
flowchart of if-else
If you observe the above flow chart, first the controller will come to if condition and evaluate
the condition if it is true and then the statements of if block will be executed otherwise else
block will be executed and later the rest of the code present outside if-else block will be
executed.
Example: 1
1 num = 5
4 else:
Output:
In python, we have one more conditional statement called elif statements. Elif statement is
used to check multiple conditions only if the given if condition false. It’s similar to an if-else
statement and the only difference is that in else we will not check the condition but in elif we
will do check the condition.
Elif statements are similar to if-else statements but elif statements evaluate multiple
conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
if(a>0):
print(“number is +ve”)
elif(a==0):
else:
print(“number is -ve”)
Nested if-else statements mean that an if statement or if-else statement is present inside
another if or if-else block. Python provides this feature as well, this in turn will help us to
check multiple conditions in a given program.
if(condition):
if(condition):
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it and so on. If
block can contain ‘n’ number of if block inside it.
example
if(a==1):
print(“today is sunday”)
if(a==2):
print(“today is monday”)
if(a==3):
print(“today is tuesday”)
if(a==4):
print(“today is wednesday”)
if(a==5):
print(“today is thursday”)
if(a==6):
print(“today is friday”)
if(a==7):
print(“today is saturday”)
#5) elif Ladder
We have seen about the elif statements but what is this elif ladder. As the name itself suggests
a program which contains ladder of elif statements or elif statements which are structured in
the form of a ladder.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif
condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and
third elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
example
if(a==1):
print(“today is sunday”)
elif(a==2):
print(“today is monday”)
elif(a==3):
print(“today is tuesday”)
elif(a==4):
print(“today is wednesday”)
elif(a==5):
print(“today is thursday”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
Looping statements in python are used to execute a block of statements or code repeatedly for
several times as specified by the user.
While loop
For loop
While loop in python is used to execute multiple statement or codes repeatedly until the given
condition is true.
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
3.increment /decrement
Syntax:
In while loop, we check the expression, if the expression becomes true, only then the block of
statements present inside the while loop will be executed. For every iteration, it will check
the condition and execute the block of statements until the condition becomes false.
i=0
while (i<=10):
print(i)
i = i+1
print(“end loop)
Output:
1 2 3 4 5 6 7 8 9 10
Syntax:
Here var will take the value from the sequence and execute it until all the values in the
sequence are done.
Output:
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. In other words, we can say that break is
used to abort the current execution of the program and the control goes to the next line
after the loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
break;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
The continue statement in python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can
skip some specific code for a particular condition.
#loop statements
continue;
Example
if i==5:
continue;
print(i);
Output:
10
1.Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string
etc.).
1. # empty list
2. my_list = []
3. # list of integers
4. my_list = [1, 2, 3]
# nested list
my_list = [‘p’,’r’,’o’,’b’,’e’]
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Python provides the following built-in functions which can be used with the lists.
SN Function Description
a=[1,2,3]
1 list.append(obj)
a.append(4)
print(a)
2 list.clear() It removes all the elements from the list.
a=[1,2,3]
a.clear()
print(a)
It returns a shallow copy of the list.
a=[1,2,3]
3 List.copy()
b=a.copy()
print(b)
It returns the number of occurrences of the specified object in the list.
4 list.count(obj) a=[1,2,3,4,5,2,5,6]
Print(a.count(5))
The sequence represented by the object seq is extended to the list.
List1=[1,2,3]
5 list.extend(seq) List2=[4,5,6]
List1.extend(List2)
Print(List1)
It returns the index value in the list that object appears.
6 list.index(obj) l=[1,2,3,4,5]
print(l.index(5))
The object is inserted into the list at the specified index.
L=[1,2,4,5]
7 list.insert(index, obj)
L.insert(2,3)
Print(L)
It removes and returns the last object of the list.
S=[1,2,3,4,5]
8 list.pop(obj=list[-1])
int(S.pop())
print(S)
9 list.remove(obj) It removes the specified object from the list.
L=[1,2,1,1,3]
L.remove(1)
Print(L)
10 list.reverse() It reverses the list.
List=[1,2,3,4,5]
List.reverse()
Print(List)
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
SN Function Description
It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
false.
1 cmp(tuple1, tuple2)
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
list1= [ 1, 2, 3, 4 ]
5 tuple(seq)
tuple2 = tuple(list1)
print(tuple2)
The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.
T1 = (1, 2, 3, 4, 5,)
The repetition operator enables the tuple elements to be repeated
Repetition T1=T1*2
multiple times.
Print(T1)
T1= (1, 2, 3, 4, 5, 6, 7, 8,
9)
Concatenation It concatenates the tuple mentioned on either side of the operator.
T1=T1+(10,)
Print(T1)
T1=(1,2,3,4,5)
Membership It returns true if a particular item exists in the tuple otherwise false.
print (2 in T1)
Iteration The for loop is used to iterate over the tuple elements. T1=(1,2,3)
for i in T1:
print(i)
Output
5
T1=(1,2,3,4,5)
len(T1) = 5
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality than tuple. The tuple provides less functionality than the list.
The list Is used in the scenario in which we need The tuple is used in the cases where we need to store
to store the simple collections with no the read-only collections i.e., the value of the items can
5
constraints where the value of the items can be not be changed. It can be used as the key inside the
changed. dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must
be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
In the previous example, we have discussed about how the set is created in python. However,
we can perform various mathematical operations on python sets like union, intersection,
difference, etc.
The union of two sets are calculated by using the or (|) operator. The union of the two sets
contains the all the items that are present in both the sets.
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
The & (intersection) operator is used to calculate the intersection of the two sets in python.
The intersection of the two sets are given as the set of the elements that common in both sets.
Output:
{‘Martin’, ‘David’}
Output:
{‘Martin’, ‘David’}
The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).
The Intersection_update() method is different from intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, intersection() method returns
a new set.
Output:
{‘castle’}
SN Method Description
It adds an item to the set. It has no effect if the item is already present in the set.
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1 = {1,2,3,4,5,6}
2 clear() set1.clear()
print(set1)
It returns a shallow copy of the set.
set1 = {1, 2, 3, 4}
3 copy()
set2 = set1.copy()
print(set2)
4 difference_update(….) It modifies this set by removing all the items that are also present in the specified sets.
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
It removes the specified item from the set.
print(fruits)
It returns a new set that contains only the common elements of both the sets. (all the sets
if more than two are specified).
z = x.intersection(y)
print(z)
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of
the tutorial, we will discuss the most popular data type in python i.e., string.
In python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create
the string.
In python, strings are treated as the sequence of strings which means that python doesn’t
support the character data type instead a single character written as ‘p’ is treated as the string
of length 1.
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
It capitalizes the first character of the String. This function is deprecated in python3
capitalize() b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
It is change string in lower case.
print(string.upper())
The split() method breaks up a string at the specified separator and returns a list of strings.
print(text.split( ))
The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
print(song.replace(‘cold’, ‘hurt’))
The index() method returns the index number of given string (if found).
sentence = ‘Python’
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python has a set of built-in methods that you can use on dictionaries.
Method Description
car = {
“brand”: “Ford”,
“model”: “Mustang”,
clear() “year”: 1964
}
car.clear()
print(car)
Returns a copy of the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
copy() “year”: 1964
}
x = car.copy()
print(x)
Returns a dictionary with the specified keys and value,it Create a dictionary with 3
keys, all with the value 0:
thisdict = dict.fromkeys(x, y)
print(thisdict)
Returns the value of the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
get() “year”: 1964
}
x = car.get(“model”)
print(x)
items() Returns a list containing a tuple for each key value pair
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.items()
print(x)
Returns a list containing the dictionary’s keys
car = {
“brand”: “Ford”,
“model”: “Mustang”,
keys() “year”: 1964
}
x = car.keys()
print(x)
Removes the element with the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
pop() “year”: 1964
}
car.pop(“model”)
print(car)
Removes the last inserted key-value pair,it delete last value.
car = {
“brand”: “Ford”,
“model”: “Mustang”,
popitem() “year”: 1964
}
car.popitem()
print(car)
setdefault() Returns the value of the specified key value. If the key does not exist: insert the key,
with the specified value
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.setdefault(“model”, “Bronco”)
print(x)
Updates the dictionary with the specified key-value pairs
car = {
“brand”: “Ford”,
“model”: “Mustang”,
update() “year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
values() Returns a list of all the values in the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.values()
print(x)
Unit-3
Python Functions
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the python
program.
1.Inbuilt functions
The user can create its functions which can be called user-defined functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A simple function that prints the message “Hello Word” is given below.
1. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters, but we have to separate
them with a comma.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function(parameterlist):
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. Return <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed. If the return statement is without any expression, then the
special value None is returned.
z = (x + y)
return z
a=4
b=7
res2 = f(a, b)
In the event that you pass arguments like whole numbers, strings or tuples to a function, the
passing is like call-by-value because you can not change the value of the immutable objects
being passed to the function.
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
Output
In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.
However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is
made, and therefore the two different objects are printed.
list1=[1,2,3,4,5]
def fun(list1):
list1.append(20)
print(“outside”,list1)
Output:
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
Data sharing is not possible as data of the local Data sharing is possible as multiple functions ca
Data sharing
variable can be accessed by only one function. access the same global variable.
Parameters passing is required for local variables Parameters passing is not necessary for a globa
Parameters
to access the value in other function variable as it is visible throughout the program
When the value of the local variable is modified When the value of the global variable is modifie
Modification of
in one function, the changes are not visible in in one function changes are visible in the rest o
variable value
another function. the program.
Memory storage It is stored on the stack unless specified. It is stored on a fixed location decided by the
Parameter Local Global
compiler.
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
Output
The factorial of 4 is 24
Advantages of Recursion
Python Modules
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
def displayMsg(name)
print(“Hi “+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
The import statement is used to import all the functionality of one module into another. Here,
we must notice that we can use the functionality of any python source file by importing that
file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
1. importmodule1,module2,…….. module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
Example:
import file;
file.displayMsg(name)
Output:
Hi John
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
calculation.py:
Main.py:
Sum = 30
1. from<module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can
use this name to use that module in our python source file.
Example
#the module calculation of previous example is imported in this example as cal. import calcu
lation as cal;
a = int(input(“Enter a?”));
b = int(input(“Enter b?”));
print(“Sum = “,cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list
contains all the sub-modules, variables and functions defined in this module.
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
As we have already stated that, a module is loaded once regardless of the number of times it
is imported into the python source file. However, if you want to reload the already imported
module to re-execute the top-level code, python provides us the reload() function. The syntax
to use the reload() function is given below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use
the following line of code.
1. reload(calculation)
Statistics Module
This module, as mentioned in the Python 3 documentation, provides functions for calculating
mathematical statistics of numeric (Real-valued) data.
Math Module
This module, as mentioned in the Python 3’s documentation, provides access to the
mathematical functions defined by the C standard.
Random module
Packages are a way of structuring many packages and modules which helps in a well-
organized hierarchy of data set, making the directories and modules easy to access.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is a package.
Example of Creating Package
Let’s look at this example and see how a package is created. Let’s create a package named
Cars and build three modules in it namely, Bmw, Audi and Nissan.
class Bmw:
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
Then we create another file with the name Audi.py and add the similar type of code to it with
different members.
def add(x,y):
z=x*y
return(z)
3. Finally we create the __init__.py file.This file will be placed inside Cars directory and can be
left blank or we can put this initialisation code into it.
print(b.add(x,y))
Now, let’s use the package that we created. To do this make a sample.py file in the same
directory where Cars package is located and add the following code to it:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
error occurs, Python generate an exception that can be handled, which avoids your
program to crash.
Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
Types of Exception
1)Build in
2) User Define
1)Build in Exception
IOError
ValueError
Raised when a built-in operation or function receives an argument that has the
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
… try:
… break
… except ValueError:
File Handling
File Object
Instead we can use the built-in object “file”. That object provides basic functions and
methods necessary to manipulate files by default. Before you can read, append or write to a
file, you will first have to it using
1.Open()
The open() function is used to open files in our system, the filename is the
The mode indicates, how the file is going to be opened “r” for reading,”w” for writing and
“a” for a appending. The open function takes two arguments, the name of the file and and the
mode or which we would like to open the file. By default, when only the filename is passed,
the open function opens the file in read mode.
Example
This small script, will open the (hello.txt) and print the content.
This will store the file information in the file object “filename”.
filename = “hello.txt”
print line,
2.Read ()
3.Write ()
4.Append ()
The append function is used to append to the file instead of overwriting it.
To append to an existing file, simply open the file in append mode (“a”):
5.Close()When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file.
6.seek() sets the file’s current position at the offset. The whence argument is optional and
defaults to 0, which means absolute file positioning, other values are 1 which means seek
relative to the current position and 2 means seek relative to the file’s end.
7.tell() Python file method tell() returns the current position of the file read/write pointer
within the file.
fh = open(“hello.txt”, “r”)
fh = open(“hello.txt”,”r”)
print fh.read()
fh = open(“hello”.txt”, “r”)
print fh.readline()
fh = open(“hello.txt.”, “r”)
print fh.readlines()
fh = open(“hello.txt”,”w”)
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh = open(“Hello.txt”, “a”)
fh.close()
fh = open(“hello.txt”, “r”)
print fh.read()
fh.close()
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 takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
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)
Example
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
We can think of class as a sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here, a
parrot is an object.
class Parrot:
pass
2.Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
3.Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
4.Inheritance
Inheritance is a way of creating a new class for using details of an existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
5.Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private
attributes using underscore as the prefix i.e single _ or double __.
6.Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data
types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square,
circle). However we could use the same method to color any shape. This concept is called
Polymorphism.
7.Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Python Classes/Objects
Create a Class
Example
class MyClass:
x=5
Create Object/Accessing members
Example
p1 = MyClass()
print(p1.x)
Example
p1.age = 40
Example
class Person:
def myfunc(self):
print(“Hello my name is ” + self.name)
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the name of the module in which the class is defined.
__module__
In an interactive mode it will give us __main__.
A possibly empty tuple containing the base classes in the order of their
__bases__
occurrence.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Python’s memory allocation and deallocation method is automatic. The user does not have to
preallocate or deallocate memory similar to using dynamic memory allocation in languages
such as C or C++.
Python uses two strategies for memory allocation:
Reference counting
Garbage collection
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when
the instance is about to be destroyed. This method might be used to clean up any non memory
resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about to be destroyed −
https://www.javatpoint.com/python-modules
https://www.tutorialspoint.com/execute_python_online.php
https://www.onlinegdb.com/online_python_compiler
CLASS:BCA3rdSem
Batch: 2019-2021
Python
Unit-I
6-34
Operators and Expressions: Operators in Python, Expressions,
Precedence, Associativity of Operators, Non Associative Operators.
Unit-II
Unit-IV
Unit- 1
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
Python programming language is being updated regularly with new features and supports.
There are lots of updations in python versions, started from 1994 to current release.
Python Features
Python is easy to learn and use. It is developer-friendly and high level programming
language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.
Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.
Python has a large and broad library and provides rich set of module and functions for rapid
application development.
10) Integrated
Speed
Python is slower than C or C++. But of course, Python is a high-level language, unlike C or
C++ it’s not closer to hardware.
Mobile Development
Python is not a very good language for mobile development . It is seen as a weak language
for mobile computing. This is the reason very few mobile applications are built in it like
Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-
types, Python’s memory consumption is also high.
Database Access
Python has limitations with database access . As compared to the popular technologies like
JDBC and ODBC, the Python’s database access layer is found to be bit underdeveloped and
primitive . However, it cannot be applied in the enterprises that need smooth interaction of
complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the language. Because the
language is dynamically typed , it requires more testing and has errors that only show up at
runtime .
If you’ve installed Python in Windows using the default installation options, the path to the
Python executable wasn’t added to the Windows Path variable. The Path variable lists the
directories that will be searched for executables when you type a command in the command
prompt. By adding the path to the Python executable, you will be able to
access python.exe by typing the python keyword (you won’t need to specify the full path to
the program).
Consider what happens if we enter the python command in the command prompt and the
path to that executable is not added to the Path variable:
C:\>python
As you can see from the output above, the command was not found. To run python.exe,
you need to specify the full path to the executable:
C:\>C:\Python34\python –version
Python 3.4.3
To add the path to the python.exe file to the Path variable, start the Run box and
enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and click
the Environment Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to
the python.exe file, preceeded with the semicolon character (;). In our example, we have
added the following value: ;C:\Python34
Close all windows. Now you can run python.exe without specifying the full path to the file:
C:>python –version
Python 3.4.3
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a
new project, click on “Create New Project”.
1. You can select the location where you want the project to be created. If you don’t want to
change location than keep it as it is but at least change the name from “untitled” to
something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give
“HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
Step 7) You can see the output of your program at the bottom of the screen.
The python help function is used to display the documentation of modules, functions, classes,
keywords etc.
The help function has the following syntax:
help([object])
If the help function is passed without an argument, then the interactive help utility starts up
on the console.
1. Python programs are generally expected to run slower than Java programs.
2. Python supports a programming style that uses simple functions and variables.
3. Python development is much quicker than having to write and debug a C or C++.
4. Python shines as a glue language, used to combine components written in C++
5. Python is one of the popular high-level programming languages used in an extensive variety
of application domains.
6. Python provides the ability to ‘write once, run anywhere’ that enables it to run on all the
operating systems which have Python installed.
7. Python has inbuilt garbage collection and dynamic memory allocation process that enables
efficient memory management.
8. Python is used as a scripting language, and at times it is also used for the non-scripting
purpose.
9. It is easier to write a code in Python as the number of lines is less comparatively.
10. Python is an interpreted language and it runs through an interpreter during compilation.
1.Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is
an assignment statement. if statement, for statement, while statement etc. are other kinds
of statements which will be discussed later.
2.Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
1. a = 1 + 2 + 3 + \
2. 4 + 5 + 6 + \
3. 7 + 8 + 9
This is explicit line continuation. In Python, line continuation is implied inside parentheses
( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement
as
1. a = (1 + 2 + 3 +
2. 4 + 5 + 6 +
3. 7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
1. colors = [‘red’,
2. ‘blue’,
3. ‘green’]
We could also put multiple statements in a single line using semicolons, as follows
1. a = 1;
2. b = 2; c = 3
3.if statement
4.while statement
5for statement
6.input statement
7.print Statement ‘
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
Python Comments
Comments are very important while writing a program. It describes what’s going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month’s time. So taking
time to explain these concepts in form of comments is always fruitful.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
For Example
Python Keywords
We cannot use a keyword as a variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it
is. The list of all the keywords is given below.
Keywords in Python
as elif if Or yield
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think
of variables as a container that holds data which can be changed later throughout
programming. For example,
1. number = 10
As you can see from the above example, you can use the assignment operator = to assign a
value to a variable.
website = “String”
print(website)
a, b, c = 5, 3.2, “Hello”
print (a)
print (b)
print (c)
Constants
Create a constant.py
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
3.14
9.8
Python supports integers, floating point numbers and complex numbers. They are defined as
int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of a decimal point. 5 is
integer whereas 5.0 is a floating point number.
a=5
print(a)
# Output: 5
2. 2. Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
1. # list of integers
2. my_list = [1, 2, 3]
output
[1,2,3]
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
# set of integers
my_set = {1, 2, 3}
print(my_set)
6.Python Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming.
1. int(a) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
2. float() : This function is used to convert any data type to a floating point number
.
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
Python provides numerous built-in functions that are readily available to us at the Python
prompt.Some of the functions like input() and print() are widely used for standard input and
output operations respectively.
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given
below.
a=5
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into
the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the
input() function to allow this. The syntax for input() is
input([prompt])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter
in Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
= x=5 x=5
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Python Expressions:
Expressions are representations of value. They are different from statement in the fact that
statements do something while expressions are representation of value. For example any
string is also an expressions since it represents the value of the string as well. X+y,x-y,x*y
A=c+b
If(a>b):
While(a<=10):
Python has some advanced constructs through which you can represent values and hence
these constructs are also called expressions.
1. List comprehension
For example, the following code will get all the number within 10 and put them in a list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and will keep
the corresponding squares of those numbers as the values.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.Generator expression
For example, the following code will initialize a generator object that returns the values
within 10 when the object is called.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4.Conditional Expressions
Example:
>>> x
‘1’
Python has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a +
(b * c), and a * b + c is treated as (a * b) + c.(BODMAS)
Associativity
When two operators share an operand and the operators have the same precedence, then the
expression is evaluated according to the associativity of the operators. For example, since
the ** operator has right-to-left associativity, a * b * c is treated as a * (b * c). On the other
hand, since the / operator has left-to-right associativity, a / b / c is treated as (a / b) / c.
Some operators like assignment operators and comparison operators do not have associativity
in Python. There are separate rules for sequences of this kind of operator and cannot be
expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x <
y and y < z, and is evaluates from left-to-right.
Unit-2
Control Structures
Types
If statements
If-else statements
elif statements
Nested if and if ladder statements
elif ladder
2.Iteration Statements
While loop
For loop
3.break,Continue Statements
#1) If statements
If statement is one of the most commonly used conditional statement in most of the
programming languages. It decides whether certain statements need to be executed or not. If
statement checks for a given condition, if the condition is true, then the set of code present
inside the if block will be executed.
The If condition evaluates a Boolean expression and executes the block of code only when
the Boolean expression becomes TRUE.
Syntax:
flow chart
If you observe the above flow-chart, first the controller will come to an if condition and
evaluate the condition if it is true, then the statements will be executed, otherwise the code
present outside the block will be executed.
Example: 1
1 Num = 5
2.if else
The statement itself tells that if a given condition is true then execute the statements present
inside if block and if the condition is false then execute the else block.
Else block will execute only when the condition becomes false, this is the block where you
will perform some actions when the condition is not true.
If-else statement evaluates the Boolean expression and executes the block of code present
inside the if block if the condition becomes TRUE and executes a block of code present in the
else block if the condition becomes FALSE.
Syntax:
if(Boolean expression):
else:
Here, the condition will be evaluated to a Boolean expression (true or false). If the condition
is true then the statements or program present inside the if block will be executed and if the
condition is false then the statements or program present inside else block will be executed.
flowchart of if-else
If you observe the above flow chart, first the controller will come to if condition and evaluate
the condition if it is true and then the statements of if block will be executed otherwise else
block will be executed and later the rest of the code present outside if-else block will be
executed.
Example: 1
1 num = 5
4 else:
Output:
In python, we have one more conditional statement called elif statements. Elif statement is
used to check multiple conditions only if the given if condition false. It’s similar to an if-else
statement and the only difference is that in else we will not check the condition but in elif we
will do check the condition.
Elif statements are similar to if-else statements but elif statements evaluate multiple
conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
if(a>0):
print(“number is +ve”)
elif(a==0):
else:
print(“number is -ve”)
Nested if-else statements mean that an if statement or if-else statement is present inside
another if or if-else block. Python provides this feature as well, this in turn will help us to
check multiple conditions in a given program.
if(condition):
if(condition):
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it and so on. If
block can contain ‘n’ number of if block inside it.
example
if(a==1):
print(“today is sunday”)
if(a==2):
print(“today is monday”)
if(a==3):
print(“today is tuesday”)
if(a==4):
print(“today is wednesday”)
if(a==5):
print(“today is thursday”)
if(a==6):
print(“today is friday”)
if(a==7):
print(“today is saturday”)
#5) elif Ladder
We have seen about the elif statements but what is this elif ladder. As the name itself suggests
a program which contains ladder of elif statements or elif statements which are structured in
the form of a ladder.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif
condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and
third elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
example
if(a==1):
print(“today is sunday”)
elif(a==2):
print(“today is monday”)
elif(a==3):
print(“today is tuesday”)
elif(a==4):
print(“today is wednesday”)
elif(a==5):
print(“today is thursday”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
Looping statements in python are used to execute a block of statements or code repeatedly for
several times as specified by the user.
While loop
For loop
While loop in python is used to execute multiple statement or codes repeatedly until the given
condition is true.
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
3.increment /decrement
Syntax:
In while loop, we check the expression, if the expression becomes true, only then the block of
statements present inside the while loop will be executed. For every iteration, it will check
the condition and execute the block of statements until the condition becomes false.
i=0
while (i<=10):
print(i)
i = i+1
print(“end loop)
Output:
1 2 3 4 5 6 7 8 9 10
Syntax:
Here var will take the value from the sequence and execute it until all the values in the
sequence are done.
Output:
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. In other words, we can say that break is
used to abort the current execution of the program and the control goes to the next line
after the loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
break;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
The continue statement in python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can
skip some specific code for a particular condition.
#loop statements
continue;
Example
if i==5:
continue;
print(i);
Output:
10
1.Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string
etc.).
1. # empty list
2. my_list = []
3. # list of integers
4. my_list = [1, 2, 3]
# nested list
my_list = [‘p’,’r’,’o’,’b’,’e’]
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Python provides the following built-in functions which can be used with the lists.
SN Function Description
a=[1,2,3]
1 list.append(obj)
a.append(4)
print(a)
2 list.clear() It removes all the elements from the list.
a=[1,2,3]
a.clear()
print(a)
It returns a shallow copy of the list.
a=[1,2,3]
3 List.copy()
b=a.copy()
print(b)
It returns the number of occurrences of the specified object in the list.
4 list.count(obj) a=[1,2,3,4,5,2,5,6]
Print(a.count(5))
The sequence represented by the object seq is extended to the list.
List1=[1,2,3]
5 list.extend(seq) List2=[4,5,6]
List1.extend(List2)
Print(List1)
It returns the index value in the list that object appears.
6 list.index(obj) l=[1,2,3,4,5]
print(l.index(5))
The object is inserted into the list at the specified index.
L=[1,2,4,5]
7 list.insert(index, obj)
L.insert(2,3)
Print(L)
It removes and returns the last object of the list.
S=[1,2,3,4,5]
8 list.pop(obj=list[-1])
int(S.pop())
print(S)
9 list.remove(obj) It removes the specified object from the list.
L=[1,2,1,1,3]
L.remove(1)
Print(L)
10 list.reverse() It reverses the list.
List=[1,2,3,4,5]
List.reverse()
Print(List)
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
SN Function Description
It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
false.
1 cmp(tuple1, tuple2)
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
list1= [ 1, 2, 3, 4 ]
5 tuple(seq)
tuple2 = tuple(list1)
print(tuple2)
The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.
T1 = (1, 2, 3, 4, 5,)
The repetition operator enables the tuple elements to be repeated
Repetition T1=T1*2
multiple times.
Print(T1)
T1= (1, 2, 3, 4, 5, 6, 7, 8,
9)
Concatenation It concatenates the tuple mentioned on either side of the operator.
T1=T1+(10,)
Print(T1)
T1=(1,2,3,4,5)
Membership It returns true if a particular item exists in the tuple otherwise false.
print (2 in T1)
Iteration The for loop is used to iterate over the tuple elements. T1=(1,2,3)
for i in T1:
print(i)
Output
5
T1=(1,2,3,4,5)
len(T1) = 5
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality than tuple. The tuple provides less functionality than the list.
The list Is used in the scenario in which we need The tuple is used in the cases where we need to store
to store the simple collections with no the read-only collections i.e., the value of the items can
5
constraints where the value of the items can be not be changed. It can be used as the key inside the
changed. dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must
be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
In the previous example, we have discussed about how the set is created in python. However,
we can perform various mathematical operations on python sets like union, intersection,
difference, etc.
The union of two sets are calculated by using the or (|) operator. The union of the two sets
contains the all the items that are present in both the sets.
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
The & (intersection) operator is used to calculate the intersection of the two sets in python.
The intersection of the two sets are given as the set of the elements that common in both sets.
Output:
{‘Martin’, ‘David’}
Output:
{‘Martin’, ‘David’}
The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).
The Intersection_update() method is different from intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, intersection() method returns
a new set.
Output:
{‘castle’}
SN Method Description
It adds an item to the set. It has no effect if the item is already present in the set.
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1 = {1,2,3,4,5,6}
2 clear() set1.clear()
print(set1)
It returns a shallow copy of the set.
set1 = {1, 2, 3, 4}
3 copy()
set2 = set1.copy()
print(set2)
4 difference_update(….) It modifies this set by removing all the items that are also present in the specified sets.
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
It removes the specified item from the set.
print(fruits)
It returns a new set that contains only the common elements of both the sets. (all the sets
if more than two are specified).
z = x.intersection(y)
print(z)
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of
the tutorial, we will discuss the most popular data type in python i.e., string.
In python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create
the string.
In python, strings are treated as the sequence of strings which means that python doesn’t
support the character data type instead a single character written as ‘p’ is treated as the string
of length 1.
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
It capitalizes the first character of the String. This function is deprecated in python3
capitalize() b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
It is change string in lower case.
print(string.upper())
The split() method breaks up a string at the specified separator and returns a list of strings.
print(text.split( ))
The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
print(song.replace(‘cold’, ‘hurt’))
The index() method returns the index number of given string (if found).
sentence = ‘Python’
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python has a set of built-in methods that you can use on dictionaries.
Method Description
car = {
“brand”: “Ford”,
“model”: “Mustang”,
clear() “year”: 1964
}
car.clear()
print(car)
Returns a copy of the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
copy() “year”: 1964
}
x = car.copy()
print(x)
Returns a dictionary with the specified keys and value,it Create a dictionary with 3
keys, all with the value 0:
thisdict = dict.fromkeys(x, y)
print(thisdict)
Returns the value of the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
get() “year”: 1964
}
x = car.get(“model”)
print(x)
items() Returns a list containing a tuple for each key value pair
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.items()
print(x)
Returns a list containing the dictionary’s keys
car = {
“brand”: “Ford”,
“model”: “Mustang”,
keys() “year”: 1964
}
x = car.keys()
print(x)
Removes the element with the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
pop() “year”: 1964
}
car.pop(“model”)
print(car)
Removes the last inserted key-value pair,it delete last value.
car = {
“brand”: “Ford”,
“model”: “Mustang”,
popitem() “year”: 1964
}
car.popitem()
print(car)
setdefault() Returns the value of the specified key value. If the key does not exist: insert the key,
with the specified value
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.setdefault(“model”, “Bronco”)
print(x)
Updates the dictionary with the specified key-value pairs
car = {
“brand”: “Ford”,
“model”: “Mustang”,
update() “year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
values() Returns a list of all the values in the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.values()
print(x)
Unit-3
Python Functions
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the python
program.
1.Inbuilt functions
The user can create its functions which can be called user-defined functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A simple function that prints the message “Hello Word” is given below.
1. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters, but we have to separate
them with a comma.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function(parameterlist):
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. Return <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed. If the return statement is without any expression, then the
special value None is returned.
z = (x + y)
return z
a=4
b=7
res2 = f(a, b)
In the event that you pass arguments like whole numbers, strings or tuples to a function, the
passing is like call-by-value because you can not change the value of the immutable objects
being passed to the function.
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
Output
In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.
However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is
made, and therefore the two different objects are printed.
list1=[1,2,3,4,5]
def fun(list1):
list1.append(20)
print(“outside”,list1)
Output:
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
Data sharing is not possible as data of the local Data sharing is possible as multiple functions ca
Data sharing
variable can be accessed by only one function. access the same global variable.
Parameters passing is required for local variables Parameters passing is not necessary for a globa
Parameters
to access the value in other function variable as it is visible throughout the program
When the value of the local variable is modified When the value of the global variable is modifie
Modification of
in one function, the changes are not visible in in one function changes are visible in the rest o
variable value
another function. the program.
Memory storage It is stored on the stack unless specified. It is stored on a fixed location decided by the
Parameter Local Global
compiler.
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
Output
The factorial of 4 is 24
Advantages of Recursion
Python Modules
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
def displayMsg(name)
print(“Hi “+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
The import statement is used to import all the functionality of one module into another. Here,
we must notice that we can use the functionality of any python source file by importing that
file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
1. importmodule1,module2,…….. module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
Example:
import file;
file.displayMsg(name)
Output:
Hi John
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
calculation.py:
Main.py:
Sum = 30
1. from<module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can
use this name to use that module in our python source file.
Example
#the module calculation of previous example is imported in this example as cal. import calcu
lation as cal;
a = int(input(“Enter a?”));
b = int(input(“Enter b?”));
print(“Sum = “,cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list
contains all the sub-modules, variables and functions defined in this module.
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
As we have already stated that, a module is loaded once regardless of the number of times it
is imported into the python source file. However, if you want to reload the already imported
module to re-execute the top-level code, python provides us the reload() function. The syntax
to use the reload() function is given below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use
the following line of code.
1. reload(calculation)
Statistics Module
This module, as mentioned in the Python 3 documentation, provides functions for calculating
mathematical statistics of numeric (Real-valued) data.
Math Module
This module, as mentioned in the Python 3’s documentation, provides access to the
mathematical functions defined by the C standard.
Random module
Packages are a way of structuring many packages and modules which helps in a well-
organized hierarchy of data set, making the directories and modules easy to access.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is a package.
Example of Creating Package
Let’s look at this example and see how a package is created. Let’s create a package named
Cars and build three modules in it namely, Bmw, Audi and Nissan.
class Bmw:
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
Then we create another file with the name Audi.py and add the similar type of code to it with
different members.
def add(x,y):
z=x*y
return(z)
3. Finally we create the __init__.py file.This file will be placed inside Cars directory and can be
left blank or we can put this initialisation code into it.
print(b.add(x,y))
Now, let’s use the package that we created. To do this make a sample.py file in the same
directory where Cars package is located and add the following code to it:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
error occurs, Python generate an exception that can be handled, which avoids your
program to crash.
Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
Types of Exception
1)Build in
2) User Define
1)Build in Exception
IOError
ValueError
Raised when a built-in operation or function receives an argument that has the
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
… try:
… break
… except ValueError:
File Handling
File Object
Instead we can use the built-in object “file”. That object provides basic functions and
methods necessary to manipulate files by default. Before you can read, append or write to a
file, you will first have to it using
1.Open()
The open() function is used to open files in our system, the filename is the
The mode indicates, how the file is going to be opened “r” for reading,”w” for writing and
“a” for a appending. The open function takes two arguments, the name of the file and and the
mode or which we would like to open the file. By default, when only the filename is passed,
the open function opens the file in read mode.
Example
This small script, will open the (hello.txt) and print the content.
This will store the file information in the file object “filename”.
filename = “hello.txt”
print line,
2.Read ()
3.Write ()
4.Append ()
The append function is used to append to the file instead of overwriting it.
To append to an existing file, simply open the file in append mode (“a”):
5.Close()When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file.
6.seek() sets the file’s current position at the offset. The whence argument is optional and
defaults to 0, which means absolute file positioning, other values are 1 which means seek
relative to the current position and 2 means seek relative to the file’s end.
7.tell() Python file method tell() returns the current position of the file read/write pointer
within the file.
fh = open(“hello.txt”, “r”)
fh = open(“hello.txt”,”r”)
print fh.read()
fh = open(“hello”.txt”, “r”)
print fh.readline()
fh = open(“hello.txt.”, “r”)
print fh.readlines()
fh = open(“hello.txt”,”w”)
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh = open(“Hello.txt”, “a”)
fh.close()
fh = open(“hello.txt”, “r”)
print fh.read()
fh.close()
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 takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
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)
Example
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
We can think of class as a sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here, a
parrot is an object.
class Parrot:
pass
2.Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
3.Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
4.Inheritance
Inheritance is a way of creating a new class for using details of an existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
5.Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private
attributes using underscore as the prefix i.e single _ or double __.
6.Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data
types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square,
circle). However we could use the same method to color any shape. This concept is called
Polymorphism.
7.Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Python Classes/Objects
Create a Class
Example
class MyClass:
x=5
Create Object/Accessing members
Example
p1 = MyClass()
print(p1.x)
Example
p1.age = 40
Example
class Person:
def myfunc(self):
print(“Hello my name is ” + self.name)
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the name of the module in which the class is defined.
__module__
In an interactive mode it will give us __main__.
A possibly empty tuple containing the base classes in the order of their
__bases__
occurrence.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Python’s memory allocation and deallocation method is automatic. The user does not have to
preallocate or deallocate memory similar to using dynamic memory allocation in languages
such as C or C++.
Python uses two strategies for memory allocation:
Reference counting
Garbage collection
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when
the instance is about to be destroyed. This method might be used to clean up any non memory
resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about to be destroyed −
https://www.javatpoint.com/python-modules
https://www.tutorialspoint.com/execute_python_online.php
https://www.onlinegdb.com/online_python_compiler
CLASS:BCA3rdSem
Batch: 2019-2021
Python
Unit-I
6-34
Operators and Expressions: Operators in Python, Expressions,
Precedence, Associativity of Operators, Non Associative Operators.
Unit-II
Unit-IV
Unit- 1
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
Python programming language is being updated regularly with new features and supports.
There are lots of updations in python versions, started from 1994 to current release.
Python Features
Python is easy to learn and use. It is developer-friendly and high level programming
language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.
Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.
Python has a large and broad library and provides rich set of module and functions for rapid
application development.
10) Integrated
Speed
Python is slower than C or C++. But of course, Python is a high-level language, unlike C or
C++ it’s not closer to hardware.
Mobile Development
Python is not a very good language for mobile development . It is seen as a weak language
for mobile computing. This is the reason very few mobile applications are built in it like
Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-
types, Python’s memory consumption is also high.
Database Access
Python has limitations with database access . As compared to the popular technologies like
JDBC and ODBC, the Python’s database access layer is found to be bit underdeveloped and
primitive . However, it cannot be applied in the enterprises that need smooth interaction of
complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the language. Because the
language is dynamically typed , it requires more testing and has errors that only show up at
runtime .
If you’ve installed Python in Windows using the default installation options, the path to the
Python executable wasn’t added to the Windows Path variable. The Path variable lists the
directories that will be searched for executables when you type a command in the command
prompt. By adding the path to the Python executable, you will be able to
access python.exe by typing the python keyword (you won’t need to specify the full path to
the program).
Consider what happens if we enter the python command in the command prompt and the
path to that executable is not added to the Path variable:
C:\>python
As you can see from the output above, the command was not found. To run python.exe,
you need to specify the full path to the executable:
C:\>C:\Python34\python –version
Python 3.4.3
To add the path to the python.exe file to the Path variable, start the Run box and
enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and click
the Environment Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to
the python.exe file, preceeded with the semicolon character (;). In our example, we have
added the following value: ;C:\Python34
Close all windows. Now you can run python.exe without specifying the full path to the file:
C:>python –version
Python 3.4.3
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a
new project, click on “Create New Project”.
1. You can select the location where you want the project to be created. If you don’t want to
change location than keep it as it is but at least change the name from “untitled” to
something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give
“HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
Step 7) You can see the output of your program at the bottom of the screen.
The python help function is used to display the documentation of modules, functions, classes,
keywords etc.
The help function has the following syntax:
help([object])
If the help function is passed without an argument, then the interactive help utility starts up
on the console.
1. Python programs are generally expected to run slower than Java programs.
2. Python supports a programming style that uses simple functions and variables.
3. Python development is much quicker than having to write and debug a C or C++.
4. Python shines as a glue language, used to combine components written in C++
5. Python is one of the popular high-level programming languages used in an extensive variety
of application domains.
6. Python provides the ability to ‘write once, run anywhere’ that enables it to run on all the
operating systems which have Python installed.
7. Python has inbuilt garbage collection and dynamic memory allocation process that enables
efficient memory management.
8. Python is used as a scripting language, and at times it is also used for the non-scripting
purpose.
9. It is easier to write a code in Python as the number of lines is less comparatively.
10. Python is an interpreted language and it runs through an interpreter during compilation.
1.Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is
an assignment statement. if statement, for statement, while statement etc. are other kinds
of statements which will be discussed later.
2.Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
1. a = 1 + 2 + 3 + \
2. 4 + 5 + 6 + \
3. 7 + 8 + 9
This is explicit line continuation. In Python, line continuation is implied inside parentheses
( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement
as
1. a = (1 + 2 + 3 +
2. 4 + 5 + 6 +
3. 7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
1. colors = [‘red’,
2. ‘blue’,
3. ‘green’]
We could also put multiple statements in a single line using semicolons, as follows
1. a = 1;
2. b = 2; c = 3
3.if statement
4.while statement
5for statement
6.input statement
7.print Statement ‘
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
Python Comments
Comments are very important while writing a program. It describes what’s going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month’s time. So taking
time to explain these concepts in form of comments is always fruitful.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
For Example
Python Keywords
We cannot use a keyword as a variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it
is. The list of all the keywords is given below.
Keywords in Python
as elif if Or yield
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think
of variables as a container that holds data which can be changed later throughout
programming. For example,
1. number = 10
As you can see from the above example, you can use the assignment operator = to assign a
value to a variable.
website = “String”
print(website)
a, b, c = 5, 3.2, “Hello”
print (a)
print (b)
print (c)
Constants
Create a constant.py
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
3.14
9.8
Python supports integers, floating point numbers and complex numbers. They are defined as
int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of a decimal point. 5 is
integer whereas 5.0 is a floating point number.
a=5
print(a)
# Output: 5
2. 2. Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
1. # list of integers
2. my_list = [1, 2, 3]
output
[1,2,3]
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
# set of integers
my_set = {1, 2, 3}
print(my_set)
6.Python Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming.
1. int(a) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
2. float() : This function is used to convert any data type to a floating point number
.
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
Python provides numerous built-in functions that are readily available to us at the Python
prompt.Some of the functions like input() and print() are widely used for standard input and
output operations respectively.
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given
below.
a=5
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into
the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the
input() function to allow this. The syntax for input() is
input([prompt])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter
in Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
= x=5 x=5
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Python Expressions:
Expressions are representations of value. They are different from statement in the fact that
statements do something while expressions are representation of value. For example any
string is also an expressions since it represents the value of the string as well. X+y,x-y,x*y
A=c+b
If(a>b):
While(a<=10):
Python has some advanced constructs through which you can represent values and hence
these constructs are also called expressions.
1. List comprehension
For example, the following code will get all the number within 10 and put them in a list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and will keep
the corresponding squares of those numbers as the values.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.Generator expression
For example, the following code will initialize a generator object that returns the values
within 10 when the object is called.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4.Conditional Expressions
Example:
>>> x
‘1’
Python has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a +
(b * c), and a * b + c is treated as (a * b) + c.(BODMAS)
Associativity
When two operators share an operand and the operators have the same precedence, then the
expression is evaluated according to the associativity of the operators. For example, since
the ** operator has right-to-left associativity, a * b * c is treated as a * (b * c). On the other
hand, since the / operator has left-to-right associativity, a / b / c is treated as (a / b) / c.
Some operators like assignment operators and comparison operators do not have associativity
in Python. There are separate rules for sequences of this kind of operator and cannot be
expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x <
y and y < z, and is evaluates from left-to-right.
Unit-2
Control Structures
Types
If statements
If-else statements
elif statements
Nested if and if ladder statements
elif ladder
2.Iteration Statements
While loop
For loop
3.break,Continue Statements
#1) If statements
If statement is one of the most commonly used conditional statement in most of the
programming languages. It decides whether certain statements need to be executed or not. If
statement checks for a given condition, if the condition is true, then the set of code present
inside the if block will be executed.
The If condition evaluates a Boolean expression and executes the block of code only when
the Boolean expression becomes TRUE.
Syntax:
flow chart
If you observe the above flow-chart, first the controller will come to an if condition and
evaluate the condition if it is true, then the statements will be executed, otherwise the code
present outside the block will be executed.
Example: 1
1 Num = 5
2.if else
The statement itself tells that if a given condition is true then execute the statements present
inside if block and if the condition is false then execute the else block.
Else block will execute only when the condition becomes false, this is the block where you
will perform some actions when the condition is not true.
If-else statement evaluates the Boolean expression and executes the block of code present
inside the if block if the condition becomes TRUE and executes a block of code present in the
else block if the condition becomes FALSE.
Syntax:
if(Boolean expression):
else:
Here, the condition will be evaluated to a Boolean expression (true or false). If the condition
is true then the statements or program present inside the if block will be executed and if the
condition is false then the statements or program present inside else block will be executed.
flowchart of if-else
If you observe the above flow chart, first the controller will come to if condition and evaluate
the condition if it is true and then the statements of if block will be executed otherwise else
block will be executed and later the rest of the code present outside if-else block will be
executed.
Example: 1
1 num = 5
4 else:
Output:
In python, we have one more conditional statement called elif statements. Elif statement is
used to check multiple conditions only if the given if condition false. It’s similar to an if-else
statement and the only difference is that in else we will not check the condition but in elif we
will do check the condition.
Elif statements are similar to if-else statements but elif statements evaluate multiple
conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
if(a>0):
print(“number is +ve”)
elif(a==0):
else:
print(“number is -ve”)
Nested if-else statements mean that an if statement or if-else statement is present inside
another if or if-else block. Python provides this feature as well, this in turn will help us to
check multiple conditions in a given program.
if(condition):
if(condition):
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it and so on. If
block can contain ‘n’ number of if block inside it.
example
if(a==1):
print(“today is sunday”)
if(a==2):
print(“today is monday”)
if(a==3):
print(“today is tuesday”)
if(a==4):
print(“today is wednesday”)
if(a==5):
print(“today is thursday”)
if(a==6):
print(“today is friday”)
if(a==7):
print(“today is saturday”)
#5) elif Ladder
We have seen about the elif statements but what is this elif ladder. As the name itself suggests
a program which contains ladder of elif statements or elif statements which are structured in
the form of a ladder.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif
condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and
third elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
example
if(a==1):
print(“today is sunday”)
elif(a==2):
print(“today is monday”)
elif(a==3):
print(“today is tuesday”)
elif(a==4):
print(“today is wednesday”)
elif(a==5):
print(“today is thursday”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
Looping statements in python are used to execute a block of statements or code repeatedly for
several times as specified by the user.
While loop
For loop
While loop in python is used to execute multiple statement or codes repeatedly until the given
condition is true.
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
3.increment /decrement
Syntax:
In while loop, we check the expression, if the expression becomes true, only then the block of
statements present inside the while loop will be executed. For every iteration, it will check
the condition and execute the block of statements until the condition becomes false.
i=0
while (i<=10):
print(i)
i = i+1
print(“end loop)
Output:
1 2 3 4 5 6 7 8 9 10
Syntax:
Here var will take the value from the sequence and execute it until all the values in the
sequence are done.
Output:
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. In other words, we can say that break is
used to abort the current execution of the program and the control goes to the next line
after the loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
break;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
The continue statement in python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can
skip some specific code for a particular condition.
#loop statements
continue;
Example
if i==5:
continue;
print(i);
Output:
10
1.Python List
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string
etc.).
1. # empty list
2. my_list = []
3. # list of integers
4. my_list = [1, 2, 3]
# nested list
my_list = [‘p’,’r’,’o’,’b’,’e’]
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Python provides the following built-in functions which can be used with the lists.
SN Function Description
a=[1,2,3]
1 list.append(obj)
a.append(4)
print(a)
2 list.clear() It removes all the elements from the list.
a=[1,2,3]
a.clear()
print(a)
It returns a shallow copy of the list.
a=[1,2,3]
3 List.copy()
b=a.copy()
print(b)
It returns the number of occurrences of the specified object in the list.
4 list.count(obj) a=[1,2,3,4,5,2,5,6]
Print(a.count(5))
The sequence represented by the object seq is extended to the list.
List1=[1,2,3]
5 list.extend(seq) List2=[4,5,6]
List1.extend(List2)
Print(List1)
It returns the index value in the list that object appears.
6 list.index(obj) l=[1,2,3,4,5]
print(l.index(5))
The object is inserted into the list at the specified index.
L=[1,2,4,5]
7 list.insert(index, obj)
L.insert(2,3)
Print(L)
It removes and returns the last object of the list.
S=[1,2,3,4,5]
8 list.pop(obj=list[-1])
int(S.pop())
print(S)
9 list.remove(obj) It removes the specified object from the list.
L=[1,2,1,1,3]
L.remove(1)
Print(L)
10 list.reverse() It reverses the list.
List=[1,2,3,4,5]
List.reverse()
Print(List)
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
SN Function Description
It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
false.
1 cmp(tuple1, tuple2)
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
list1= [ 1, 2, 3, 4 ]
5 tuple(seq)
tuple2 = tuple(list1)
print(tuple2)
The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.
T1 = (1, 2, 3, 4, 5,)
The repetition operator enables the tuple elements to be repeated
Repetition T1=T1*2
multiple times.
Print(T1)
T1= (1, 2, 3, 4, 5, 6, 7, 8,
9)
Concatenation It concatenates the tuple mentioned on either side of the operator.
T1=T1+(10,)
Print(T1)
T1=(1,2,3,4,5)
Membership It returns true if a particular item exists in the tuple otherwise false.
print (2 in T1)
Iteration The for loop is used to iterate over the tuple elements. T1=(1,2,3)
for i in T1:
print(i)
Output
5
T1=(1,2,3,4,5)
len(T1) = 5
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality than tuple. The tuple provides less functionality than the list.
The list Is used in the scenario in which we need The tuple is used in the cases where we need to store
to store the simple collections with no the read-only collections i.e., the value of the items can
5
constraints where the value of the items can be not be changed. It can be used as the key inside the
changed. dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must
be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
In the previous example, we have discussed about how the set is created in python. However,
we can perform various mathematical operations on python sets like union, intersection,
difference, etc.
The union of two sets are calculated by using the or (|) operator. The union of the two sets
contains the all the items that are present in both the sets.
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
The & (intersection) operator is used to calculate the intersection of the two sets in python.
The intersection of the two sets are given as the set of the elements that common in both sets.
Output:
{‘Martin’, ‘David’}
Output:
{‘Martin’, ‘David’}
The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).
The Intersection_update() method is different from intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, intersection() method returns
a new set.
Output:
{‘castle’}
SN Method Description
It adds an item to the set. It has no effect if the item is already present in the set.
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1 = {1,2,3,4,5,6}
2 clear() set1.clear()
print(set1)
It returns a shallow copy of the set.
set1 = {1, 2, 3, 4}
3 copy()
set2 = set1.copy()
print(set2)
4 difference_update(….) It modifies this set by removing all the items that are also present in the specified sets.
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
It removes the specified item from the set.
print(fruits)
It returns a new set that contains only the common elements of both the sets. (all the sets
if more than two are specified).
z = x.intersection(y)
print(z)
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of
the tutorial, we will discuss the most popular data type in python i.e., string.
In python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create
the string.
In python, strings are treated as the sequence of strings which means that python doesn’t
support the character data type instead a single character written as ‘p’ is treated as the string
of length 1.
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
It capitalizes the first character of the String. This function is deprecated in python3
capitalize() b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
It is change string in lower case.
print(string.upper())
The split() method breaks up a string at the specified separator and returns a list of strings.
print(text.split( ))
The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
print(song.replace(‘cold’, ‘hurt’))
The index() method returns the index number of given string (if found).
sentence = ‘Python’
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized
to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Python has a set of built-in methods that you can use on dictionaries.
Method Description
car = {
“brand”: “Ford”,
“model”: “Mustang”,
clear() “year”: 1964
}
car.clear()
print(car)
Returns a copy of the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
copy() “year”: 1964
}
x = car.copy()
print(x)
Returns a dictionary with the specified keys and value,it Create a dictionary with 3
keys, all with the value 0:
thisdict = dict.fromkeys(x, y)
print(thisdict)
Returns the value of the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
get() “year”: 1964
}
x = car.get(“model”)
print(x)
items() Returns a list containing a tuple for each key value pair
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.items()
print(x)
Returns a list containing the dictionary’s keys
car = {
“brand”: “Ford”,
“model”: “Mustang”,
keys() “year”: 1964
}
x = car.keys()
print(x)
Removes the element with the specified key
car = {
“brand”: “Ford”,
“model”: “Mustang”,
pop() “year”: 1964
}
car.pop(“model”)
print(car)
Removes the last inserted key-value pair,it delete last value.
car = {
“brand”: “Ford”,
“model”: “Mustang”,
popitem() “year”: 1964
}
car.popitem()
print(car)
setdefault() Returns the value of the specified key value. If the key does not exist: insert the key,
with the specified value
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
x = car.setdefault(“model”, “Bronco”)
print(x)
Updates the dictionary with the specified key-value pairs
car = {
“brand”: “Ford”,
“model”: “Mustang”,
update() “year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
values() Returns a list of all the values in the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.values()
print(x)
Unit-3
Python Functions
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the python
program.
1.Inbuilt functions
The user can create its functions which can be called user-defined functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A simple function that prints the message “Hello Word” is given below.
1. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters, but we have to separate
them with a comma.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function(parameterlist):
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. defmy_function():
2. function-suite
3. Return <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function
or the python prompt. To call the function, use the function name followed by the
parentheses.
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed. If the return statement is without any expression, then the
special value None is returned.
z = (x + y)
return z
a=4
b=7
res2 = f(a, b)
In the event that you pass arguments like whole numbers, strings or tuples to a function, the
passing is like call-by-value because you can not change the value of the immutable objects
being passed to the function.
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
Output
In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.
However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is
made, and therefore the two different objects are printed.
list1=[1,2,3,4,5]
def fun(list1):
list1.append(20)
print(“outside”,list1)
Output:
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
Data sharing is not possible as data of the local Data sharing is possible as multiple functions ca
Data sharing
variable can be accessed by only one function. access the same global variable.
Parameters passing is required for local variables Parameters passing is not necessary for a globa
Parameters
to access the value in other function variable as it is visible throughout the program
When the value of the local variable is modified When the value of the global variable is modifie
Modification of
in one function, the changes are not visible in in one function changes are visible in the rest o
variable value
another function. the program.
Memory storage It is stored on the stack unless specified. It is stored on a fixed location decided by the
Parameter Local Global
compiler.
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
Output
The factorial of 4 is 24
Advantages of Recursion
Python Modules
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
def displayMsg(name)
print(“Hi “+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
The import statement is used to import all the functionality of one module into another. Here,
we must notice that we can use the functionality of any python source file by importing that
file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
1. importmodule1,module2,…….. module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
Example:
import file;
file.displayMsg(name)
Output:
Hi John
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
calculation.py:
Main.py:
Sum = 30
1. from<module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can
use this name to use that module in our python source file.
Example
#the module calculation of previous example is imported in this example as cal. import calcu
lation as cal;
a = int(input(“Enter a?”));
b = int(input(“Enter b?”));
print(“Sum = “,cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list
contains all the sub-modules, variables and functions defined in this module.
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
As we have already stated that, a module is loaded once regardless of the number of times it
is imported into the python source file. However, if you want to reload the already imported
module to re-execute the top-level code, python provides us the reload() function. The syntax
to use the reload() function is given below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use
the following line of code.
1. reload(calculation)
Statistics Module
This module, as mentioned in the Python 3 documentation, provides functions for calculating
mathematical statistics of numeric (Real-valued) data.
Math Module
This module, as mentioned in the Python 3’s documentation, provides access to the
mathematical functions defined by the C standard.
Random module
Packages are a way of structuring many packages and modules which helps in a well-
organized hierarchy of data set, making the directories and modules easy to access.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is a package.
Example of Creating Package
Let’s look at this example and see how a package is created. Let’s create a package named
Cars and build three modules in it namely, Bmw, Audi and Nissan.
class Bmw:
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
Then we create another file with the name Audi.py and add the similar type of code to it with
different members.
def add(x,y):
z=x*y
return(z)
3. Finally we create the __init__.py file.This file will be placed inside Cars directory and can be
left blank or we can put this initialisation code into it.
print(b.add(x,y))
Now, let’s use the package that we created. To do this make a sample.py file in the same
directory where Cars package is located and add the following code to it:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
error occurs, Python generate an exception that can be handled, which avoids your
program to crash.
Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
Types of Exception
1)Build in
2) User Define
1)Build in Exception
IOError
ValueError
Raised when a built-in operation or function receives an argument that has the
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
… try:
… break
… except ValueError:
File Handling
File Object
Instead we can use the built-in object “file”. That object provides basic functions and
methods necessary to manipulate files by default. Before you can read, append or write to a
file, you will first have to it using
1.Open()
The open() function is used to open files in our system, the filename is the
The mode indicates, how the file is going to be opened “r” for reading,”w” for writing and
“a” for a appending. The open function takes two arguments, the name of the file and and the
mode or which we would like to open the file. By default, when only the filename is passed,
the open function opens the file in read mode.
Example
This small script, will open the (hello.txt) and print the content.
This will store the file information in the file object “filename”.
filename = “hello.txt”
print line,
2.Read ()
3.Write ()
4.Append ()
The append function is used to append to the file instead of overwriting it.
To append to an existing file, simply open the file in append mode (“a”):
5.Close()When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file.
6.seek() sets the file’s current position at the offset. The whence argument is optional and
defaults to 0, which means absolute file positioning, other values are 1 which means seek
relative to the current position and 2 means seek relative to the file’s end.
7.tell() Python file method tell() returns the current position of the file read/write pointer
within the file.
fh = open(“hello.txt”, “r”)
fh = open(“hello.txt”,”r”)
print fh.read()
fh = open(“hello”.txt”, “r”)
print fh.readline()
fh = open(“hello.txt.”, “r”)
print fh.readlines()
fh = open(“hello.txt”,”w”)
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh = open(“Hello.txt”, “a”)
fh.close()
fh = open(“hello.txt”, “r”)
print fh.read()
fh.close()
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 takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
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)
Example
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
We can think of class as a sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here, a
parrot is an object.
class Parrot:
pass
2.Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
3.Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
4.Inheritance
Inheritance is a way of creating a new class for using details of an existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
5.Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private
attributes using underscore as the prefix i.e single _ or double __.
6.Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data
types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square,
circle). However we could use the same method to color any shape. This concept is called
Polymorphism.
7.Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Python Classes/Objects
Create a Class
Example
class MyClass:
x=5
Create Object/Accessing members
Example
p1 = MyClass()
print(p1.x)
Example
p1.age = 40
Example
class Person:
def myfunc(self):
print(“Hello my name is ” + self.name)
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the name of the module in which the class is defined.
__module__
In an interactive mode it will give us __main__.
A possibly empty tuple containing the base classes in the order of their
__bases__
occurrence.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Python’s memory allocation and deallocation method is automatic. The user does not have to
preallocate or deallocate memory similar to using dynamic memory allocation in languages
such as C or C++.
Python uses two strategies for memory allocation:
Reference counting
Garbage collection
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when
the instance is about to be destroyed. This method might be
In Python, we use this syntax to create a variable and assign a value to this variable:
<var_name> = <value>
For example:
age = 56
name = "Nora"
color = "Blue"
grades = [67, 100, 87, 56]
If the name of a variable has more than one word, then the Style Guide for Python Code
recommends separating words with an underscore "as necessary to improve readability."
For example:
my_list = [1, 2, 3, 4, 5]
💡 Tip: The Style Guide for Python Code (PEP 8) has great suggestions that you should
follow to write clean Python code.
Note that this scrim and the others in this handbook were narrated by a member of the
Scrimba team and have been added to illustrate some key Python concepts.
You just need to call the print() function and write "Hello, World!" within parentheses:
print("Hello, World!")
"Hello, World!"
💡 Tip: Writing a "Hello, World!" program is a tradition in the developer community. Most
developers start learning how to code by writing this program.
Great. You just wrote your first Python program. Now let's start learning about the data types
and built-in data structures that you can use in Python.
These are the numeric types that you can work with in Python:
Integers
Integers are numbers without decimals. You can check if a number is an integer with the
type() function. If the output is <class 'int'>, then the number is an integer.
For example:
>>> type(1)
<class 'int'>
>>> type(15)
<class 'int'>
>>> type(0)
<class 'int'>
>>> type(-46)
<class 'int'>
Floats
Floats are numbers with decimals. You can detect them visually by locating the decimal
point. If we call type() to check the data type of these values, we will see this as the output:
<class 'float'>
>>> type(4.5)
<class 'float'>
>>> type(5.8)
<class 'float'>
>>> type(2342423424.3)
<class 'float'>
>>> type(4.0)
<class 'float'>
>>> type(0.0)
<class 'float'>
>>> type(-23.5)
<class 'float'>
Complex
Complex numbers have a real part and an imaginary part denoted with j. You can create
complex numbers in Python with complex(). The first argument will be the real part and the
second argument will be the imaginary part.
>>> complex(4, 5)
(4+5j)
>>> complex(6, 8)
(6+8j)
>>> complex(0, 0)
0j
>>> complex(5)
(5+0j)
>>> complex(0, 4)
4j
Strings in Python
Strings incredibly helpful in Python. They contain a sequence of characters and they are
usually used to represent text in the code.
For example:
"Hello, World!"
'Hello, World!'
We can use both single quotes '' or double quotes "" to define a string. They are both valid
and equivalent, but you should choose one of them and use it consistently throughout the
program.
💡 Tip: Yes! You used a string when you wrote the "Hello, World!" program. Whenever
you see a value surrounded by single or double quotes in Python, that is a string.
Strings can contain any character that we can type in our keyboard, including numbers,
symbols, and other special characters.
For example:
"45678"
"my_email@email.com"
"#IlovePython"
If we define a string with double quotes "", then we can use single quotes within the string.
For example:
If we define a string with single quotes '', then we can use double quotes within the string.
For example:
String Indexing
We can use indices to access the characters of a string in our Python program. An index is an
integer that represents a specific position in the string. They are associated to the character at
that position.
String: H e l l o
Index: 0 1 2 3 4
💡 Tip: Indices start from 0 and they are incremented by 1 for each character to the right.
For example:
>>> my_string[0]
'H'
>>> my_string[1]
'e'
>>> my_string[2]
'l'
>>> my_string[3]
'l'
>>> my_string[4]
'o'
>>> my_string[-1]
'o'
>>> my_string[-2]
'l'
>>> my_string[-3]
'l'
>>> my_string[-4]
'e'
>>> my_string[-5]
'H'
String Slicing
We may also need to get a slice of a string or a subset of its characters. We can do so with
string slicing.
<string_variable>[start:stop:step]
start is the index of the first character that will be included in the slice. By default, it's 0.
stop is the index of the last character in the slice (this character will not be included). By
default, it is the last character in the string (if we omit this value, the last character will also
be included).
step is how much we are going to add to the current index to reach the next index.
We can specify two parameters to use the default value of step, which is 1. This will include
all the characters between start and stop (not inclusive):
<string_variable>[start:stop]
For example:
>>> freecodecamp[2:8]
'eeCode'
>>> freecodecamp[0:3]
'fre'
>>> freecodecamp[0:4]
'free'
>>> freecodecamp[4:7]
'Cod'
>>> freecodecamp[4:8]
'Code'
>>> freecodecamp[8:11]
'Cam'
>>> freecodecamp[8:12]
'Camp'
>>> freecodecamp[8:13]
'Camp'
💡 Tip: Notice that if the value of a parameter goes beyond the valid range of indices, the
slice will still be presented. This is how the creators of Python implemented this feature of
string slicing.
If we customize the step, we will "jump" from one index to the next according to this value.
For example:
>>> freecodecamp[0:9:2]
'feCdC'
>>> freecodecamp[2:10:3]
'eoC'
>>> freecodecamp[1:12:4]
'roa'
>>> freecodecamp[4:8:2]
'Cd'
>>> freecodecamp[3:9:2]
'eoe'
>>> freecodecamp[1:10:5]
'rd'
>>> freecodecamp[10:2:-1]
'maCedoCe'
>>> freecodecamp[11:4:-2]
'paeo'
>>> freecodecamp[5:2:-4]
'o'
And we can omit a parameter to use its default value. We just have to include the
corresponding colon (:) if we omit start, stop, or both:
# Default stop
>>> freecodecamp[4::3]
'Cem'
💡 Tip: The last example is one of the most common ways to reverse a string.
f-Strings
In Python 3.6 and more recent versions, we can use a type of string called f-string that helps
us format our strings much more easily.
To define an f-string, we just add an f before the single or double quotes. Then, within the
string, we surround the variables or expressions with curly braces {}. This replaces their
value in the string when we run the program.
For example:
first_name = "Nora"
favorite_language = "Python"
Here we have an example where we calculate the value of an expression and replace the
result in the string:
value = 5
5 multiplied by 2 is: 10
We can also call methods within the curly braces and the value returned will be replaced in
the string when we run the program:
freecodecamp = "FREECODECAMP"
print(f"{freecodecamp.lower()}")
The output is:
freecodecamp