0% found this document useful (0 votes)
4 views13 pages

Python Unit 2 Notes

The document provides an overview of conditional statements and loops in Python, detailing the syntax and examples for 'if', 'if-else', 'elif', and nested statements. It also covers the use of loops, including 'while' and 'for' loops, as well as control statements like 'break', 'continue', and 'pass'. Additionally, the document explains file handling, including reading and writing text files, and introduces arrays in Python, highlighting their types and implementations.

Uploaded by

suyoggamer95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Python Unit 2 Notes

The document provides an overview of conditional statements and loops in Python, detailing the syntax and examples for 'if', 'if-else', 'elif', and nested statements. It also covers the use of loops, including 'while' and 'for' loops, as well as control statements like 'break', 'continue', and 'pass'. Additionally, the document explains file handling, including reading and writing text files, and introduces arrays in Python, highlighting their types and implementations.

Uploaded by

suyoggamer95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 2

Conditional Statement :

Conditional statements in Python are used to execute certain blocks of code based on specific
conditions. These statements help control the flow of a program, making it behave differently in
different situations.

[Link] Conditional Statement

If statement is the simplest form of a conditional statement. It executes a block of code if the given
condition is true.

Syntax : Flow Chart for If statement

Example :

age = 20

if age >= 18:

print("Eligible to vote.")

Output

Prof. Neha Daharwal


2. If else Conditional Statement

If Else allows us to specify a block of code that will execute if the condition(s) associated with an if or
elif statement evaluates to False. Else block provides a way to handle all other cases that don't meet the
specified conditions.

Syntax Flowchart of the if – Else Statement

Syntax :

age = 10

if age <= 12:

print("Travel for free.")

else:

print("Pay for ticket.")

Output :

3. elif Statement : elif statement in Python stands for "else if." It allows us to check multiple
conditions, providing a way to execute different blocks of code based on which condition is true. Using
elif statements makes our code more readable and efficient by eliminating the need for multiple nested if
statements.

Syntax

Prof. Neha Daharwal


Example :

age = 25

if age <= 12:

print("Child.")

elif age <= 19:

print("Teenager.")

elif age <= 35:

print("Young adult.")

else:

print("Adult.")

output

4. Nested if..else : Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within
conditions.

Nested if statements allow us to place one if


statement inside another. This helps when we
need to check multiple conditions in a structured
way.

We use conditional statements in Python to


control the flow of code based on more than one
condition.

Prof. Neha Daharwal


Syntax Flowchart

Example :

age = 70

is_member = True

if age >= 60:

if is_member:

print("30% senior discount!")

else:

print("20% senior discount.")

else:

print("Not eligible for a senior discount.")

Output

Loop In Python :
o Loops in Python are used to repeat actions efficiently.
o Loops in Python are used to repeat a block of code multiple times, helping you avoid writing
the same lines again and again. They play a key role in controlling how a program runs,
especially when you need to go through lists, run conditions, or perform repeated tasks.
o The two main types of loops in Python.

1. Python while loop

o A while loop in Python is used to repeat a block of code as long as a certain condition is true. It
keeps running the loop body again and again until the condition becomes false. This is useful
when you don't know in advance how many times the loop should run.

Syntax

Prof. Neha Daharwal


Example :

Output

2. For Loop : For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow
to execute a block of code repeatedly, once for each item in the sequence.

For Loops are used when the number of iterations is known or determinable at the start of the loop.
They work well for iterating over sequences (like lists, tuples, strings or ranges) and performing an
action for each element.
Prof. Neha Daharwal
Syntax :

Here, the iterating_var is a variable to which the value of each sequence item will be assigned during
each iteration. Statements represents the block of code that you want to execute repeatedly.

Example :

Output:

Prof. Neha Daharwal


3. Nested Loops : Python programming language allows to use one loop inside another loop which is
called nested loop.

Syntax :

Example :

Output

Python Control Statement : Python control statements direct the flow of a program's execution
.
Python provides control statements like continue, break, and pass to manage the flow of the loops
efficiently.

1. break Statement : Python break statement is used to terminate the current loop and resumes
execution at the next statement.

The break statement can be used in both Python while and for loops.

Syntax

Prof. Neha Daharwal


Flow Diagram of break Statement

Example

Output

Explanation: The loop prints numbers from p,y,t. because letter == “h”.
2. Continue Statement : The continue statement skips the current iteration and proceeds to the next
iteration of the loop.

The continue statement is just the opposite to that of break. It skips the remaining statements in the
current loop and starts the next iteration.
Prof. Neha Daharwal
Syntax:

Flow Diagram of continue Statement

Example :

Output

Prof. Neha Daharwal


Explanation:
 The loop prints odd numbers from 0 to 9.
 When i is even, the continue statement skips the current iteration.

3. Pass Statement :
The pass statement is a null operation; it does nothing when executed. It's useful as a placeholder for
code that you plan to write in the future.

Syntax

Example :

Output

