Unit I
Unit I
Introduction to
Python
Topics to be covered:
History, Features,
Modes of Execution,
Setting up path,
working with Python Basic Syntax,
Variable and Data Types, Operators.
Conditional Statements (If, If- else, Nested if-else)
Looping (for, While Nested loops)
Control Statements (Break, Continue, Pass).
Input-Output:
Printing on screen,
Reading data from keyboard,
Opening and closing file
Python is General purpose high-level
programming language.
General purpose multi purpose-Data science
application,machine learning,web application,Ai
application, Robotics etc.
High-level langugae:understand by machine and
human
Low-level language: machine level language &
Assembly lang
Developed by “Guido Ran Rassam”
In 1989 while working at National Research
Institute(NRI) in Netherlands.
In Feb 28 1991 python available to public.
Highly recommended programming-language.
Main advantage is easy to write like English like
Why “PYTHON” name?
Monty “Python” Flying Circus.
Python Contains:
Functional Programming features from C
OOP features from C++.
Scripting features from Perl & Shell Scripting.
Modular programming features from Modula-
3(Every thing Module).
Syntax are borrowed from C & ABC Language.
PYTHON=Powerful programming + Powerful
Scripting language
Where we can use PYTHON ?
Desktop application
Web application Django—frame work to develop
web applications
Database application
Network application
Games
Data Analytics
Machine learning
AI
IOT
Features of Python programming language:
1. Readable: Python is a very readable language.
2. Easy to Learn: Learning python is easy as this is a
expressive and high level programming language, which
means it is easy to understand the language and thus easy to
learn.
3. Cross platform: Python is available and can run on various
operating systems such as Mac, Windows, Linux, Unix etc. This
makes it a cross platform and portable language.
4. Open Source: Python is a open source programming
language.
5. Large standard library: Python comes with a large
standard library that has some handy codes and functions
which we can use while writing code in Python.
6. Free: Python is free to download and use. This means you
can download it for free and use it in your application. See:
Open Source Python License. Python is an example of a FLOSS
(Free/Libre Open Source Software), which means you can
freely distribute copies of this software, read its source code
and modify it.
7. Supports exception handling: what is an
exception?
An exception is an event that can occur during
program exception and can disrupt the normal
flow of program.
Python supports exception handling which means
we can write less error prone code and can test
various scenarios that can cause an exception
later on.
8. Advanced features: Supports generators and
list comprehensions.
9. Automatic memory management: Python
supports automatic memory management which
means the memory is cleared and freed
automatically.
You do not have to bother clearing the memory.
What Can You Do with Python?
You may be wondering what all are the applications of
Python. There are so many applications of Python, here are
some of the them.
1. Web development – Web framework like Django and
Flask are based on Python.
They help you write server side code which helps you
manage database, write backend programming logic,
mapping urls etc.
2. Machine learning – There are many machine learning
applications written in Python. Machine learning is a way
to write a logic so that a machine can learn and solve a
particular problem on its own.
For example, products recommendation in websites like
Amazon, Flipkart, eBay etc. is a machine learning
algorithm that recognizes user’s interest.
Face recognition and Voice recognition in your phone is
another example of machine learning.
3. Data Analysis – Data analysis and data
visualisation in form of charts can also be
developed using Python.
4. Scripting – Scripting is writing small programs
to automate simple tasks such as sending
automated response emails etc. Such type of
applications can also be written in Python
programming language.
5. Game development – You can develop games
using Python.
6. You can develop Embedded applications in
Python.
7. Desktop applications – You can develop
desktop application in Python using library like
TKinter or QT.
Modes of Execution:
1) Interactive Mode
For working in the interactive mode, we will start
Python on our computer.
We type Python expression / statement /
command after the prompt (>>>) and Python
immediately responds with the output of it.
2) Script Mode
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is
finished.
When the script is finished, the interpreter is no longer
active.
Let us write a simple Python program in a script.
Python files have extension .py.
To create and run a Python script, we will use following
steps in IDLE, if the script mode is not made available
by default with IDLE environment.
1. File>New File (for creating a new script file) or Press
ctrl+N.
2. Write the Python code as function i.e. script.
3. Save it (^S).
4. Execute it in interactive mode- by using RUN option
(^F5).
Setting up path
Working with Python Basic Syntax:
Python Line Structure
A Python program comprises logical lines. A NEWLINE
token follows each of those. The interpreter ignores blank
lines.
The following line causes an error.
print("Hi
How are you?")
Python Multiline Statements
This one is an important Python Syntax
We saw that Python does not mandate semicolons. A new
line means a new statement.
But sometimes, you may want to split a statement over
two or more lines. It may be to aid readability. You can do
so in the following ways.
a. Use a backward slash
print("Hi\
how are you?")
b. Put the string in triple quotes
Python Comments:
Python Syntax ‘Comments’ let you store tags at the right places
in the code. You can use them to explain complex sections of
code.
The interpreter ignores comments. Declare a comment using an
octothorpe (#).
#This is a comment
Python does not support general multiline comments like Java
or C++.
Python Docstrings:
Python documentation strings (or docstrings) provide a
convenient way of associating documentation with Python
modules, functions, classes, and methods.
Like a comment, this Python Syntax is used to explain code.
But unlike comments, they are more specific. Also, they are
retained at runtime.
This way, the programmer can inspect them at runtime.
Delimit a docstring using three double quotes. You may put it as
a function’s first line to describe it.
Python Indentation
Since Python doesn’t use curly braces to delimit
blocks of code, this Python Syntax is mandatory.
You can indent code under a function, loop, or
class.
Python Quotations:
Python supports the single quote and the double quote for
string literals. But if you begin a string with a single quote,
you must end it with a single quote. The same goes for double
quotes.
Python Blank Lines:
If you leave a line with just whitespace, the
interpreter will ignore it.
Python Identifiers:
An identifier is a name of a program element, and
it is user-defined. This Python Syntax uniquely
identifies the element.
There are some rules to follow while choosing an
identifier:
An identifier may only begin with A-Z, a-z, or an
underscore(_).
This may be followed by letters, digits, and
underscores- zero or more.
Python is case-sensitive. Name and name are two
different identifiers.
The following is a list of keywords.
Local Scope
In the above code, we define a variable ‘d’ in a
function ‘func’.
So, ‘d’ is local to ‘func’. Hence, we can read/write
it in func, but not outside it.
When we try to do so, it raises a NameError.
Enclosing Scope:
In this code, ‘b’ has local scope in Python function
‘blue’, and ‘a’ has nonlocal scope in ‘blue’. Of course, a
python variable scope that isn’t global or local is
nonlocal. This is also called enclosing scope.
Built-in Scope
The built-in scope has all the names that are loaded into
python variable scope when we start the interpreter. For
example, we never need to import any module to access
functions like print() and id().
Global Scope
Variables that are defined inside a function body
have a local scope, and those defined outside
have a global scope.
This means that local variables can be accessed
only inside the function in which they are
declared, whereas global variables can be
accessed throughout the program body by all
functions.
Global Keyword in Python
Nonlocal Keyword
Like the ‘global’ keyword, you want to make a
change to a nonlocal variable, you must use the
‘nonlocal’ keyword.
As you can see, this did not change the value of
Data Types:
Data types are used to store data or information
in a variable.
Python data types are dynamic, because we
don’t need to mention type of the variable.
But in other languages we should mention the
type of data.
Python Numbers:
There are four numeric Python data types.
1. int– int stands for integer.
This Python Data Type holds signed integers.
We can use the type() function to find which
class it belongs to.
2. float– This Python Data Type holds floating point
real values.
complex- This Python Data Types holds a complex number.
A complex number looks like this: a+bj Here, a and b are
the real parts of the number, and j is imaginary.
Strings
A string is a sequence of characters. Python does not have
a char data type, unlike C++ or Java.
You can delimit a string using single quotes or double
quotes.
Displaying part of a string– You can display a character
from a string using its index in the string. Remember,
indexing starts with 0.
>>> name=‘SNIST'
>>> name[0] o/p ”S’
You can also display a burst of characters in a string using
the slicing operator [ ].
>>> name[2:4] o/p ‘IS’
This prints the characters from 2 to 3.
Slice Operator:
Syntax: s[begin:end]
Begin to end-1
Default value for begin is “0”.
If end is not specified it takes end has last index
Slices operator never raises any Index error.
Application:
+ operator:
* operator:
String reputation operator
‘*’ is applicable for string but one argument shuld
be int
Booleans:
Boolean data types are of 2 types in Python.
They are True and False. These can be used to
assign or compare the boolean values.
In Python, logical expressions return the boolean
values.
In Python, True is equalled to 1 and False is
equals to 0.
Python turns the boolean values into integers
explicitly during the arithmetic operations.
All fundamental data types are immutable.
Once we create an object we cannot change
If we try to perform any changes with that a new
object will be created
Collection Related Data types:
Fundamental data types can hold only One value
Group of values as a single entity then we use
Collection Related Data types.
List
Tuple
Set
Frozenset
Dict
Range
Bytes
Bytearray
Lists
A list is a collection of values.
List is an ordered sequence of items.
It is one of the most used datatype in Python and
is very flexible.
All the items in a list do not need to be of the
same type.
Declaring a list is pretty straight forward. Items
separated by commas are enclosed within
brackets [ ].
Example:
>>> days=['Monday','Tuesday',3,4,5,6,7]
>>> days
Output:
[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]
Order is preserved
Duplicates objects are allowed
[ ] representation
Accepts heterogeneous or dissimilar
objects
Indexing and slicing are applicable
L[ ] creation of empty list
to add an element to list use “append”
To remove use “remove”
1. Slicing a list – You can slice a list the way you’d
slice a string- with the slicing operator.
>>> days[1:3]
[‘Tuesday’, 3]
Indexing for a list begins with 0, like for a string. A
Python doesn’t have arrays.
Length of a list– Python supports an inbuilt function
to calculate the length of a list.
>>> len(days)
7
3. Reassigning elements of a list– A list is
mutable.
This means that you can reassign elements later on.
>>> days[2]='Wednesday'
>>> days
[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]
4. Multidimensional lists– A list may have more
than one dimension.
>>> a=[[1,2,3],[4,5,6]]
>>> a
[[1, 2, 3], [4, 5, 6]]
Tuple:
Tuple is an ordered sequence of items same as
list.
The only difference is that tuples are immutable.
Tuples once created cannot be modified.
Tuples are used to write-protect data and are
usually faster than list as it cannot change
dynamically.
It is defined within parentheses () where items
are separated by commas.
We cannot add or remove values.
Read only version of list is tuple
The above example shows type is “int”
When we add a comma after value then it is
consider as “TUPLE”
Single value tuple end should end with “COMMA”
Without “comma” its type is int.
With comma
LIST its type is tuple
TUPLE
1.Mutable 1.Immutable
2.[ ] 2.( )
3.More memory 3.To store tuple
elements python
required very less
memory
4.Performance is less 4.Performance is more
5.application:contenet Ex:Account types
Example:
>>> subjects=('Physics','Chemistry','Maths')
>>> subjects
(‘Physics’, ‘Chemistry’, ‘Maths’)
Accessing and Slicing a Tuple– You access a tuple the
same way as you’d access a list. The same goes for slicing it.
>>> subjects[1]
‘Chemistry’
>>> subjects[0:2]
(‘Physics’, ‘Chemistry’)
A tuple is immutable– However, it is immutable. Once
declared, you can’t change its size or elements.
>>> subjects[2]='Biology'
Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
TypeError: ‘tuple’ object does not support item
assignment
Set:
A set is an unordered and unindexed collection of
items.
This means when we print the elements of a set
they will appear in the random order and we
cannot access the elements of set based on
indexes because it is unindexed.
In List & Tuple order is important and duplicates
are allowed.
Tuple is immutable and List is Mutable
Duplicates are not allowed
Order is not required
Representation { }
Indexing and slicing are not applicable
Set is Mutable and Growable
append() add()
In list adding values at In set adding values in
last any position
S={10,20,30} S={10,20,30}
l.append(50) l.add(50)
print(s) print(s)
10,20,30,50 10,20,50,30
By default Curly Braces open and close type is
“Dict” not “set”
Frequently used data type is dict, more priority to
“dict”
List Set
Order is important No order
Duplicate are No duplicates
allowed
Represented by [ ] Represented by { }
Frozenset:
Frozen set same as Set
But Frozen set is immutable.
In frozen set we cannot add or remove values.
Order is not applicable
No duplication
Indexing and slicing are not applicable.
Dict:
If we want to represent a group of objects as “key
value pair” then use “dict”
Order is not important.
Dict is mutable.
Indexing & slicing are not applicable.
Syntax:
d={key:value}
{k1:v1,k2:v2,………..kn:vn}
Duplicate keys are not allowed .
Duplicate values are allowed
If we assign same “Key” if already assigned then
old value is replaced with new values. If we try to
insert duplicate we wont get any error or simply
old is value is replaced with new value.
Range:
Representing a sequence of numbers then use
range.
Indexing and slicing are applicable
Range object is immuatble
Different ways to create Range:
1.range(n):
Ex: r=range(10) #0 to 9
r=range(100) #0 to 99
2.range(begin,end):
Begin to end-1
r=range(1,10) #1 to 9
For x in r:
print(x)
r=range(1,11) #1 to 10 values
3.range(begin,end,increment/decrement):
r=range(1,21,1) # increment by1
r=range(1,21,2) # increment by2
r=range(1,21,-1) # decrement by -1
Byte:
Representing group of byte values
If we want to create byte use in-built byte
function.
Byte values assign only from 0 to 255
Bytes are immutable
Bytearray:
Both are same.
Bytes are immutable
Bytearray is mutable
By using Bytearray function we can create
bytearray
Type Conversion:
Python has five standard Data Types.
Sometimes it is necessary to convert values from
one type to another.
Python defines type conversion functions to
directly convert one data type to another.
Converting to Tuples and Lists:
A list is a mutable ordered sequence of elements
that is contained within square brackets [ ].
A tuple is an immutable ordered sequence of
elements contained within parentheses ( ).
You can use the methods list() and tuple() to
convert the values passed to them into the list
and tuple data type respectively.
ValueError
While converting from string to int you may get
ValueError exception.
This exception occurs if the string you want to
convert does not represent any numbers.
set()
bool()
It converts the value into a boolean.
It converts the
>>> bool(3) value into a
True set.
>>> bool(0)
False >>>
>>> bool(True) set([1,2,2,3])
True
>>> bool(0.1) {1, 2, 3}
True >>>
You can convert a list into a Boolean.
>>> bool([1,2])
set({1,2,2,3})
True {1, 2, 3}
The function returns False for empty constructs.
>>> bool()
False
>>> bool([])
False
>>> bool({})
False
None is a keyword in Python that represents an absence of value.
>>> bool(None)
False
None data type:
None means Nothing or No value associated
If the value is not available, then to handle such
type of cases None is introduced.
It is something like null value in java.
Constants:
Constants are not applicable in Python.
But it is convention to use only uppercase
characters if we don’t want to change value.
It is just convention but we can change the
value.
MAX_VALUE=16
list() tuple()
It converts the value
It converts the value into a list.
into a tuple.
>>> del list
>>> tuple({1,2,2,3})
>>> list("123") (1, 2, 3)
[‘1’, ‘2’, ‘3’] You can try your own
>>> list({1,2,2,3}) combinations. Also
[1, 2, 3] try composite
>>> list({"a":1,"b":2}) functions.
>>>
[‘a’, ‘b’] tuple(list(set([1,2])))
However, the following raises an(1,error.
2)
>>> list({a:1,b:2})
Traceback (most recent call last):
File “<pyshell#173>”, line 1, in <module>;
list({a:1,b:2})
TypeError: unhashable type: ‘set’
Operators:
Operators are used to perform operations on
values and variables.
Operators can manipulate individual items and
returns a result.
The data items are referred as operands or
arguments.
Operators are either represented by keywords or
special characters.
Python Operator falls into 7 categories:
Arithmetic Operator
Relational Operator
Assignment Operator
Logical Operator
Membership Operator
Python Arithmetic Operator:
These Python arithmetic operators include Python
operators for basic mathematical operations.
Python Relational Operator:
Relational operators are used to compare values.
It either returns True or False according to the
condition.
Python Assignment Operator:
Assignment operators are used in Python to
assign values to variables.
a = 5 is a simple assignment operator that
assigns the value 5 on the right to the variable a
on the left. There are various compound operators
in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a =
a + 5.
Python Logical Operator:
Logical operators are the and, or, not operators.
Python Bitwise Operator:
Bitwise operators act on operands as if they were
string of binary digits. It operates bit by bit, hence
the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in
binary) and y = 4 (0000 0100 in binary)
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Single Statement Condition:
If you only need to write a single statement under
if, you can write it in the same line using single
statement python decision making constructs.
Iterative Statements:
Loops in Python are used to control your program.
Loops are basically used to execute a block of
code several number of times accordingly.
Advantages of loops
There are the following advantages of loops in
Python.
It provides code re-usability.
Using loops, we do not need to write the same
code again and again.
Using loops, we can traverse over the elements of
data structures (array or linked lists).
4 types of Python Loop:
For Loop
While Loop
Python Loop Control Statements
Nested For Loop
For Loop:
Python for loop can iterate over a sequence of
items. T
he structure of a for loop in Python is different
than that in C++ or Java.
That is, for(int i=0;i<n;i++) won’t work here.
In Python, we use the ‘in’ keyword.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of
the item inside the sequence on each iteration.
Loop continues until we reach the last item in the
sequence.
The body of for loop is separated from the rest of
while loop:
The while loop is also known as a pre-tested loop.
In general, a while loop allows a part of the code
to be executed as long as the given condition is
true.
It can be viewed as a repeating if statement.
The while loop is mostly used in the case where
the number of iterations is not known in advance.
syntax is given below:
while expression:
statements
Loop Control Statements:
break statement:
When you put a break statement in the body of a
loop, the loop stops executing, and control shifts
to the first statement outside it.
You can put it in a for or while loop.
continue statement:
The continue statement is used to skip the rest of
the code inside a loop for the current iteration
only.
Loop does not terminate but continues on with
the next iteration.
pass statement:
Pass is a keyword in python.
In our programming syntactically if block is required
which won’t do anything then we can define that
empty block with pass keyword.
It is an empty statement
It is null statement
It won’t do anything
Ex: Expecting true
block Expected
If True: Indentation
else:
Print(“Hello”)
If the number is even we are doing
nothing and if it is odd then we are
displaying the number.
Input-Output:
Input:
Reading dynamic input from the keyboard.
In python 2 we have 2 functions are available to read
dynamic input from the keyboard.
1.raw_input()
2.input()
1.raw_input():
This function always reads the data from the
keyboard in the form of String format.
We have to convert that string type to our required
type by using corresponding type casting methods.
Ex:
a=raw_input(“enter a value”) It always print str type only
for any input type
Print(type(a))
2.input():
input() function can be used to read data directly
in our required format.
Here we don’t require to perform type casting.
Ex:
x=input(“enter value”)
type(x)
6int
“SNIST”str
7.8float
Truebool
But in python 3 we have only input() method.
raw_input() method is not available
In Python 3 input() function behavior exactly
same as raw_input() method of Python 2
Raw_input() function of python 2 is renamed as
input() function in Python 3
split( ) function takes
SPACE as separator by
default
eval():
eval function take a string evalutes to
corresponding type.
Output statements:
We can use print() function to display output.
Format 1:
print() without any argument
Just it prints new line character.
Format 2:
Note:
If both arguments are String type then + operator
acts as Concatenation operator.
If one argument is string type and second id any
other type like int then we will get Error.
If both arguments are number type then +
operator acts as arithmetic addition operator.
Format 3:
print() with variable number of arguments:
By default output values are separated by space.
If we want separator we can specify by using
”sep” attribute.
Format 4:
Print() with end attribute.
Default value for
If we want output in the same line with space
end attribute is \
n, which is
nothing but new
line character
Format 5:print(object) statement:
We can pass any object like list,tuple,set,etc as
arguments to print() statement.
output:
Format 7:print(formatted string):
%iint
%dint
%ffloat
%sstring type
print(“fotmatted string”,%(variable list))
Format 8:print() with replacement operator{}
We can format the strings with variable values by
using replacement operator{} and format()
method.
Output: