0% found this document useful (0 votes)
20 views25 pages

Conditional Statements: If Statement

This document provides an overview of control structures in Python, including conditional statements, loops, list comprehensions, exception handling, and functions. It explains how to define and use custom functions, including parameters, return values, and variable-length arguments. Additionally, it covers Python modules, object-oriented programming concepts, and the creation of custom modules.

Uploaded by

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

Conditional Statements: If Statement

This document provides an overview of control structures in Python, including conditional statements, loops, list comprehensions, exception handling, and functions. It explains how to define and use custom functions, including parameters, return values, and variable-length arguments. Additionally, it covers Python modules, object-oriented programming concepts, and the creation of custom modules.

Uploaded by

vasantha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT 2

 Control structures in Python are the statements that control the flow of execution in a program.
 They enable the code to make decisions, repeat actions, and manage complex logic.
 Each control structure serves a specific purpose and helps to organize code efficiently and logically.
 Here’s an overview of the main types of control structures in Python:

1. Conditional Statements

 Conditional statements allow the program to execute certain blocks of code only if certain conditions
are met.

 if statement: Executes a block of code if a specified condition is `True`.

```python

if condition:

# Code to execute if the condition is True

```

 if-else statement: Adds an alternative block to execute if the condition is `False`.

```python

if condition:

# Code to execute if the condition is True

else:

# Code to execute if the condition is False

```

 if-elif-else statement: Adds multiple conditions with a final fallback.

```python

if condition1:

# Code to execute if condition1 is True

elif condition2:

# Code to execute if condition2 is True

else:

# Code to execute if none of the conditions above are True

```
2. Loops

 Loops allow the program to execute a block of code multiple times.

 for loop: Iterates over items of a collection (like a list or tuple) or a sequence of numbers.

```python

for item in iterable:

# Code to execute for each item

```Example with `range`:

```python

for i in range(5):

print(i) # Prints numbers from 0 to 4

```

 while` loop: Repeats as long as a specified condition is `True`.

```python

while condition:

# Code to execute while condition is True

```

 break and continue statements:


 break: Exits the loop immediately.

```python

for i in range(5):

if i == 3:

break # Exits the loop when i is 3

print(i)

```

 continue: Skips the current iteration and moves to the next.

```python

for i in range(5):

if i == 3:

continue # Skips printing when i is 3

print(i)

```
3. List Comprehensions

 A concise way to create lists using `for` loops and conditional expressions.

```python

squares = [x ** 2 for x in range(10)]

even_squares = [x ** 2 for x in range(10) if x % 2 == 0]

```

4. Exception Handling

 Manages errors in a program to prevent crashes.


 try-except block: Executes a block of code, catching any errors in the `except` block.

```python

try:

# Code that might raise an exception

except ExceptionType:

# Code to handle the exception

```

 finally block: Executes code regardless of whether an exception occurred.

```python

try:

# Code that might raise an exception

except ExceptionType:

# Code to handle the exception

finally:

# Code that will run no matter what

```

5. Functions

 Functions provide a way to encapsulate code logic into reusable components and control execution
by calling the function.
```python

def my_function(param):

# Code to execute

return result

```

### Example Combined Usage

 Here’s an example combining these control structures:

```python

def find_even_squares(numbers):

even_squares = []

for num in numbers:

if num % 2 == 0:

square = num ** 2

even_squares.append(square)

else:

continue

return even_squares

try:

result = find_even_squares(range(10))

print(result)

except Exception as e:

print(f"An error occurred: {e}")

```

custom functions

● In Python, you can create custom functions to perform specific tasks.


● Functions help make your code more modular, reusable, and easier to understand.
● Let’s go over the basics of creating custom functions.

1. Defining a Function
● To define a function, use the `def` keyword, followed by the function name, parentheses for
parameters (if any), and a colon.
● The function body is indented under the definition line.

```python

def greet():

print("Hello, world!")

```

2. Calling a Function

● Once a function is defined, you can call it by using its name followed by parentheses.

```python

