Unit II Python
Unit II Python
Unit- II
Control Statements in Python:
What are Control Statements in Python?
Control statements are an essential aspect of any programming language, including Python.
Control statements in Python are used to manage the flow of execution of a program based on
certain conditions.
Control statements in Python are a powerful tool for managing the flow of execution. They allow
developers to make decisions based on specific conditions and modify the normal sequential
flow of a program. By using control statements effectively, developers can write more efficient
and effective code.
Types of Control Statements in Python
There are three types of control statements in Python.
while condition:
# statements
if condition:
break
In this syntax, the break statement is used inside a loop (while loop or for loop). When the
condition specified in the if statement is true, the break statement is executed, and the control is
transferred to the next statement after the loop. This means that the loop is terminated, and the
code execution continues from the statement after the loop.
Explanation:
In this example, we have a list called list_of_numbers. We want to find the first even number in
this list. We use a for loop to iterate over the list, and inside the loop, we use an if statement to
check if the current number is even. If the current number is even, we print it as the first even
number, and we use the break statement to exit the loop.
if condition:
continue
In this syntax, when the condition specified in the if statement is true, the continue statement is
executed, and the control is transferred to the next iteration of the loop. This means that the
current iteration is skipped, and the loop continues with the next iteration.
Example of Continue Statement in Python
Output:
1
3
7
9
11
15
Explanation: We have a list of integers called numbers. Only the odd numbers from this list
should be printed. We use a for loop to traverse through the list, and an if statement inside the
loop checks if the current number is even. If the current number is an even integer, we apply the
continue statement to skip the current iteration and proceed to the next. We print the current
number if it is odd.
Pass Statement in Python
The pass statement is a placeholder statement that does nothing. It is used when a statement is
required syntactically, but you don’t want to execute any code. Pass is mostly used as a
placeholder for functions or conditional statements that have not yet been implemented.
while condition:
if condition:
pass
In this syntax, the pass statement is used inside a loop (while loop or for loop) and inside an if
statement. When the pass statement is executed, it does nothing, and the control is transferred to
the next statement after the loop or the if statement.
x = 25
if x > 15:
pass
else:
Explanation: In this example, we have a variable called x that has a value of 10. We want to
print a message when the value of x is greater than 5. We use an if statement to check if the value
of x is greater than 5. Inside the if statement, we use the pass statement as a placeholder for the
code that we haven’t written yet. If the value of x is less than or equal to 5, we print a message.
When we run this program, it will not output anything, as the pass statement does nothing.
However, it serves as a placeholder for the code that we will write in the future.
1. Conditionally executing code: The if-else statement is used to execute specific code
based on a condition. This allows us to selectively execute certain parts of the code based
on the input data or the state of the program.
2. Repeating code: Loops such as for loop and while loop are used to execute a block of
code repeatedly based on a condition. This is useful when we want to perform a specific
operation multiple times, such as processing a list of items or iterating over a range of
numbers.
3. Exiting loops: The break statement is used to exit a loop prematurely when a specific
condition is met. This is useful when we want to terminate a loop when we have found
the desired value or have encountered an error condition.
4. Skipping iterations: The continue statement is used to skip a specific iteration of a loop
when a particular condition is met. This is useful when we want to exclude specific
values from the loop, such as even numbers or duplicates.
5. Handling errors: The try-except statement is used to handle errors that may occur
during the execution of a program. This allows us to gracefully handle errors and prevent
the program from crashing.
Else
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
n this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
a = 200
b = 33
c = 500
Or
Example
a = 200
b = 33
c = 500
if a > b or a > c:
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example
a = 33
b = 200
if not a > b:
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
else:
if statements cannot be empty, but if you for some reason have an if statement with no content,
put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
Python Loops
• while loops
• for loops
With the while loop, we can execute a set of statements as long as a condition is true.
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
Short-Circuiting Techniques in Python
This “laziness” on the part of the interpreter is called “short-circuiting” and is a common
way of evaluating Boolean expressions in many programming languages. Similarly, for an
and expression, python uses a short circuit technique to speed truth value evaluation.
By short-circuiting, we mean the stoppage of execution of a Boolean operation if the truth value
of the expression has been determined already. The evaluation of expression takes place from
left to right. In Python, short-circuiting is supported by various Boolean operators and functions.
or: When the Python interpreter scans or expression, it takes the first statement and checks to see
if it is true. If the first statement is true, then Python returns that object’s value without checking
the second statement. The program does not bother with the second statement. If the first value is
false, only then Python checks the second value, and then the result is based on the second half.
and: For an and expression, Python uses a short circuit technique to check if the first statement is
false then the whole statement must be false, so it returns that value. Only if the first value is
true, does it check the second statement and return the value.
An expression containing and or stops execution when the truth value of expression has been
achieved. Evaluation takes place from left to right.
What is a Text file in Python?
A text file is a computer file that is structured as lines of electronic text. For the purposes of
programming and Python, it is a file containing a single string-type data object. Generally, it is
also encoded by the computer and must be decoded before it can be parsed by a program.
Write String to Text File in Python
Python – Write String to Text File
To write string to a file in Python, we can call write() function on the text file object and pass the
string as argument to this write() function.
In this tutorial, we will learn how to write Python String to a file, with the help of some Python
example programs.
Open the text file in write mode using open() function. The function returns a file object.
Call write() function on the file object, and pass the string to write() function as argument.
Once all the writing is done, close the file using close() function.
#close file
text_file.close()
Prof. Shubhra chinchmalatpure
13 Unit - II
If you try to write a string to an existing file, be careful. When you create a file in write mode
and call write() function, existing data is lost and new data is written to the file.
For instance, in the previous example, we created a file and written some data to it.
Python Program
#open text file
text_file = open("D:/data.txt", "w")
#close file
text_file.close()
Python has the os module that provides us with many useful methods to work with directories
(and files as well).
We can get the present working directory using the getcwd() method of the os module.
This method returns the current working directory in the form of a string. For example,
import os
print(os.getcwd())
In Python, we can change the current working directory by using the chdir() method.
The new path that we want to change into must be supplied as a string to this method. And
we can use both the forward-slash / or the backward-slash \ to separate the path elements.
example,
import os
# change directory
os.chdir('C:\\Python33')
print(os.getcwd())
Output: C:\Python33
Here, we have used the chdir() method to change the current working directory and passed a new
path as a string to chdir().
File Handling in Python
File handling is an important activity in every web app. The types of activities that you can
perform on the opened file are controlled by Access Modes. These describe how the file will be
used after it has been opened.
These modes also specify where the file handle should be located within the file. Similar to a
pointer, a file handle indicates where data should be read or put into the file.
Read Only ('r’): This mode opens the text files for reading only. The start of the file is where
the handle is located. It raises the I/O error if the file does not exist. This is the default mode for
opening files as well.
Read and Write ('r+’): This method opens the file for both reading and writing. The start of the
file is where the handle is located. If the file does not exist, an I/O error gets raised.
Write Only ('w’): This mode opens the file for writing only. The data in existing files are
modified and overwritten. The start of the file is where the handle is located. If the file does not
already exist in the folder, a new one gets created.
Write and Read ('w+’): This mode opens the file for both reading and writing. The text is
overwritten and deleted from an existing file. The start of the file is where the handle is located.
Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet
exist, a new one gets created. The handle is set at the end of the file. The newly written data will
be added at the end, following the previously written data.
Append and Read (‘a+’): Using this method, you can read and write in the file. If the file
doesn't already exist, one gets created. The handle is set at the end of the file. The newly written
text will be added at the end, following the previously written data.
Below is the code required to create, write to, and read text files using the Python file handling
methods or access modes.
"w" – Write: this command will create a new text file whether or not there is a file in the memory
with the new specified name. It does not return an error if it finds an existing file with the same
name – instead it will overwrite the existing file.
f = open("myfile.txt", "w")
#This "w" command can also be used create a new file but unlike the the "x" command the "w" c
With the code above, whether the file exists or the file doesn't exist in the memory, you can still
go ahead and use that code. Just keep in mind that it will overwrite the file if it finds an existing
file with the same name.
This function inserts the string into the text file on a single line.
Based on the file we have created above, the below line of code will insert the string into the
created text file, which is "myfile.txt.”
file.write("Hello There\n")
There are three methods of reading data from a text file in Python. They are:
This function returns the bytes read as a string. If no n is specified, it then reads the entire file.
Example:
f = open("myfiles.txt", "r")
print(f.read())
#The "f.read" prints out the data in the text file in the shell when run.
This function reads a line from a file and returns it as a string. It reads at most n bytes for the
specified n. But even if n is greater than the length of the line, it does not read more than one
line.
f = open("myfiles.txt", "r")
print(f.readline())
Array
What Is an Array?
An array is a data structure that lets us hold multiple values of the same data type. Think of it as
a container that holds a fixed number of the same kind of object. Python makes coding easier for
programmers.
Example:
ypecodes are alphabetic representations that are used to define the type of value the
array is going to store. Some common typecodes are:
Typecode Value
Hence, the index number is always one less than the length of the array.
Example:
One-Dimensional Array
In computer science, arrays serve as a data structure for the contiguous storage of elements
sharing the same data type. Arrays allow for the consolidation of multiple values of a uniform
data type within a single variable. Various types of arrays facilitate the storage of values in
different configurations, with one-dimensional arrays being one of the most frequently employed
structures for this purpose.
Definition of One-Dimensional Array
One Dimensional Array can be defined as follows.
The most basic type of array is a one dimensional array, in which each element is stored linearly
and may be retrieved individually by providing its index value.
A collection of elements with the same data type that are kept in a linear arrangement under a
single variable name is referred to as a one dimensional array.
One Dimensional Array
The one-dimensional array is considered one of the simplest forms of arrays, known for its ease
of use and definition in programming. This type of array is particularly practical as a data
structure because it allows for straightforward initialization and modification of the stored
values.
where,
Simply adding a list to the right side of the One Dimensional Array’s declaration syntax
initializes it. Simply said, we assign values to the defined 1D Array according to the supplied
array size.
data_type array_name [array_size] = {comma_separated_element_list};
Note: The defined Array Size shall not be exceeded by the number of entries supplied in the list.
There are just a few techniques available for assigning and storing values in one dimensional
array. Let’s look at the two most popular approaches to better comprehend.
The elements are allocated in this procedure at the time the 1D Array is declared.
Example
With this approach, the user is prompted to enter an array of items during program execution.
Example of Input Elements in One Dimensional Array:
• C++
#include <iostream>
using namespace std;
int main()
{
int num [5];
cout<<"Enter array elements: \n";
for(int i = 0; i < 5 ; i++)
{
cin >> num[i] ;
}
}
Output
To find out what the elements of a 1D Array are, we may either display the full array or use the
indexing technique to display only the values of the array that we need.
Note: Indexing an array always begins at 0.
cout << arr[3]; // arr[3] i.e. index 3 of the array will print the value
# Modifying an element
my_list[1] = 25
print(f"Modified list: {my_list}")
# Adding elements
# Removing elements
my_list.remove(30) # Removes the first occurrence of the value
popped_element = my_list.pop(2) # Removes and returns element at index
print(f"List after removing elements: {my_list}")
print(f"Popped element: {popped_element}")
# Accessing elements
print(f"NumPy array: {numpy_array}")
print(f"Element at index 3: {numpy_array[3]}")
# Slicing
sliced_array = numpy_array[1:4]
print(f"Sliced array: {sliced_array}")
Using Fromiter()
Fromiter() is useful for creating non-numeric sequence type array however it can create any type
of array. Here we will convert a string into a NumPy array of characters.
import numpy as np
# creating the string
str = "geeksforgeeks"
# creating 1-d array
x = np.fromiter(str, dtype='U2')
print(x)
Output:
['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']
2D Array in Python
A 2D array in python is a two-dimensional data structure used for storing data generally in a
tabular format. For example, if you want to store a matrix and do some computations, how would
you do it in Python? Well, the answer is the use of 2D arrays in Python.
In Python, a two-dimensional array is commonly represented using nested lists, where an outer
list contains multiple inner lists, and each inner list represents a row in the array.
Example using nested lists:
# Creating a 3x3 two-dimensional array (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements
print(f"Element at row 0, column 1: {matrix[0][1]}") # Output: 2
print(f"Element at row 2, column 0: {matrix[2][0]}") # Output: 7
# Modifying an element
matrix[1][2] = 10
print(f"Modified matrix: {matrix}") # Output: [[1, 2, 3], [4, 5, 10], [7, 8, 9]]
# Iterating through the array
print("Iterating through the matrix:")
for row in matrix:
for element in row:
print(element, end=" ")
print()
What is 2D Array in Python & Its Uses
A 2D array in python is a two-dimensional data structure stored linearly in the memory. It means
that it has two dimensions, the rows, and the columns, and thus it also represents a matrix. By
linear data structure, we mean that the elements are linearly placed in memory, and each element
is connected to its previous and next elements.
We visualize a 2D array in a tabular format, but actually, elements are stored linearly in memory.
Elements of a 2D array are contiguously placed in the memory. It means that if one element is
present at the current memory address, the next element will be placed at the next memory
address. This type of storage makes arrays randomly accessible. It means that we can access any
element of the array independently.
In a 2D array, multiple arrays are inserted as elements in an outer array. Each element in a 2D
array is represented by two indices, the row and the column. 2D arrays in python are zero-
indexed, which means counting indices start from zero rather than one; thus, zero is the first
index in an array in python.
2D arrays are used wherever a matrix needs to be represented. We can create a 2D array with n
rows and m columns representing an mxn matrix.
2D arrays are also used to store data in a tabular format. 2D arrays are also used to represent a
grid while working with graphics, as the screen is also represented as a grid of pixels.
array_name=[n_rows][n_columns]
Where array_name is the array's name, n_rows is the number of rows in the array, and
n_columns is the number of columns in the array.
This syntax only creates the array, which means that memory space is reserved for this array, but
we will add the values later.
There is another syntax for creating a 2D array where initialization (creation of array and
addition of elements) is done with a single line of code. This syntax is as follows:
array_name=[[r1c1,r1c2,r1c3,..],[r2c1,r2c2,r2c3,...],. . . .]
Where array_name is the array's name, r1c1, r1c1 etc., are elements of the array. Here r1c1
means that it is the element of the first column of the first row. A 2D array is an array of arrays.
Accessing Values in Python 2D Array
We can directly access values or elements of a 2D array in Python. It can be done by using the
row and column indices of the element to be accessed. It has the following syntax:
array_name[row_ind][col_ind]
Where array_name is the array's name, row_ind is the row index of the element, and col_ind is
the column index of the element.
If we specify only one index while accessing an array, this index is treated as the row index, and
the whole row is returned. It has the syntax:
array_name[row_ind]
Where array_name is the array's name, row_ind is the row index to be accessed.
If an index exceeds the size, if the array is provided to this function, it returns the index out of
range error. Such indices are known as out of bounds. It is further clarified by the examples
below.
arr=[[1,2,3],[4,5,6],[7,8,9]]
print("Element at [1][0]=",arr[1][0])
Output:
Element at [1][0]= 4
Accessing an Internal Array
In this example, we only pass the row index, i.e., 2, to access the 2D array arr. At that location,
another array is present, and thus that array is returned to us.
Code:
arr=[[1,2,3],[4,5,6],[7,8,9]]
print("Element at [2]=",arr[2])
Output:
Element at [2]= [7, 8, 9]
traversing Values in Python 2D Array
As you can see in the above image, the arrows are marked in sequence. The first row is traversed
horizontally, then we come down to the second row, traverse it, and finally come down to the last
row, traversed.
In this example, we traverse the array named arr by using two for loops. The first for loop
iterates the outer array, returning the internal arrays and the second for loop traverses each of the
inner loops, returning the elements.
Code:
arr=[[1,2,3],[4,5,6],[7,8,9]]
for _ in arr:
for i in _:
print(i,end=" ")
print()
Output:
123
456
789
Inserting Values in Python 2D Array
nserting a value in an array means adding a new element at a given index in the array and then
shifting the remaining elements accordingly. Inserting a value would cause the values after to be
shifted forward.
Example using NumPy (for numerical operations and efficiency):
For more advanced numerical operations or when dealing with large datasets, the NumPy library
is highly recommended as it provides efficient array objects.
import numpy as np
# Creating a 2D array using NumPy
numpy_array = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Accessing elements
print(f"Element at row 0, column 1 (NumPy): {numpy_array[0, 1]}") # Output: 2
# Performing array operations (e.g., adding a scalar)
numpy_array_plus_one = numpy_array + 1
print(f"NumPy array after adding 1: {numpy_array_plus_one}")