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

Python Manual - Session 4 (Bootcamp)

Uploaded by

laibaabbasi6969
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 views10 pages

Python Manual - Session 4 (Bootcamp)

Uploaded by

laibaabbasi6969
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
You are on page 1/ 10

Python Basics Manual- Session 4

Objective
The objective of this manual is to provide a comprehensive understanding of while loops,
Functions, and Exception Handling in programming. By the end of this manual, readers should
be able to:

1. Understand and implement while loops, Combine loops with conditional statements.
2. Use the break statement and the continue statement within loops.
3. Implement nested loops for handling complex iterations.
4. Understand the Functions, explore the various types of parameters and arguments in
Python functions. Learn the importance of documenting functions using docstrings..
5. Master the use of try-except blocks for handling exceptions, including specific exceptions,
multiple exceptions, and leveraging else and finally clauses for robust error management and
cleanup operations.

Table of Contents
1. While Loop
o Syntax of While Loop
o Conditions in While Loop
o Break Statement
o Continue Statement
o Nested Loops
2. Functions
o Introduction to Functions
o Defining and Calling User-Defined Functions
o Parameters and Arguments
o Return Statement and Function Output
o Variable Scope and Lifetime
o Function Documentation and Code Readability
3. Exception Handling
o Errors, Exceptions, and Exception Hierarchy
o Handling Exceptions Using try-except Blocks
o Handling Specific Exceptions
o Handling Multiple Exceptions
o Using else Clause with try-except Blocks
o Using finally Clause for Cleanup Actions
1. While Loop
Loops are fundamental constructs in programming that allow the execution of a block of code
multiple times. This manual focuses on the while loop, break and continue statements, and
nested loops, which are essential for creating efficient and effective code.

1.1 Syntax of While Loop

The while loop continues to execute a block of code as long as a specified condition is true. The
syntax is as follows:

while condition:
# Code block to be executed

1.2 Conditions in While Loop


Conditions in a while loop determine how long the loop will continue to execute. The loop will
only terminate when the condition evaluates to false.

Example 1: Basic While Loop

count = 0
while count < 5:
print("Count is:", count)
count += 1

Example 2: Using While Loop with User Input

user_input = ""
while user_input.lower() != "exit":
user_input = input("Type 'exit' to stop: ")

1.3. Combining Loops and Conditionals

Loops can be combined with conditional statements to perform complex operations.

number = 0
while number < 10:
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
number += 1
Complex Example

Combining nested conditionals within loops for more intricate logic.

number = 1
while number <= 20:
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
number += 1

1.4. Break Statement

The break statement terminates the loop immediately when encountered.

count = 0
while count < 10:
print(count)
if count == 5:
break
count += 1

Example 1: Breaking Out of a Loop

while True:
response = input("Type 'quit' to exit: ")
if response == 'quit':
break

1.5. Continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
Example 1: Continue with User Input

while True:
num = int(input("Enter a number (0 to skip, 9 to quit): "))
if num == 9:
break
if num == 0:
continue
print("You entered:", num)

1.6. Nested Loops

Nested loops are loops within loops. They are useful for performing repeated actions on a
multidimensional scale.

Example 1: Multiplication Table

i = 1 # Outer loop counter

while i <= 3:
j = 1 # Inner loop counter
while j <= 3:
print(f"{i} * {j} = {i * j}")
j += 1
i += 1
print() # Blank line for better readability

2. Functions
2.1. Introduction to Functions

• Objective: Understand the fundamental concepts of functions and their role in Python
programming.

• Purpose of Functions: Functions encapsulate reusable blocks of code to perform


specific tasks, promoting modularity and improving code organization.

• Advantages of Using Functions:

• Code Reusability: Functions allow code to be reused across different parts of a


program, reducing redundancy.
• Modularity: Breaking down complex tasks into smaller functions enhances
readability and maintainability.
• Abstraction: Functions abstract away implementation details, allowing users to focus
on high-level logic.

Best Practices for Writing Functions:

• Single Responsibility Principle: Each function should perform a single task.


• Descriptive Naming: Use meaningful names for functions and parameters to enhance
clarity.
• Documentation: Document function behavior, parameters, and usage with docstrings for
better understanding.

2.2. Defining and Calling User-Defined Functions

• Objective: Master the syntax and principles of defining and calling user-defined
functions in Python.

• Syntax for Defining Functions:

def function_name(parameters):
# Function body
# Statements

• How to Call Functions:

# Calling a function
function_name(arguments)

• Examples of User-Defined Functions:

# Example function definition


def greet(name):
"""Function to greet a person by name."""
print(f"Hello, {name}!")

# Example function call


greet("Alice")
2.3. Parameters and Arguments

• Objective: Explore different types of parameters and arguments in Python functions to


enhance flexibility and usability.

• Positional Parameters and Arguments: Positional parameters are defined in the order
they appear in the function definition and correspond to the order of arguments passed
during function call.

• Keyword Parameters and Arguments: Keyword parameters are identified by


parameter names during function call, allowing arguments to be passed in any order.

• Default Parameter Values: Parameters can have default values, which are used when no
argument is provided for that parameter.

2.4. Return Statement and Function Output

• Objective: Learn how to use return statements effectively to output data from functions
and understand different types of function outputs.

• Using return Statements: The return statement exits a function and optionally sends a
value back to the calling code.

• Handling Function Outputs: Functions can return single values, multiple values (as
tuples), or complex data structures.

• Examples of Return Values:


# Example function with return statement
def add(a, b):
"""Function to add two numbers and return the result."""
return a + b

2.5. Variable Scope and Lifetime

• Objective: Understand variable scope in Python functions and how variable lifetime
affects program execution.

• Global vs. Local Variables: Variables defined inside a function have local scope, while
variables defined outside functions have global scope.
• Lifetime of Variables Inside Functions: Local variables are created when the function
is called and destroyed when the function exits.

• Scope Rules and Examples:

# Example of variable scope


total = 0 # global variable

def add_to_total(num):
"""Function to add a number to a global total."""
global total
total += num

add_to_total(5)
print(total) # Output: 5

2.6. Function Documentation and Code Readability

• Objective: Grasp the importance of documenting functions using docstrings and adopt
best practices for enhancing code readability and maintainability.

• Writing Docstrings: Docstrings are triple-quoted strings that describe the purpose,
usage, and parameters of a function.

• Importance of Documentation: Well-documented functions are easier to understand,


use, and maintain, especially in collaborative projects.

• Best Practices for Code Readability:

o Use descriptive function and variable names to convey intent.


o Include comments for complex or non-obvious sections of code.

3. Exception Handling
3.1 Errors, Exceptions, and Exception Hierarchy

Errors in Python can broadly be categorized into syntax errors and exceptions. Exceptions are
runtime errors that occur during the execution of a program. Python's exception hierarchy
provides a structured way to handle different types of exceptions.

• Syntax Errors: Occur when there is a mistake in the syntax of a program, preventing it
from running.
• Exceptions: Occur during program execution and can be handled to prevent program
crashes.
3.2. Handling Exceptions Using try-except Blocks

The try-except block in Python allows you to handle exceptions gracefully. Here's the basic
syntax:

try:
# Code block where exceptions may occur
...
except ExceptionType1:
# Handle ExceptionType1
...
except ExceptionType2:
# Handle ExceptionType2
...
else:
# Optional block that executes if no exceptions are raised
...
finally:
# Optional block that always executes, useful for cleanup actions
...

3.3 Handling Specific Exceptions

You can specify different exception types to handle specific errors separately. For example:

try:
# Code block
...
except ValueError:
# Handle ValueError
...
except FileNotFoundError:
# Handle FileNotFoundError
...

3.4 Handling Multiple Exceptions

Multiple except clauses can be used to handle different exceptions within the same try block.

try:
# Code block
...
except (ValueError, TypeError):
# Handle ValueError or TypeError
...
3.5 Using else Clause with try-except Blocks

The else block executes if no exceptions are raised in the try block.

try:
# Code block
...
except ValueError:
# Handle ValueError
...
else:
# Executes if no exceptions were raised
...

3.6 Using finally Clause for Cleanup Actions

The finally block always executes, regardless of whether an exception occurred or not, making
it suitable for cleanup actions like closing files or releasing resources.

try:
# Code block
...
except ExceptionType:
# Handle ExceptionType
...
finally:
# Cleanup code (e.g., closing files)
...

3.7. Raising Exceptions and Creating Custom Exception Classes

You can raise exceptions explicitly using the raise statement.

def divide(x, y):


if y == 0:
raise ValueError("Divisor cannot be zero")
return x / y

4. Conclusion
Understanding loops, functions, and Exception Handling is crucial for writing efficient and
effective code. Mastery of these concepts allows for the creation of complex and dynamic
programs. Practice with various examples and applications to solidify your understanding and
improve your programming skills.

You might also like