greet() # Outputs: Hello, world!

```

3. Function Parameters

● Functions can accept parameters to make them more flexible.


● Parameters are variables listed inside the parentheses in the function definition.

```python

def greet(name):

print(f"Hello, {name}!")

```

Now, you can pass a `name` when calling `greet`:

```python

greet("Alice") # Outputs: Hello, Alice!

greet("Bob") # Outputs: Hello, Bob!

```

4. Default Parameters

● You can set default values for parameters.


● If no argument is provided, the default value is used.

```python

def greet(name="Guest"):
print(f"Hello, {name}!")

```

```python

greet() # Outputs: Hello, Guest!

greet("Alice") # Outputs: Hello, Alice!

```

5. Return Values

● Functions can return values using the `return` keyword, allowing you to store or use the result in other
parts of your code.

```python

def add(a, b):

return a + b

result = add(5, 3)

print(result) # Outputs: 8

```

6. Multiple Return Values

● A function can return multiple values as a tuple, allowing for multiple outputs.

```python

def get_person():

name = "Alice"

age = 30

return name, age

name, age = get_person()

print(name) # Outputs: Alice

print(age) # Outputs: 30

```

7. Keyword Arguments

● Keyword arguments allow you to pass arguments to a function by name, which makes the function call
clearer and allows for arguments to be passed in any order.

```python

def greet(name, age):

print(f"Hello, {name}! You are {age} years old.")


greet(age=25, name="Alice") # Outputs: Hello, Alice! You are 25 years old.

```

8. Variable-Length Arguments

● Sometimes, you may want a function to accept an arbitrary number of arguments.


● You can use `*args` for positional arguments and `**kwargs` for keyword arguments.
● args: Accepts multiple positional arguments as a tuple.
● kwargs: Accepts multiple keyword arguments as a dictionary.

```python

def print_numbers(*args):

for number in args:

print(number)

print_numbers(1, 2, 3) # Outputs: 1 2 3

```

```python