Reading and Writing to text files in Python: Python provides built-in functions for creating,
reading, and writing files. Python can handle two types of files:
 Text files: Each line of text is terminated with a special character called EOL (End of Line), which
is new line character ('\n') in Python by default.
 A text file in Python is a file that stores data as plain text (readable characters) rather than binary
data. Python allows you to create, read, write, and modify text files easily using built-in functions.
 Text file extensions like .txt, .csv, .log, .py etc.
Prof. Neha Daharwal
[Link] a Text File

Python uses the built-in open() function to work with text files

file = open("[Link]", "r")

[Link] a Text File

Python uses the built-in read() function for reading text files.

file = open("[Link]", "r")


content = [Link]()
print(content)
[Link]()

[Link] to a Text File

Python uses the built-in write() function to write on text files.

file = open("[Link]", "w")


[Link]("Hello Python")
[Link]()

 Binary files: There is no terminator for a line and data is stored after converting it into a machine-
understandable binary format.
 A binary file is a file that stores data in binary format (0s and 1s) instead of readable text.
 Unlike text files, binary files are not human-readable.

Examples of Binary Files

 Images (.jpg, .png)


 Videos (.mp4)
 Audio files (.mp3)

File Modes In Python

When working with files in Python, the file mode tells Python what kind of operations (read, write, etc.)
you want to perform on the file If the file does not exist, it will raise a .FileNotFoundError.

1. Read Mode ('r'): This mode allows you to open a file for reading only.

Example : with open('[Link]', 'r') as file:


content = [Link]()

2. Write Mode ('w') : Opens the file for writing only. If the file exists, its content is deleted. If not, a
new file is created.

Example : with open('[Link]', 'w') as file:


[Link]('Hello, world!')

3. Append Mode ('a') : Opens the file to add content at the end without deleting existing data. If the file
doesn’t exist, it creates a new one.

Prof. Neha Daharwal


Example : with open('[Link]', 'a') as file:
[Link]('\n This is a new college!')

4. Binary Mode ('b') : Used for non-text files like images or audio. Always combined with 'r', 'w', or 'a.

Example : with open('[Link]', 'rb') as file:


data = [Link]()
# Process the binary data

5. Read and Write Mode ('r+') : Opens the file for both reading and writing. Starts at the beginning of
the file. Raises FileNotFoundError if the file doesn’t exist.
Example : with open('[Link]', 'r+') as file:
content = [Link]()
[Link]('\nThis is a new line.')

6. Write and Read Mode ('w+') : This mode allows you to open a file for both reading and writing. If
the file already exists, it will truncate the file to zero length. If the file does not exist, it will create a new
file.

Example : with open('[Link]', 'w+') as file:


[Link]('Hello, world!')
[Link](0)
content = [Link]()

Array In Python :
An array in Python is a structured way to store multiple items of the same data type. Unlike general-
purpose lists, arrays are more memory-efficient and computationally faster for numerical data
operations.
In most traditional programming languages like C or Java, arrays are fixed-size and strictly typed.
Python offers more flexibility but maintains the concept of arrays through various modules and libraries
The basic properties of arrays in Python include:
 Contiguous memory storage
 Homogeneous data types (especially when using the array module or NumPy)
 Efficient access and manipulation via indexing

Array Implementation
Python offers Three main ways to Implement

1. Python Lists: Dynamic and flexible, but less memory-efficient for homogeneous [Link]
Module: A built-in module offering typed arrays, suitable for primitive data types like integers
and floats. While Python lists are flexible, arrays offer better memory and performance for
numerical operations.
Prof. Neha Daharwal
Example : # Creating a list

arr = [10, 20, 30, 40]

print(arr[2])

Output : 30

2. NumPy Arrays: Part of the NumPy library, these arrays are powerful and optimized for
numerical computations.

Example: import numpy as np

arr = [Link]([1, 2, 3, 4])

print(arr[2])

Output : 3

3. The Array Module ; The built-in array module in Python provides more structure and
efficiency for homogeneous data types. When you create an array using array () module.

Example : import array

arr = [Link]('i', [1, 2, 3, 4])

print(arr[1])

Output : 2

Types of Arrays in Python


 SINGLE DIMENSIONAL ARRAY(1D)
 TWO DIMENSIONAL ARRAY (2D)

1. One-Dimensional (1D) Arrays : A 1D array is a single row of elements. It is the simplest form of an
array and is often compared to a list or a row in a spreadsheet.

Example : import numpy as np

arr_1d = [Link]([10, 20, 30, 40, 50])

print(arr_1d[0]) # Output: 10

2. Two-Dimensional (2D) Arrays : A 2D array is essentially an array of arrays. It adds a second


dimension (columns), creating a table or matrix structure.

Example : arr2 = [Link]([[1,2,3], [4,5,6])

print([Link]) #Output (2, 2)

Row 0: [1, 2, 3]

Row 1: [4, 5, 6]

Prof. Neha Daharwal

You might also like