230410116098
PRACTICAL-2
AIM:-Study in detail about Python Language
Python Data Types:- Python data types are actually classes, and the defined
variables are their instances or objects. Since Python is dynamically typed,
the data type of a variable is determined at runtime based on the assigned
value. In general, the data types are used to define the type of a variable. It
represents the type of data we are going to store in a variable and
determines what operations can be done on it. Each programming language
has its own classification of data items. With these datatypes, we can store
different types of data values.
Types of Data Types in Python:-
Python supports the following built-in data types –
Flow Chart Of Python Data Types
230410116098
Numeric Data Types:-
int
float
Complex
String Data Types:-
230410116098
Sequence Data Types:-
List
Tuple
230410116098
Binary Data Types:-
Bytes
Byte array
Dictionary Data Type:-
Set
230410116098
Python – Variables
Python Variables Python variables are the reserved memory locations used to
store values with in a Python Program. This means that when you create a
variable you reserve some space in the memory.
Based on the data type of a variable, memory space is allocated to it. Therefore,
by assigning different data types to Python variables, you can store integers,
decimals or characters in these variables.
Memory Addresses
Data items belonging to different data types are stored in computer's memory.
Computer's memory locations are having a number or address, internally
represented in binary form. Data is also stored in binary form as the computer
works on the principle of binary representation. In the following diagram, a
string May and a number 18 is shown as stored in memory locations.
If you know the assembly language, you will covert these data items and the
memory address, and give a machine language instruction. However, it is not
easy for everybody. Language translator such as Python interpreter performs
this type of conversion. It stores the object in a randomly chosen memory
location. Python's built-in id() function returns the address where the object
is stored.
230410116098
Once the data is stored in the memory, it should be accessed repeatedly for
performing a certain process. Obviously, fetching the data from its ID is
cumbersome. High level languages like Python make it possible to give a suitable
alias or a label to refer to the memory location.
In the above example, let us label the location of May as month, and location
in which 18 is stored as age. Python uses the assignment operator (=) to bind
an object with the label.
The data object (May) and its name (month) have the same id(). The id() of 18
and age are also same.
The label is an identifier. It is usually called as a variable. A Python variable is a
symbolic name that is a reference or pointer to an object.
Creating Python Variables
Python variables do not need explicit declaration to reserve memory space or
you can say to create a variable. A Python variable is created automatically when
you assign a value to it. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example −
Example to Create Python Variables
230410116098
This example creates different types (an integer, a float, and a string) of
variables.
Printing Python Variables
Once we create a Python variable and assign a value to it, we can print it using
print() function. Following is the extension of previous example and shows how
to print different variables in Python: Example to Print Python Variables This
example prints variables.
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles,
and name variables, respectively. When running the above Python
program, this produces the following result –
Deleting Python Variables
You can delete the reference to a number object by using the del statement.
The syntax of the del statement is −
230410116098
Getting Type of a Variable
Youcan getthe datatype of aPython variable using the python built-in
function type() as follows.
Example: Printing Variables Type
230410116098
Casting Python Variables
Youcan specifythedatatype of a variable with the help of casting as
follows: Example This example demonstrates case sensitivity of
variables.
Python Operators Python operators are special symbols used to
perform specific operations on one or more operands. The variables,
values, or expressions can be used as operands. For example,
Python's addition operator (+) is used to perform addition operations
on two variables, values, or expressions. The following are some of
the terms related to Python operators:
Unary operators: Python operators that require one operand to
perform a specific operation are known as unary operators. Binary
operators: Python operators that require two operands to perform a
specific operation are known as binary operators. Operands:
Variables, values, or expressions that are used with the operator to
perform a specific operation.
230410116098
Python Arithmetic Operators:
Python Arithmetic operators are used to perform basic mathematical
operations such as addition, subtraction, multiplication, etc.
The following table contains all arithmetic operators with their symbols,
names, and examples (assume that the values of a and b are 10 and 20,
respectively) –
230410116098
Python logical operators are used to combile two or more conditions and
check the final result. There are following logical operators supported by
Python language. Assume variable a holds 10 and variable b holds 20 then
The following table contains all logical operators with their symbols, names, and
examples −
230410116098
Python Comparison Operators
PythonComparisonoperators compare the values on either side of them
and decide the relation among them. They are also called Relational
operators.
The following table contains all comparison operators with their symbols,
names, and examples (assume that the values of a and b are 10 and 20,
respectively) −
230410116098
Python Assignment operators are used to assign values to variables. Following
is a table which shows all Python assignment operators.
The following table contains all assignment operators with their symbols,
names, and examples –
230410116098
Python Bitwise Operators
Python Bitwise operator works on bits and performs bit by bit operation. These
operators are used to compare binary numbers.
The following table contains all bitwise operators with their symbols, names,
and examples −
230410116098
Python Membership Operators
Python's membership operators test for membership in a sequence, such as
strings, lists, or tuples.
There are two membership operators as explained below –
230410116098
Python If Statement
The if statement in Python evaluateswhether a condition is true or false. It contains
a logical expression that compares data, and a decision is made based on the result
of the comparison.
Syntax of the if Statement
if expression:
# statement(s) to be executed
If the boolean expression evaluates to TRUE, then the statement(s) inside the if block
is executed. If boolean expression evaluates to FALSE, then the first set of code after
the end of the if block is executed.
Flow Diagram (Flowchart) of the if Statement
The below diagram shows flowchart of the if statement −
230410116098
Python if else Statement
The if-else statement in Python isused toexecute a blockofcode when the condition in the if
statement is true, and another block of code when the condition is false.
Syntax of if-else Statement
Thesyntaxofanif-elsestatementin Python is as follows −
if boolean_expression:
# code block to be executed
# when boolean_expression is true
else:
# code block to be executed
# when boolean_expression is false
If the boolean expression evaluates to TRUE, then the statement(s) inside the if block will be
executed otherwise statements of the else block will be executed.
Flowchart of if-else Statement
Thisflowchartshowshowif-elsestatement is used −
230410116098
Python - For Loops
The for loop in Python provides the ability to loop overthe items of any sequence, such as a
list, tuple or a string. It performs the same action on each item of the sequence. This loop
starts with the for keyword, followed by a variable that represents the current item in the
sequence. The in keyword links the variable to the sequence you want to iterate over. A
colon (:) is used at the end of the loop header, and the indented block of code beneath it is
executed once for each item in the sequence.
Syntax of Python for Loop
for iterating_var in sequence:
statement(s)
Statements represents the block of code that you want to execute repeatedly.
Flowchart of Python for Loop
The following flow diagram illustrates the working of for loop −
230410116098
Python - While Loops
A while loop in Python programminglanguagerepeatedly executes a target
statement as long as the specified boolean expression is true. This loop starts with
while keyword followed by a boolean expression and colon symbol (:). Then, an
indented block of statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform
indent. The condition may be any expression, and true is any non-zero value. As
soon as the expression becomes false, the program control passes to the line
immediately following the loop.
Syntax of while Loop
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code.
Python uses indentation as its method of grouping statements.
Flowchart of While loop
The following flow diagram illustrates the while loop −
230410116098
LOOP CONTROL STATEMENTS
230410116098
Python - Functions
A Python function is a block of organized, reusable code that is used to
perform a single, related action. Functions provide better modularity for your
application and a high degree of code reusing. A top-to-down approach towards
building the processing logic involves defining blocks of independent reusable
functions. A Python function may be invoked from any other function by passing
required data (called parameters or arguments). The called function returns its
result back to the calling environment.
Types of Python Functions
Python functions can be categorized into several types based on their origin and
characteristics:
Built-in Functions:
These are pre-defined functions that are readily available in Python without requiring any
explicit import. They perform common tasks and are part of the standard Python library.
Examples include print(), len(), abs(), max(), and min().
User-defined Functions:
These functions are created by the programmer to perform specific tasks tailored to their
program's requirements. They are defined using the def keyword.
230410116098
Defining a Python Function
Function blocks begin with the keyword def followed by the function name and
parentheses ().
Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement; the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments
is the same as return None.
Syntax to Define a Python Function
By default, parameters have a positional behavior and you need to inform
them in the same order that they were defined.
230410116098
Once the function is defined, you can execute it by calling it from another
function or directly from the Python prompt.
Example to Define a Python Function
When this function is called, Hello world message will be printed.
Calling a Python Function
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code. Once the basic
structure of a function is finalized, you can call it by using the function name
itself. If the function requires any parameters, they should be passed within
parentheses. If the function doesn't require any parameters, the parentheses
should be left empty.
Example to Call a Python Function
Following is the example to call printme() function –
Pass by Reference vs Value In programming languages like C and C++, there
are two main ways to pass
variables to a function, which are Call by Value and Call by Reference (also
known as pass by reference and pass by value). However, the way we pass
variables to functions in Python differs from others.
call by value − When a variable is passed to a function while calling, the
value of actual arguments is copied to the variables representing the
formal arguments. Thus, any changes in formal arguments does not get
230410116098
reflected in the actual argument. This way of passing variable is known
as call by value.
call by reference − In this way of passing variable, a reference to the
object in memory is passed. Both the formal arguments and the actual
arguments (variables in the calling code) refer to the same object.
Hence, any changes in formal arguments does get reflected in the actual
argument.
Python
uses pass by reference mechanism. As variable in Python is a label or reference
to the object in the memory, both the variables used as actual argument as
well as formal arguments really refer to the same object in the memory. We
can verify this fact by checking the id() of the passed variable before and after
passing.
Example
In the following example, we are checking the id() of a variable.
Python Function Arguments
230410116098
Function arguments are the values or variables passed into a function when it
is called. The behavior of a function often depends on the arguments passed to
it.
While defining a function, you specify a list of variables (known as formal
parameters) within the parentheses. These parameters act as placeholders for
the data that will be passed to the function when it is called. When the
function is called, value to each of the formal arguments must be provided.
Those are called actual arguments.
Example
Function Argument
Keyword Arguments
Default Arguments
Keyword-only arguments
Arbitrary or Variable-length Arguments
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name. This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords provided to match
the values with parameters.
230410116098
Example 1
Default Arguments
A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
Keyword-only arguments
Those arguments that must be specified by their name while calling the
function is known as Keyword-only arguments. They are defined by placing an
asterisk ("*") in the function's parameter list before any keyword-only
parameters. This type of argument can only be passed to a function as a
keyword argument, not a positional argument. Example
230410116098
Arbitrary or Variable-length Arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
Example
Syntax for a function with non-keyword variable arguments is this –
Python Function with Return Value The return keyword as the last statement in
function definition indicates end
of function block, and the program flow goes back to the calling function.
Although reduced indent after the last statement in the block also implies
return but using explicit return is a good practice.
Along with the flow control, the function can also return value of an expression
to the calling function. The value of returned expression can be stored in a
variable for further processing
Example
The Anonymous Functions
The functions are called anonymous when they are not declared in the
standard manner by using the def keyword. Instead, they are defined using
the lambda keyword.
230410116098
Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
An anonymous function cannot be a direct call to print because lambda
requires an expression
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose purpose
is by passing function stack allocation during invocation for performance
reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as
follows –
Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python
−
Global variables
Local variables
Global vs. Local variables
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. When you call a function, the variables
declared inside it are brought into scope.
230410116098
Example
Python – Lists
List is one of the built-in data types in Python. A Python list is a sequence of
comma separated items, enclosed in square brackets [ ]. The items in a Python
list need not be of the same data type.
Following are some examples of Python lists −
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index
or indices to obtain value available at that index. For example –
Updating Lists You can update single or multiple elements of lists by giving the
slice on the
left-hand side of the assignment operator, and you can add to elements in a
list with the append() method. For example –
Delete List Elements
To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do
not know. For example –
230410116098
Note − remove() method is discussed in subsequent section.
Python List Operations
In Python, List is a sequence. Hence, we can concatenate two lists with "+"
operator and concatenate multiple copies of a list with "*" operator. The
membership operators "in" and "not in" work with list object.
Because lists are sequences, indexing and slicing work the same way for lists as
they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']
Python List Methods
Python includes following list methods −
230410116098
Built-in Functions with Lists
Following are the built-in functions we can use with lists −
230410116098
Arrays In Python
What are arrays? An array is a container which can hold a fix number of items
and these items should be of the same type. Each item stored in an array is
called an element and they can be of any type including integers, floats,
strings, etc. These elements are stored at contiguous memory location. Each
location of an element in an array has a numerical index starting from 0. These
indices are used to identify and access the elements.
Array Representation
Arrays are represented as a collection of multiple containers where each
container stores one element. These containers are indexed from '0' to 'n-
1', where n is the size of that particular array.
Arrays can be declared in various ways in different languages. Below is an
illustration −
Creating Array in Python
To create an array in Python, import the array module and use its array()
function. We can create an array of three basic types namely integer, float
and Unicode characters using this function.
The array() function accepts typecode and initializer as a parameter value
and returns an object of array class.
Syntax
The syntax for creating an array in Python is –
230410116098
Where,
Typecode − The typecode character used to speccify the type of
elements in the array.
Initializer − It is an optional value from which array is initialized. It must
be a list, a bytes-like object, or iterable elements of the appropriate
type.
Example
Adding and Removing Elements
Below methods are used for appending, extending, inserting, and
removing elements from arrays –
230410116098
Information and Utility Methods
These methods are used for obtaining information about arrays and to
perform utility operations −
Manipulating Array Elements
Following methods are used for manipulating array elements, such as
reversing the array or byteswapping values.
Conversion Methods
230410116098
These methods are used to convert arrays to and from bytes, files, lists, and
Unicode strings.
230410116098
Create a DataFrame with Pandas
A data frame is a structured representation of data.
Let's define a data frame with 3 columns and 5 rows with fictional numbers:
Example:
Output:
Interpreting the Output
This is the output:
We see that "col1", "col2" and "col3" are the names of the columns.
Do not be confused about the vertical numbers ranging from 0-4. They tell us
the information about the position of the rows.
In Python, the numbering of rows starts with zero.
230410116098
Now, we can use Python to count the columns and rows.
We can use df.shape[1] to find the number of columns:
We can use df.shape[0] to find the number of rows:
Python Factor Method
Factors (also called divisors) of a number are integers that divide the number
exactly (no remainder).
For example, the factors of 12 are:
1, 2, 3, 4, 6, 12
Example : -
def find_factors(n):
factors = []
for i in range(1, n + 1):
230410116098
if n % i == 0:
factors.append(i)
return factors
num = 12
print("Factors of", num, "are:", find_factors(num))
Output:-
Factors of 12 are: [1, 2, 3, 4, 6, 12]
Use Cases of Factors
Prime checking (a prime has exactly 2 factors: 1 and itself)
Number theory problems
Cryptography
Optimization and divisibility checks
Python File Methods
Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number representing the stream from the OS perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
230410116098
Method Description
seek() Changes the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
Python File read() Method
The read() method returns the specified number of bytes from the file. Default
is -1 which means the whole file.
Syntax
file.read()
Parameter Values
size Optional. The number of bytes to return. Default -1, which
means the whole file.
Example
Read the content of the file "demofile.txt":
f = open("demofile.txt", "r")
print(f.read(33))
Explanation
f = open("demofile.txt", "r"): Opens a file named demofile.txt in read mode.
f.read(33): Reads the first 33 characters from the file.
print(...): Prints those 33 characters to the console.