def print_details(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

print_details(name="Alice", age=30, city="New York")

# Outputs:

# name: Alice

# age: 30

# city: New York

```

9. Lambda Functions

● Lambda functions are small, anonymous functions defined with the `lambda` keyword.
● They are useful for simple operations that need to be defined quickly.

```python

square = lambda x: x * x

print(square(5)) # Outputs: 25

```

● You can also use lambda functions within other functions, such as with `map`, `filter`, or `sorted`
functions.

10. Docstrings in Functions


● To document what a function does, add a docstring (a string at the beginning of the function body).
● This helps others (and yourself) understand the purpose and usage of the function.

```python

def greet(name):

"""Greet a person by their name."""

print(f"Hello, {name}!")

print(greet.__doc__) # Outputs: Greet a person by their name.

```

Full Example: Creating and Using a Custom Function

● Here's a more complete example that combines multiple concepts.

```python

def calculate_area(length=1, width=1):

"""Calculate the area of a rectangle."""

return length * width

# Using the function

area = calculate_area(5, 3)

print(f"Area: {area}") # Outputs: Area: 15

# Using keyword arguments and default parameters

print(calculate_area(width=4)) # Outputs: 4 (uses default length of 1)

```

Summary

- Define functions with `def` and provide a name.

- Use parameters to make functions flexible.

- Return values to make results accessible.

- Utilize default values for optional parameters.

- Use `args` and `kwargs` for variable-length arguments.

- Lambda functions provide quick, anonymous functions.

- Document functions with docstrings.

Custom functions

● Custom functions make your code modular, reusable, and help manage complexity by dividing tasks
into manageable sections.
● Let's dive into each of these Python modules along with an explanation of how to create a custom
module.

1. random Module

● The `random` module provides functions to generate random numbers and to perform random
selections.
● Commonly used functions include:

- random.randint(a, b): Returns a random integer between `a` and `b` (inclusive).

- random.choice(seq): Returns a random element from a sequence like a list or tuple.

- random.shuffle(list): Shuffles the elements in a list in-place.

```python

import random

print(random.randint(1, 10)) # Random integer between 1 and 10

print(random.choice(['apple', 'banana', 'cherry'])) # Random choice from list

```

2. math Module

● The `math` module includes basic mathematical operations and constants.

- math.sqrt(x): Returns the square root of `x`.

- math.pi: Constant representing π.

- math.pow(x, y): Computes `x` raised to the power `y`.

```python

import math

print(math.sqrt(16)) # 4.0

print(math.pi) # 3.141592653589793

print(math.pow(2, 3)) # 8.0

```

3. time Module

● The `time` module provides various time-related functions.

- time.sleep(seconds): Pauses program execution for the specified time in seconds.

- time.time(): Returns the current time in seconds since the epoch.

- time.strftime(format): Formats time according to the given string format.

```python

import time
print("Start")

time.sleep(2) # Pauses for 2 seconds

print("End after 2 seconds")

```

4. os Module

● The `os` module provides functions for interacting with the operating system.

- os.listdir(path): Returns a list of entries in the specified directory.

- os.mkdir(path): Creates a new directory.

- os.remove(path): Removes a specified file.

```python

import os

os.mkdir("test_folder") # Creates a new directory named test_folder

print(os.listdir(".")) # Lists files and directories in the current directory

```

5. shutil Module

● The `shutil` module offers high-level file operations, like copying and removing files.

- shutil.copy(src, dest): Copies a file from `src` to `dest`.

- shutil.rmtree(path): Deletes a directory tree (i.e., a directory and its contents).

```python

import shutil

shutil.copy("source.txt", "destination.txt") # Copies a file

shutil.rmtree("test_folder") # Deletes test_folder and its contents

```

6. sys Module

● The `sys` module provides access to system-specific parameters and functions.

- sys.argv: List of command-line arguments passed to a Python script.

- sys.exit(): Exits the program.

```python

import sys

print(sys.argv) # Prints command-line arguments

sys.exit("Exiting script") # Exits the program with a message


```

7. glob Module

● The `glob` module finds files based on filename patterns.

- glob.glob(pattern): Returns a list of files matching the specified pattern.

```python

import glob

print(glob.glob("*.txt")) # Lists all .txt files in the current directory

```

8. re Module

● The `re` module provides support for regular expressions.

- re.search(pattern, string): Searches for the pattern within the string.

- re.findall(pattern, string): Finds all occurrences of the pattern in the string.

- re.sub(pattern, repl, string): Replaces occurrences of the pattern in the string with `repl`.

```python

import re

text = "The price is 100 dollars"

result = re.search(r"\d+", text)

print(result.group()) # Outputs: 100

```

9. statistics Module

● The `statistics` module provides functions for statistical operations.

- statistics.mean(data): Returns the mean of data.

- statistics.median(data): Returns the median of data.

- statistics.mode(data): Returns the mode of data.

```python

import statistics

data = [10, 20, 20, 40]

print(statistics.mean(data)) # 22.5

print(statistics.median(data)) # 20
print(statistics.mode(data)) # 20

```

10. Creating a Custom Module in Python

● You can create your own module by writing a Python file and saving it with a `.py` extension.
● Then, you can import it into other Python scripts.
● Modules can contain any Python code, including variables, classes, and other imported modules.
● Step-by-Step Example:

1. Create a Python file named `mymodule.py` with some functions.

```python

# mymodule.py

def greet(name):

return f"Hello, {name}!"

def add(x, y):

return x + y

```

2. Import and use the custom module in another Python script.

```python

# main.py

import mymodule

print(mymodule.greet("Alice")) # Outputs: Hello, Alice!

print(mymodule.add(5, 3)) # Outputs: 8

```

● You can also use `from` to import specific functions:

```python

from mymodule import greet

print(greet("Bob")) # Outputs: Hello, Bob!

```

OOP

● Object-oriented programming (OOP) in Python is a programming paradigm that organizes code


around objects, which can represent real-world entities.
● It emphasizes the use of classes and objects and the four core principles of OOP: encapsulation,
abstraction, inheritance, and polymorphism.

1. Classes and Objects


- Class: A blueprint for creating objects (a template that defines data and behavior).

- Object: An instance of a class with specific data.

```python

class Dog:

# Class attribute (shared by all instances)

species = "Canis familiaris"

# Initializer (constructor)

def __init__(self, name, age):

self.name = name # Instance attribute

self.age = age # Instance attribute

# Instance method

def bark(self):

return f"{self.name} says woof!"

# Creating an object of the Dog class

my_dog = Dog("Buddy", 5)

print(my_dog.bark()) # Outputs: Buddy says woof!

```

2.Encapsulation

● Encapsulation is the bundling of data and methods that operate on that data within a class.
● It also restricts direct access to some components (using private attributes).

- Private Attributes:

● Use an underscore `_` prefix (e.g., `_attribute`) to suggest that an attribute or method is intended for
internal use only.
● A double underscore (`__`) triggers name mangling to make it harder to access from outside.

```python

class BankAccount:

def __init__(self, owner, balance=0):

self.owner = owner

self.__balance = balance # Private attribute

def deposit(self, amount):

if amount > 0:
self.__balance += amount

def withdraw(self, amount):

if 0 < amount <= self.__balance:

self.__balance -= amount

return amount

return "Insufficient funds"

def get_balance(self):

return self.__balance

account = BankAccount("Alice", 100)

account.deposit(50)

print(account.get_balance()) # Outputs: 150

```

3. Abstraction

● Abstraction hides complex details from the user and exposes only the essentials.
● In Python, this is achieved by defining public methods that provide meaningful and simplified
interfaces.

```python

class Car:

def __init__(self, make, model):

self.make = make

self.model = model

def start(self):

self.__check_fuel()

print("Car is starting")

def __check_fuel(self): # Private method

print("Checking fuel level")

my_car = Car("Toyota", "Corolla")

my_car.start() # User only calls start(), and details are hidden

```

4. Inheritance

● Inheritance allows a class (child or subclass) to inherit attributes and methods from another class
(parent or superclass).
● It enables code reusability.
```python

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

return "Some sound"

class Dog(Animal): # Inherits from Animal

def speak(self):

return "Woof!"

class Cat(Animal): # Inherits from Animal

def speak(self):

return "Meow!"

dog = Dog("Buddy")

cat = Cat("Whiskers")

print(dog.speak()) # Outputs: Woof!

print(cat.speak()) # Outputs: Meow!

```

5. Polymorphism

● Polymorphism allows methods in different classes to have the same name but behave differently
depending on the class.
● It allows the use of a single interface for different types.

```python

class Bird:

def fly(self):

return "Flies in the sky"

class Penguin(Bird):

def fly(self):

return "Cannot fly but swims well"

def bird_action(bird):

print(bird.fly())

sparrow = Bird()
penguin = Penguin()

bird_action(sparrow) # Outputs: Flies in the sky

bird_action(penguin) # Outputs: Cannot fly but swims well

```

6. Method Overriding and Super()

- Method Overriding: Redefining a method in a subclass to change its behavior.

- super() function: Calls the parent class’s method within an overridden method.

```python

class Vehicle:

def __init__(self, brand, speed):

self.brand = brand

self.speed = speed

def drive(self):

print(f"The {self.brand} is driving at {self.speed} km/h")

class ElectricVehicle(Vehicle):

def __init__(self, brand, speed, battery_capacity):

super().__init__(brand, speed)

self.battery_capacity = battery_capacity

def drive(self):

super().drive()

print(f"Battery capacity: {self.battery_capacity} kWh")

ev = ElectricVehicle("Tesla", 120, 75)

ev.drive()

```

7. Class vs. Instance Variables

- Class Variables: Shared across all instances of a class.

- Instance Variables: Unique to each instance.

```python

class Book:

genre = "Fiction" # Class variable

def __init__(self, title, author):


self.title = title # Instance variable

self.author = author

book1 = Book("1984", "George Orwell")

book2 = Book("To Kill a Mockingbird", "Harper Lee")

print(book1.genre) # Outputs: Fiction

print(book2.genre) # Outputs: Fiction

```

File handling

● File handling in Python allows you to read from, write to, and manage files, making it a crucial tool
for interacting with external files in various formats.
● Here's an overview of the main concepts and methods.

1. Opening and Closing Files

 Use the open() function to open a file, which returns a file object.
 The general syntax is:

```python

file = open("filename", mode)

```

- Modes:

r - Read (default mode): Opens the file for reading. The file must exist.

w - Write: Opens the file for writing. Creates a new file if it doesn’t exist or overwrites an existing file.

a - Append: Opens the file for appending. Data is added to the end of the file without truncating it.

r+ - Read and Write: Allows reading and writing in the file.

b - Binary mode: Used with other modes like `rb` or `wb` for binary files (e.g., images, executable files).

 To ensure files are closed after use, always use `file.close()` or the **with statement**, which closes
the file automatically:

```python

with open("example.txt", "r") as file:

data = file.read()

```

2. Reading Files

 Python provides several methods to read files:

read() :Reads the entire file content as a single string.


```python

with open("example.txt", "r") as file:

data = file.read()

print(data)

```

readline() :Reads one line at a time.

```python

with open("example.txt", "r") as file:

line = file.readline()

while line:

print(line.strip())

line = file.readline()

```

readlines(): Reads all lines and returns them as a list of strings.

```python

with open("example.txt", "r") as file:

lines = file.readlines()

for line in lines:

print(line.strip())

```

3. Writing to Files

 To write content to a file, open it in `'w'` (write) or `'a'` (append) mode.

write(): Writes a string to the file.

```python

with open("example.txt", "w") as file:

file.write("Hello, world!\n")

file.write("This is a new line.")

```

writelines(): Writes a list of strings to the file.

```python

lines = ["First line\n", "Second line\n", "Third line\n"]


with open("example.txt", "w") as file:

file.writelines(lines)

```

4. Appending to Files

 Opening a file in `'a'` mode adds content to the end of the file without overwriting existing data.

```python

with open("example.txt", "a") as file:

file.write("Adding a new line at the end.\n")

```

5. File Pointers and `seek()

 The file pointer represents the current position in the file where reading or writing will occur.

- seek(offset, whence) : changes the file pointer position:

- offset: Number of bytes to move.

- whence: Reference position (0: start, 1: current, 2: end).

```python

with open("example.txt", "r") as file:

file.seek(5) # Moves pointer to the 5th byte

data = file.read() # Reads from the 5th byte onward

print(data)

```

6. Working with Binary Files

 Binary files (e.g., images, videos) are opened in binary mode (`'rb'` or `'wb'`).

```python

# Reading a binary file

with open("image.jpg", "rb") as file:

data = file.read()

# Writing a binary file

with open("copy.jpg", "wb") as file:

file.write(data)

```

7. Checking and Managing Files


 Python's `os` and `os.path` modules offer methods to manage and check file properties.

Checking if a File Exists

```python

import os

if os.path.exists("example.txt"):

print("File exists.")

else:

print("File does not exist.")

```

Deleting a File

```python

import os

if os.path.exists("example.txt"):

os.remove("example.txt")

else:

print("File does not exist.")

```

Renaming a File

```python

import os

os.rename("old_name.txt", "new_name.txt")

```

8. File Handling with `with` Statement

 Using `with` is recommended because it automatically closes the file, even if an error occurs.

```python

with open("example.txt", "r") as file:

data = file.read()

print(data)

```

 Summary of File Handling

1. Opening and Closing Files: `open("filename", mode)` and `file.close()`.


2. Reading:

- `read()` for entire content.

- `readline()` for one line at a time.

- `readlines()` for a list of lines.

3. Writing:

- `write()` for writing strings.

- `writelines()` for a list of strings.

4. Appending: Use `'a'` mode to add data without deleting existing content.

5. Seek and File Pointer: `seek(offset, whence)` to move the file pointer.

6. Binary Files: Open with `'rb'` or `'wb'` for binary data.

7. File Management: `os.path.exists()`, `os.remove()`, and `os.rename()` for file checks and management.

 These operations provide essential control over reading, writing, and managing files in Python.

Writing and parsing text files

 Writing and parsing text files in Python is simple and can be done using basic file handling techniques.
 Here’s a breakdown of how to write data to text files and then parse them to read and process the
contents.

1. Writing to a Text File

 You can write data to a file using the `open()` function with write (`"w"`) or append (`"a"`) modes.

Writing a Simple String

```python

with open("example.txt", "w") as file:

file.write("This is a line of text.\n")

file.write("Here is another line.\n")

```

This code opens `example.txt` for writing, writes two lines, and automatically closes the file when done.

Writing Multiple Lines (from a List)

 If you have a list of strings, you can use `writelines()` to write all lines at once:

```python

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("example.txt", "w") as file:

file.writelines(lines)
```

Appending to an Existing File

 To add content without deleting what’s already in the file, use the append mode `"a"`.

```python

with open("example.txt", "a") as file:

file.write("This line will be added to the end of the file.\n")

```

2. Reading and Parsing a Text File

 Reading a file allows you to extract its content and perform processing.

Reading the Entire Content: Use the `read()` method to read the entire content as a single string.

```python

with open("example.txt", "r") as file:

content = file.read()

print(content)

```

Reading Line by Line :The `readline()` method allows you to read a file line by line, which is useful for
large files.

```python

with open("example.txt", "r") as file:

line = file.readline()

while line:

print(line.strip()) # `.strip()` removes trailing newlines

line = file.readline()

```

Reading All Lines into a List : The `readlines()` method reads all lines into a list, where each element is a
line from the file.

```python

with open("example.txt", "r") as file:

lines = file.readlines()

for line in lines:

print(line.strip())
```

3. Parsing a File with Specific Delimiters

 If your file has structured data, such as CSV format (comma-separated values), you can use Python’s
`csv` module for parsing, or simply split each line by a delimiter.

Using `split()` to Parse Data

 For a text file with a specific delimiter, you can use `split()` to break down each line.

```python

with open("data.txt", "r") as file:

for line in file:

parts = line.strip().split(",") # Splits by comma

print(parts)

```

For example, if `data.txt` contains:

```

Alice,24,Engineer

Bob,30,Doctor

```

The code will output:

```

['Alice', '24', 'Engineer']

['Bob', '30', 'Doctor']

```

4. Writing and Parsing with CSV Files

 Python’s `csv` module is particularly useful for handling CSV files.

Writing a CSV File

```python

import csv

data = [

["Name", "Age", "Occupation"],

["Alice", 24, "Engineer"],

["Bob", 30, "Doctor"]

]
with open("data.csv", "w", newline="") as file:

writer = csv.writer(file)

writer.writerows(data)

```

Reading and Parsing a CSV File

```python

import csv

with open("data.csv", "r") as file:

reader = csv.reader(file)

for row in reader:

print(row)

```

5. Using JSON for Structured Text Data

 For complex data structures, JSON format is popular.


 Python’s `json` module makes it easy to read and write JSON files.

Writing a JSON File

```python

import json

data = {

"name": "Alice",

"age": 24,

"occupation": "Engineer"

with open("data.json", "w") as file:

json.dump(data, file, indent=4)

```

Reading a JSON File

```python

import json

with open("data.json", "r") as file:

data = json.load(file)

print(data)
```

 Summary

Writing to Files:

- Use `write()` for single strings.

- Use `writelines()` for multiple lines.

- Use append mode (`"a"`) to add content without overwriting.

Reading from Files:

- `read()` for entire content.

- `readline()` for line-by-line reading.

- `readlines()` for a list of all lines.

Parsing Structured Text:

- Use `split()` for custom delimiters.

- Use `csv` module for CSV data.

- Use `json` module for JSON data.

 With these techniques, you can easily write and parse text files for various data handling needs.

You might also like