Unit5 Python
Unit5 Python
Python Programming
Introduction
Python is one of the latest and largely used languages and has gained popularity due to its simplicity
in coding and platform independent behaviours. Its easily understood and doesn’t require any coding
skills to start learning. It is a general-purpose language that is interactive and a high-level
programming language. It is object oriented as well as a scripting language.
Features:
▪ Python is Interpreted − Python is processed at runtime by the interpreter. One doesn’t need to
compile the program before executing it. This is similar to PERL and PHP.
▪ Python is Interactive − Coder can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
▪ Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
▪ Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
History:
▪ Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
▪ Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
▪ Like Perl, Python source code is now available under the GNU General Public License (GPL).
▪ Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.
Advantages:
▪ Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
▪ Easy-to-read − Python code is more clearly defined and visible to the eyes.
▪ Easy-to-maintain − Python's source code is fairly easy-to-maintain.
▪ A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
▪ Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
▪ Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
▪ GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
▪ Scalable − Python provides a better structure and support for large programs than shell scripting.
Interactive Interpreter:
Users can start Python from Unix, DOS, or any other system that provides a command-line
interpreter or shell window.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
▪ Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
▪ Starting an identifier with a single leading underscore indicates that the identifier is private.
▪ Starting an identifier with two leading underscores indicates a strongly private identifier.
▪ If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
▪ Arithmetic Operators
▪ Relational Operators
▪ Assignment Operators
▪ Logical Operators
▪ Bitwise Operators
▪ Membership Operators
▪ Identity Operators
Arithmetic Operators:
Relational Operators
Relational operators compare the values and returns True or False according to the condition.
Operator Description
> Greater than: True if left operand is greater than the right
< Less than: True if left operand is less than the right
== Equal to: True if both operands are equal
!= Not equal to: True if operands are not equal
>= Greater than or equal to: True if left operand is greater than or equal to the right
<= Less than or equal to: True if left operand is less than or equal to the right
Logical Operators
These are conjunctions that you can use to combine more than one condition.
Operator Description
and Logical AND: True if both the operands are true
or Logical OR: True if either of the operands is true
not Logical NOT: True if operand is false
Assignment Operators
Operator Description
= Assign value of right side of expression to left side operand
+= Add AND: Add right side operand with left side operand and then assign to left
operand
-= Subtract AND: Subtract right operand from left operand and then assign to left
operand
*= Multiply AND: Multiply right operand with left operand and then assign to left
operand
/= Divide AND: Divide left operand with right operand and then assign to
left operand
%= Modulus AND: Takes modulus using left and right operands and assign result
to left operand
//= Divide(floor) AND: Divide left operand with right operand and then assign
the value(floor) to left operand
**= Exponent AND: Calculate exponent (raised power) value using operands
and assign value to left operand
&= Performs Bitwise AND on operands and assign value to left operand
|= Performs Bitwise OR on operands and assign value to left operand
^= Performs Bitwise xOR on operands and assign value to left operand
>>= Performs Bitwise right shift on operands and assign value to left operand
<<= Performs Bitwise left shift on operands and assign value to left operand
Membership Operators
Used to test whether a value or variable is in a sequence.
Operator Description
in True if value is found in the sequence
not in True if value is not found in the sequence
Identity Operators
Used to check if two values are located on the same part of the memory.
Operator Description
is True if the operands are identical
Is not True if the operands are not identical
print( ) Function
print( ) is a in-built(default) function of python. It is used to print identifiers, variables. The
print () function prints the given object to the standard output device (screen) or to the text
stream file.
Examples:
type( ) Function
type( ) is a in-built(default) function of python. It is used to show the type of the defined data type.
Example: type(x)
Escape Characters
▪ In Python strings, the backslash "\" is a special character, also called the "escape" character.
▪ An escape character is a backslash \ followed by the character you want to insert.
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
▪ Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes. There are various
data types in Python. These are used to store values, allocate memory and also used to hold data
temporarily/permanently.
The Built-in data Types are:
Integer Float String Bool
List Tuple Set Dictionary
Complex Range Bytes Byte Array
Memory View None Type
Type Data Type/Class
Text String
Numeric Integer, Float, Complex
Sequence Tuple, List, Set
Mapping Dictionary
Set Set
Boolean Bytes, ByteArray, Memory View
NoneType NoneType
String (str)
▪ String literals in python are surrounded by either single quotation (’ ’) marks, or double quotation
(“ ” “ ”) marks or triple quotation (‘’’ ‘’’) marks.
▪ Represented by ‘str’
Examples:
x=‘World’ x= “World”
x=“World123”
x= “World@123#”
String Features
▪ Ordered in nature
▪ Can consists only one element/item/value
▪ Immutable, that means can not make changes in string variable
▪ Can perform Indexing & Slicing
▪ It is a text type data type & can store anything like (characters, digits, special characters etc.)
String Methods
Method Description
upper ( ) The upper( ) method returns the string in upper case
lower( ) The lower( ) method returns the string in lower case
swapcase( ) Inverts case for all letters in string
split( ) The split( ) method splits the string into substrings if it finds instances of the separator
strip( ) The strip( ) method removes any whitespace from the beginning or the end
replace( ) The replace ( ) method replaces a string with another string
Integer (int): A integer is a whole number, positive, negative, without decimals of unlimited
length and it is represented by ‘int’.
Examples:
x= 123 x= 123456789 x= 9587542312578215 x= -123 x= +123
Integer Features
▪ Can consists only one element/item/number
▪ Does not create index so cannot perform Indexing & Slicing on a integer variable
▪ It is a numeric data type which can store only non-decimal numbers
Float (float): Float, or "floating point number" is a number, positive or negative, containing
one or more decimals. It is represented by ‘float’.
Examples:
Float Features
▪ Can consists only one element/item/number
▪ Does not create index so cannot perform Indexing & Slicing on a integer variable
▪ It is a numeric data type which can store only decimal numbers
Tuple (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. It is defined within parentheses () where
items are separated by commas & consists of multiple elements. All the items in a list do not need to
be of the same type. It is Represented by ‘tuple’.
Examples:
Tuple Features
▪ It is a Sequence, so can store multiple elements/items/numbers
▪ Ordered in nature
▪ It creates index so can perform Indexing & Slicing on a tuple variable
▪ Immutable, that means cannot make changes in tuple variable
▪ Allows duplicate values/elements in the same variable
▪ Can store values/elements within parentheses ( )
▪ Tuple cannot have single index, it can have multiple indexes
List (list): List is an ordered sequence of items. It is one of the most used data types 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 square brackets [ ]. It consists of
single or multiple elements. List variable can be empty as well. It is represented as ‘List’.
Examples:
List Features
▪ It is a Sequence, so can store multiple elements/items/numbers
▪ Ordered in nature
▪ It creates index so can perform Indexing & Slicing on a tuple variable
▪ Mutable/Changeable, that means can make changes in list variable
▪ Allows duplicate values/elements in the same variable
▪ Can store values/elements within square bracket [ ]
List Methods
Method Description
append( ) Add new item at the end of the list
extend( ) Add multiple items at the end of the list
insert( ) Add a new item on the specified position
index ( ) Returns the index of the specified item
count( ) Count the specified items in the list
sort( ) Arrange list items in ascending order
reverse( ) Reverse the list items
copy( ) Creates another list with the same items
remove( ) Delete the specified item from the list
pop( ) Delete the item from the list by defining its position(index)
clear( ) Delete all items from the list
Set (set): Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered. Declaring a list is pretty straight forward.
Items separated by commas are enclosed within brackets { }. It can consist of single or multiple
elements. It is Represented as ‘set’.
Examples:
Set Features
▪ It is a Sequence, so can store multiple elements/items/numbers
▪ Unordered, unchangeable & unindexed in nature
▪ Since unindexed, cannot perform Indexing & Slicing on a set variable
▪ Immutable, that means cannot make changes in set variable
▪ Does not allow duplicate values/elements in the same variable
▪ variables cannot be empty
▪ Can store values/elements within { }
Dictionary (dict): Dictionary is an unordered collection of key-value pairs. It is generally used when we
have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to
retrieve the value. Dictionaries are defined within braces {} with each item being a pair in the form key
: value. Key and value can be of any type. It is represented by ‘dict’
Examples:
Dictionary Features
▪ It is a collection of pairs of keys & values
▪ Unordered in nature
▪ It does not create index so cannot perform Indexing & Slicing on a dictionary variable
▪ Mutable/Changeable, that means can make changes in dictionary variable
▪ Does not allow duplicate keys but allows duplicate values in the same dictionary variable
▪ Dictionary variable cann be empty
▪ Can store pair of keys & values within { }
▪ Dictionary is unordered, changeable & unindexed
Dictionary Methods
Method Description
keys( ) Returns a list containing the dictionary's keys
values( ) Returns a list of all the values in the dictionary
get( ) Returns the value of the specified key
items( ) Returns a list containing a tuple for each key value pair
copy( ) Returns a copy of the dictionary
clear( ) Removes all the elements from the dictionary
pop( ) Removes the element with the specified key
popitem( ) Removes the last inserted key-value pair
update( ) Updates the dictionary with the specified key-value pairs
Python Booleans: Booleans represent one of two values: True or False. In programming you often
need to know if an expression is True or False. One can evaluate any expression in Python, and get
one of two answers, True or False. When two values are compared, the expression is evaluated and
Python returns the Boolean answer.
Examples :
Python Complex: The complex in python programming is a method we can use to convert a string
or a number into a complex data type. The complex() method takes two parameters, namely the real
and imaginary values. The complex in python uses the provided parameters and returns a complex
number. It is used in speech recognition system. Complex numbers are specially used in electronics,
optics & quantum theory for describing waves & periodic phenomena.
Example:
num = 2+4j
print(num)
Output : (2+4j)
print(type(num))
Types of Statements:
Statements can be of 3 types.
1. Conditional Statements
2. Transfer Statements
3. Iterative Statements
Conditional Statements
▪ Transfer Statements in python are used to control the order of execution of the program based on the
values and logic. These are also known as Control Statements.
A. break: The break statement is used to terminate the loop containing it, and the control of the
program comes out of the loop.
B. Continue: When the program encounters a continue statement, it will skip the statements which
are present after the continue statement inside the loop and proceed with the next iterations.
C. Pass: Pass statement is python is a null operation, which is used when the statement is required
syntactically.
Iterative Statements
▪ In Python, the iterative statements are also known as looping statements or repetitive statements. The
iterative statements are used to execute a part of the program repeatedly.
▪ Python programming language provides the different types of loops to handle looping requirements.
Python basically provides two ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.
Python provides the following iterative statements.
1. for statement
2. while statement
for: A ‘for’ loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string). With the ‘for’ loop, a set of statements can be executed repeatedly, which is
governed by the use of range( ) function.
While: While loop is used to execute a block of statements repeatedly until a given condition is
true or satisfied. And when the condition becomes false, loop process will stop.
▪ Function:
A Function is a group of statements that performs a specific task. This group of statements can be
called as ‘a block of code’, which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. The code inside function can
execute from anywhere in the program & any number of times. The code written inside function
can execute in the same program file & from another program file as well.
Functions provide better modularity for your application and a high degree of code reusing. Function
helps reducing lines of codes and break into small code section. Function allows a programmer to
make code reusable for any number of times.
A Function can also defined inside function, known as nested function. Python gives so many built-
in functions, but a programmer can also create new functions as per requirement using def keyword.
Arguments in Function:
Required Arguments: These are also known as non-default arguments. Non-Default arguments are
the arguments passed to a function in correct positional order. By default, a function. must be called
with the correct number of arguments. Meaning that if your function expects 2 arguments, you have
to call the function with 2 arguments, not more, and not less.
Default Arguments: These are the values passed after the function name, inside the parentheses( ).
Default arguments are the arguments passed to a function in correct positional order. By default, a
function. must be called with the correct number of arguments. Meaning that if your function expects
2 arguments, you have to call the function with 2 arguments, not more, and not less.
Arbitrary Arguments (*ARGS): When it is not known how many arguments that will be passed
into a function, then you can use arbitrary arguments which can pass any number of values. You
just need to add a * before the parameter name in the function definition. It gives result in tuple( )
form.
▪ You can also send arguments with the key = value syntax.
▪ If you do not know how many keyword arguments that will be passed into your function, you can use
keyword arguments.
▪ You just need to add a ** before the parameter name in the function definition.
▪ It gives result in dictionary{} form.
Types of Functions:
➢ Built-in Functions
➢ User Defined Functions
➢ Advanced Functions
Built-in Functions: The Python interpreter has a number of functions that are always available for
use. These functions are called built-in functions. For example, print( ) function prints the given
object to the standard output device (screen) or to the text stream file.
Few examples of In-built Functions : print( ) , type( ) , range( ) , input( ) etc.
User-Defined Functions: Functions that we define ourselves to do the certain specific task are
referred to as user-defined functions.
Advanced Functions: Python has some special or advanced in-built functions. These types of
functions are mostly used for arithmetical operations.
Such types of functions are also used to perform a specific task on a sequence like list, tuple etc.
Using such types of functions, we can also create inline functions for the specific operation.
Example: map( ) , filter( ) , reduce( ) , anonymous.
Global Variables: Global variables are created outside the function. A variable created in the main
body of the Python code is a global variable and belongs to the global scope. A Global variable can
be accessed from anywhere in the program as its scope is global. Global variables are available from
within any scope, global and local.
Points to be remember:
▪ More than one variable, with the same name cannot be exists in the same scope, means multiple local
variables with the same name cannot exists in the same function & multiple global variables with
the same name cannot exists in the main body of the python program.
▪ Multiple variables with the same name can exist in the different scope.
Function Process:
return statement in python: The return keyword is used to exit the function & return a value.
Statements or code after the return line will not be executed. 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.
Advanced Functions: These functions can be applied to each item of any iterative variable (list,
tuple, set etc.) Some of the advanced functions used in Python are discussed below.
map( ): This function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterative variable (list, tuple etc.). The map( ) function
executes a specified function for each item in a variable. The item is sent to the function as a
parameter. It then performs a specific operation on such item(element) and gives separate result for
each operation or item.
filter( ): The filter( ) function returns an iterator where the items are filtered through a function to
test if the item is accepted or not. A Function to be run for each item in the iterative variable and the
variable to be filtered. The filter( ) function performs a specific operation on each item(element) of
the object/variable and gives result only when the condition is true.
reduce( ): This is a useful function for performing computations on a sequence(list, tuple) and
returning the result. It applies a rolling computation to sequential pairs of values in a list and gives a
single output as result.
Anonymous: Anonymous is a in-line function that is defined without a name. While normal
functions are defined using the def keyword, in Python anonymous functions are defined using the
lambda keyword. Hence, anonymous functions are also called lambda functions. A lambda function
can take any number of arguments, but can only have one expression.
File Handling:
▪ Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
▪ The concept of file handling has stretched over various other languages, but the implementation is
either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and
short.
▪ File handling is an important part of any web application.
▪ Python has several functions for creating, reading, updating, and deleting files.
▪ Python treats file differently as text or binary and this is important. Each line of code includes a
sequence of characters and they form text file. Each line of a file is terminated with a special
character, called the EOL or End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun.
open( ) Function: It is a Built-in function used for opening an existing file for working with it. The
open( ) function takes two parameters: open( filename , mode )
modes: files can be opened for different purposes, like reading, writing, and for both reading and writing
purposes. There are different codes for each such purpose which are called in a single name ‘mode’.
The modes are explained as follows.
Mode Description
‘r’ Read mode. Used for reading an existing file. If file not exists, it creates an error.
‘w’ Write mode. Used for opening a file for writing inside it. If file doesn’t exist, it creates a
new file with that name and writes into it.
‘a’ Append mode. Adds contents to an existing file or creates a new file and adds contetnt.
‘r+’ Read and write mode. Opens a file (must exist) for both read and write.
‘w+’ Write and read mode. Same as above but can create a new file if not existing.
‘a+’ For appending an existing file or create and add data to a new file.
‘x’ Exclusive creation mode. Used for creating a new file.
‘t’ Text mode. It is a default mode, in which a file is opened in text mode.
‘b’ Binary mode. Opens a file in binary mode.
▪ Opening Files - Python has a built-in open( ) function to open a file as mentioned above. This
function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
▪ Reading Files - To read a file in Python, we must open the file in reading mode.
▪ Writing Files - In order to write into a file in Python, we need to open it in write mode, append a or
exclusive creation x mode. We need to be careful with the w mode, as it will overwrite into the file
if it already exists. Due to this, all the previous data are erased.
▪ Closing Files - When we are done with performing operations on the file, we need to properly close
the file. Closing a file will free up the resources that were tied with the file. It is done in Python using
the close( ) method.
Python Modules: