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

Notes BCA2 Rev NEP Python DSC-8 Unit1

Uploaded by

apoorvagfgchcs
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)
9 views25 pages

Notes BCA2 Rev NEP Python DSC-8 Unit1

Uploaded by

apoorvagfgchcs
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/ 25

BCA II Semester (Rev NEP)

Python Programming (C2BCA1T2)


---------------------------------------------------------------------------------------------------------------------------------------
SYLLABUS
Unit-I 15 hrs
Introduction: Installing Python, Simple program using Python, Expressions and Values,Variables
and Computer, Memory, error detection, multiple line statements, Designing and using functions,
functions provided by Python, Tracing function calls in memory model, omitting return statement.
Working with Text: Creating Strings of Characters, Using Special Characters in Strings, Creating a
Multiline String, Printing Information, Getting Information from the Keyboard, A Boolean Type,
Choosing Statements to Execute, Nested If Statements, remembering the Results of a Boolean
Expression Evaluation.

Unit-II 15 hrs
A Modular Approach to Program Organization: Importing Modules, Defining Your Own
Modules, Testing Code Semi Automatically Grouping Functions Using Methods: Modules, Classes,
and Methods, Calling Methods the Object-Oriented Way, Exploring String Methods, Underscores,
Storing Collections of Data Using Lists: Storing and Accessing Data in Lists, modifying Lists,
Operations on Lists, Slicing Lists, Aliasing, List Methods, Working with a List of Lists.

Unit-III 15 hrs
Repeating Code Using Loops: Processing Items in a List, Processing Characters in Strings,
Looping, Over a Range of Numbers, Processing Lists Using Indices, Nesting Loops in Loops,
Looping Until a Condition Is Reached, Repetition Based on User Input, Controlling Loops Using
Break and Continue. Reading and Writing Files: Kinds of files, Opening a File, Techniques for
Reading Files, Files over the Internet, Writing Files, and Writing Algorithms That Use the File-
Reading Techniques, Multiline Records.

Unit-IV 15 hrs
Storing Data Using Other Collection Types: Storing Data Using Sets, Storing Data Using Tuples,
Storing Data Using Dictionaries, Inverting a Dictionary, Using the In Operator on Tuples, Sets, and
Dictionaries, Comparing Collections. Collection of New Information Object-Oriented Programming:
Understanding a Problem Domain, Function “Isinstance”, Class Object, and Class Book, writing a
Method in Class Book. Plugging into Python Syntax: More Special Methods. Creating Graphical
User interface: Building a Basic GUI, Models, Views, and Controllers, Customizing the Visual Style
Introducing few more Widgets, Object-Oriented GUIs, Keeping the Concepts from Being a GUI
Mess.

Textbooks:
1. Introduction to Python Programming, Gowrishankar S et al., CRC Press, 2019.
2. Data Structures and Program Design Using Python, D Malhotra et al., Mercury Learning and
Information LLC, 2021.

References:
1. Think Python How to Think Like a Computer Scientist, Allen Downey et al., 2nd
Edition, Green Tea Press. Freely available online @
https://www.greenteapress.com/thinkpython/thinkCSpy.pdf, 2015.
2. Python Data Analytics: Data Analysis and Science Using Pandas, matplotlib, and the
Python Programming Language, Fabio Nelli, Apress®, 2015
3. Advance Core Python Programming, MeenuKohli, BPB Publications, 2021.
4. Core PYTHON Applications Programming, Wesley J. Chun, 3rd Edition, Prentice Hall, 2012.
5. Automate the Boring Stuff, Al Sweigart, No Starch Press, Inc, 2015.
6. http://www.ibiblio.org/g2swap/byteofpython/read/
7. https://docs.python.org/3/tutorial/index.html
BCA II Semester (Rev NEP)
Python Programming (C2BCA1T2)
---------------------------------------------------------------------------------------------------------------------------------------
STUDY MATERIAL
UNIT-I
History of Python
Python was created by Guido van Rossum in the late 1980s and was officially released
in 1991. It was developed at Centrum Wiskunde & Informatica (CWI) in the Netherlands as
a successor to the ABC programming language.

Key Milestones in Python’s History:


 1980s: Guido van Rossum worked on the ABC language but wanted a more extensible
and powerful language.
 1989: He started developing Python as a side project during Christmas.
 1991: Python 1.0 was released with features like exception handling, functions, and core
data types.
 2000: Python 2.0 introduced list comprehensions and garbage collection.
 2008: Python 3.0 was released with improvements like better Unicode support and print
as a function.
 Present: Python continues to evolve, with Python 3.x being widely used in web
development, AI, machine learning, and automation.

The name "Python" was inspired by Guido’s love for the British comedy show Monty
Python's Flying Circus, rather than the snake.

Installing Python
To start programming in Python, you need to install it on your system. Python is
available for Windows, macOS, and Linux.

1. Downloading Python
 Visit the official Python website: https://www.python.org/downloads/
 Download the latest stable version for your operating system.

2. Installing Python on Different OS

Windows Installation
1. Run the downloaded .exe file.
2. Important: Check the box "Add Python to PATH" before clicking Install.
3. Click Install Now and follow the installation process.
4. Verify the installation by opening the Command Prompt (Win + R → type cmd) and typing:

python --version

This should display the installed


Python version.
macOS Installation

Method 1: Using Installer


1. Download the .pkg installer from the Python website.
2. Open the installer and follow the installation steps.

Method 2: Using Homebrew (Recommended)


If you have Homebrew installed, open the terminal and run:
brew install python

To verify the installation, type:

python3 --version

Linux Installation

Ubuntu/Debian

Use the following command:

sudo apt update


sudo apt install python3

Verify installation:

python3 --version

Fedora

sudo dnf install python3

Arch Linux

sudo pacman -S python

3. Running Python

Once installed, you can run Python using:

 IDLE (built-in Python editor).


 Command Line/Terminal:

python

or

python3

 Integrated Development Environments (IDEs) like VS Code, PyCharm, or Jupyter Notebook.


Simple Programs Using Python
Here are some basic Python programs to help you get started:
1. Hello World (First Python Program)
The simplest program to print output on the screen.
print("Hello, World!")
Output:
Hello, World!

2. Taking User Input


name = input("Enter your name: ")
print("Hello, " + name + "!")
Output:
Enter your name: Alice
Hello, Alice!

3. Simple Calculator (Addition of Two Numbers)


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("The sum is:", sum)

Output:
Enter first number: 5
Enter second number: 3
The sum is: 8.0

Expressions and Values in Python


In Python, an expression is a combination of values, variables, and operators that
produces a result. Every expression evaluates to a value.

1. Types of Expressions in Python


a) Arithmetic Expressions
These involve numerical operations like addition, subtraction, multiplication, etc.
x = 10 + 5 # Addition
y = 20 - 3 # Subtraction
z = 4 * 2 # Multiplication
w = 10 / 2 # Division
print(x, y, z, w)

Output:
15 17 8 5.0

Other arithmetic operators:

Operator Description Example Output


+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 2 * 3 6
/ Division 10 / 3 3.3333
// Floor Division 10 // 3 3
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
b) Relational (Comparison) Expressions

These expressions compare values and return a Boolean (True or False).

a = 10
b = 5
print(a > b) # True
print(a == b) # False
print(a <= b) # False

Comparison Operators:

Operator Meaning Example Output


== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 10 > 5 True
< Less than 2 < 4 True
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 3 <= 2 False

c) Logical Expressions

Logical expressions use Boolean operators (and, or, not) to combine conditions.

x = 5
y = 10
print(x > 3 and y < 20) # True
print(x < 3 or y > 15) # False
print(not (x > y)) # True

Logical Operators:

Operator Meaning Example Output


and True if both are true True and False False
or True if at least one is true True or False True
not Negates the Boolean value not True False

d) Assignment Expressions

Assignment expressions store a value in a variable using =.

a = 10
b = a + 5
print(b) # 15

Python 3.8 introduced the Walrus operator (:=) for inline assignments:

print(num := 5) # Assigns 5 to num and prints 5


e) String Expressions

Strings can be manipulated using expressions.

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Concatenation
print(result) # Hello World

f) Membership Expressions

Checks if a value exists in a sequence (in or not in).

text = "Python"
print("y" in text) # True
print("z" not in text) # True

Evaluating Expressions

Python evaluates expressions from left to right based on operator precedence.

Operator Precedence Table

Precedence Operators
Highest () (Parentheses)
2 ** (Exponentiation)
3 *, /, //, % (Multiplication & Division)
4 +, - (Addition & Subtraction)
5 ==, !=, >, <, >=, <= (Comparison)
6 not
7 and
Lowest or

Example demonstrating precedence:

result = 5 + 2 * 3 # Multiplication (*) is evaluated first


print(result) # Output: 11

Use parentheses to change precedence:

result = (5 + 2) * 3
print(result) # Output: 21

Variables and Computer Memory:


Variables and Computer Memory in Python
What is a Variable?

A variable in Python is a named storage location in memory that holds a value. It acts as a
container that stores data, which can be modified during program execution.

Declaring and Assigning Variables

Python allows dynamic variable declaration without specifying a data type.

x = 10 # Integer
name = "Alice" # String
price = 99.99 # Float
is_active = True # Boolean

Here, x, name, price, and is_active are variables storing different types of values.

Rules for Naming Variables

 Can contain letters, digits, and underscores (_).


 Cannot start with a digit (e.g., 1name is invalid).
 Case-sensitive (name and Name are different).
 Cannot use Python keywords like if, else, while, etc.
 Should be meaningful (e.g., age = 25 is better than x = 25).

Valid Variable Names:

my_name = "John"
age = 21
_total_price = 500

Invalid Variable Names:

1name = "Alice" # Starts with a number


my-name = "Bob" # Uses a hyphen
if = 10 # Uses a reserved keyword

Memory Management in Python

When a variable is assigned a value, Python internally:

1. Allocates memory for the value.


2. Stores the reference of the memory location in the variable.

Checking Memory Address (id function)

Each variable in Python has a unique memory address that can be accessed using the id()
function.

x = 50
print(id(x)) # Output: Memory address of x
Example Output:

140719570780752

If another variable stores the same value, it may point to the same memory address (because of
Python’s memory optimization techniques like interning).

a = 50
b = 50
print(id(a), id(b)) # Both have the same memory address

Variable Reassignment and Memory Changes

Python allows reassigning variables to new values, which may change their memory addresses.

x = 10
print(id(x)) # Memory address of x
x = 20 # x now refers to a new object
print(id(x)) # New memory address

Data Types and Memory Usage

Different data types occupy different amounts of memory. Use the sys.getsizeof() function to
check memory usage.

import sys
x = 10
y = "Hello"
z = [1, 2, 3]
print(sys.getsizeof(x)) # Size of integer
print(sys.getsizeof(y)) # Size of string
print(sys.getsizeof(z)) # Size of list

Garbage Collection in Python

Python has automatic garbage collection, which removes unused objects from memory. When
a variable is reassigned, the old value is removed if no other variable refers to it.

a = 100
a = 200 # 100 is garbage collected

The gc module can be used to manually trigger garbage collection.

import gc
gc.collect() # Forces garbage collection

Error detection in Python:


In Python, errors (also called exceptions) occur when the interpreter encounters something it cannot
execute. Understanding these errors helps in debugging and writing robust programs.

Types of Errors in Python

Python errors are classified into two main categories:


1. Syntax Errors (Compile-time errors)
2. Runtime Errors (Exceptions)

1. Syntax Errors (Compile-time Errors)

 These occur when Python cannot understand the code due to incorrect syntax.
 Detected before execution.

Example 1: Missing Colon in if Statement

if 5 > 3
print("Hello")

Error Message:
SyntaxError: expected ':'

Example 2: Incorrect Indentation


def greet():
print("Hello, World!")

Error Message:
IndentationError: expected an indented block

Fix: Always follow Python's indentation rules (4 spaces per level).

2. Runtime Errors (Exceptions)

 These occur while the program is running.


 Even if the syntax is correct, exceptions can cause the program to stop execution.

Common Types of Exceptions

Exception Cause Example


ZeroDivisionError Division by zero 10 / 0
NameError Using an undefined variable print(x) (if x is not defined)
TypeError Operation on incompatible types "10" + 5
IndexError Accessing an invalid index my_list[10] (if my_list has fewer elements)
KeyError Accessing a missing dictionary key my_dict["missing_key"]
ValueError Incorrect data type conversion int("abc")

3. Detecting and Handling Errors (Try-Except Block)

Python provides the try-except mechanism to handle runtime errors.

Example 1: Handling Division by Zero

try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Output:
Error: Division by zero is not allowed.

Example 2: Handling Multiple Errors


try:
num = int(input("Enter a number: ")) # User enters "abc"
print(10 / num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("You cannot divide by zero!")

Example Outputs:

Enter a number: abc


Invalid input! Please enter a number.

Enter a number: 0
You cannot divide by zero!

4. Using else and finally in Error Handling

 else: Executes if no exception occurs.


 finally: Always executes, even if an error occurs.

try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Result:", result)
finally:
print("Execution completed.")

5. Raising Custom Errors (raise)

We can manually trigger errors using raise

num = -5
if num < 0:
raise ValueError("Negative numbers are not allowed!")

Output:
ValueError: Negative numbers are not allowed!
Multiple line statements:

Python allows statements to span multiple lines using different techniques. This helps improve
readability, especially for long expressions.

1. Using Backslash (\) for Explicit Line Continuation

The backslash (\) allows breaking a single statement across multiple lines.

Example: Long Arithmetic Expression

result = 10 + 20 + 30 + \
40 + 50 + 60
print(result) # Output: 210

Example: Function Call with Multiple Arguments


def add(a, b, c):
return a + b + c

sum_value = add(10,
20,
30)
print(sum_value) # Output: 60

Note: The backslash (\) must be the last character on the line, or an error will occur.

2. Using Parentheses (), Brackets [], or Braces {}

Python automatically extends statements inside:

 Parentheses () (for function calls or expressions)


 Square brackets [] (for lists)
 Curly braces {} (for dictionaries or sets)

Example: Using Parentheses (())

total = (10 + 20 + 30 +
40 + 50 + 60)
print(total) # Output: 210

Example: List Spread Across Multiple Lines


numbers = [
1, 2, 3,
4, 5, 6
]
print(numbers) # Output: [1, 2, 3, 4, 5, 6]

Example: Dictionary Spread Across Multiple Lines


student = {
"name": "Alice",
"age": 21,
"course": "BCA"
}
print(student) # Output: {'name': 'Alice', 'age': 21, 'course': 'BCA'}

3. Using Triple Quotes (""" """ or ''' ''') for Multi-line Strings

Triple quotes allow writing multi-line strings.

Example: Multi-line String


message = """This is a long message
that spans multiple lines
in Python."""
print(message)

Example: Multi-line Comment Using Triple Quotes


"""
This is a multi-line comment.
Python ignores it during execution.
"""
print("Hello, World!")

4. Using ; (Semicolon) for Multiple Statements on One Line

Though not recommended, Python allows multiple statements on a single line using ;

x = 10; y = 20; print(x + y) # Output: 30

Designing and using functions:


Functions are reusable blocks of code that perform specific tasks. They help in organizing
code, improving readability, and reducing redundancy.

1. Defining a Function

A function is defined using the def keyword, followed by the function name and parentheses ().

def function_name(parameters):
"""Optional docstring (describes function)"""
# Function body
return value # Optional return statement

Example: Simple Function


def greet():
print("Hello, welcome to Python!")

greet() # Calling the function

Output:
Hello, welcome to Python!
2. Function with Parameters

Parameters allow functions to accept input values.

Example: Function with One Parameter

def greet(name):
print("Hello,", name)

greet("Alice")
greet("Bob")

Output:
Hello, Alice
Hello, Bob

Example: Function with Multiple Parameters


def add(a, b):
return a + b

result = add(10, 20)


print("Sum:", result)

3. Default Parameter Values

If no argument is provided, default values are used.

def greet(name="Guest"):
print("Hello,", name)

greet() # Uses default value


greet("Charlie") # Overrides default

Output:
Hello, Guest
Hello, Charlie

4. Keyword Arguments

You can specify arguments using key=value format, making the function call more readable.

def student_info(name, age):


print(f"Student Name: {name}, Age: {age}")

student_info(age=21, name="Alice") # Order does not matter

Output:
Student Name: Alice, Age: 21
5. Return Statement

A function can return a value using the return keyword.

Example: Returning a Value

def square(num):
return num * num

result = square(5)
print("Square:", result)

Output:
Square: 25

Example: Multiple Return Values


def calculate(a, b):
sum_value = a + b
product = a * b
return sum_value, product

s, p = calculate(4, 5)
print("Sum:", s)
print("Product:", p)

Output:
Sum: 9
Product: 20

6. Variable-Length Arguments (*args and **kwargs)

Using *args for Multiple Positional Arguments

Allows passing any number of arguments as a tuple.

def total_sum(*numbers):
return sum(numbers)

print(total_sum(10, 20, 30, 40)) # Output: 100

Using **kwargs for Multiple Keyword Arguments

Allows passing any number of keyword arguments as a dictionary.

def display_info(**data):
for key, value in data.items():
print(f"{key}: {value}")

display_info(name="Alice", age=21, course="BCA")

Output:
name: Alice
age: 21
course: BCA

7. Function Scope (Local vs Global Variables)

Local Variable (Inside a Function)

def my_function():
x = 10 # Local variable
print("Inside function:", x)

my_function()
# print(x) # Error: x is not accessible outside the function

Global Variable (Outside a Function)


x = 50 # Global variable

def my_function():
print("Inside function:", x)

my_function()
print("Outside function:", x)

Modifying Global Variables

Use global keyword to modify a global variable inside a function.

x = 10

def modify_global():
global x
x = 20 # Modifying global variable
print("Inside function:", x)

modify_global()
print("Outside function:", x)

Output:
Inside function: 20
Outside function: 20

8. Recursive Functions

A recursive function calls itself until a base condition is met.

Example: Factorial using Recursion

def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print("Factorial of 5:", factorial(5))

Output:
Factorial of 5: 120

Functions provided by Python:

Python provides a rich set of built-in functions that perform common operations without
requiring additional code. These functions are always available and do not require importing any
modules.

1. Categories of Built-in Functions

Python’s built-in functions can be grouped into the following categories:

1. Mathematical Functions (abs(), pow(), round(), etc.)


2. Type Conversion Functions (int(), float(), str(), etc.)
3. String Functions (len(), ord(), chr(), etc.)
4. List and Sequence Functions (len(), min(), max(), sum(), etc.)
5. Input and Output Functions (print(), input())
6. File Handling Functions (open(), close(), read(), etc.)
7. Logical and Boolean Functions (all(), any(), bool())
8. Object Inspection Functions (type(), id(), isinstance())
9. Miscellaneous Functions (enumerate(), zip(), sorted(), reversed())

2. Commonly Used Built-in Functions

(A) Mathematical Functions

Python provides built-in math functions for performing mathematical operations.

Function Description Example Output


abs(x) Returns the absolute value of x abs(-10) 10
pow(x, y) Returns x raised to the power y pow(2, 3) 8
round(x, n) Rounds x to n decimal places round(3.14159, 2) 3.14
min(x, y, ...) Returns the smallest value min(10, 20, 5) 5
max(x, y, ...) Returns the largest value max(10, 20, 5) 20
sum(iterable) Returns the sum of elements in an iterable sum([1, 2, 3]) 6

Example:
print(abs(-7)) # Output: 7
print(pow(3, 3)) # Output: 27
print(round(3.567, 2)) # Output: 3.57

(B) Type Conversion Functions

These functions convert values from one data type to another.


Function Description Example Output
int(x) Converts x to an integer int("10") 10
float(x) Converts x to a floating-point number float("3.14") 3.14
str(x) Converts x to a string str(123) '123'
list(iterable) Converts an iterable into a list list("abc") ['a', 'b', 'c']
tuple(iterable) Converts an iterable into a tuple tuple([1, 2, 3]) (1, 2, 3)

Example:
x = "100"
print(int(x) + 50) # Output: 150

y = 3.75
print(int(y)) # Output: 3

(C) String Functions

Python provides several built-in functions to manipulate strings.

Function Description Example Output


len(s) Returns the length of s len("Python") 6
ord(c) Returns ASCII value of character c ord('A') 65
chr(x) Returns character from ASCII value x chr(65) 'A'

Example:
print(len("Hello")) # Output: 5
print(ord('A')) # Output: 65
print(chr(97)) # Output: 'a'

(D) List and Sequence Functions

Python has built-in functions for working with lists and other sequences.

Function Description Example Output


len(iterable) Returns length of the iterable len([1,2,3]) 3
sorted(iterable) Returns a sorted list sorted([3,1,2]) [1,2,3]
reversed(iterable) Returns an iterator with elements in reverse order list(reversed([1,2,3])) [3,2,1]

Example:
numbers = [5, 3, 8, 1]
print(sorted(numbers)) # Output: [1, 3, 5, 8]
print(list(reversed(numbers))) # Output: [1, 8, 3, 5]

(E) Input and Output Functions

Python provides functions for user interaction and displaying output.


Function Description
print(*objects) Displays output
input(prompt) Accepts user input as a string

Example:
name = input("Enter your name: ")
print("Hello,", name)

(F) File Handling Functions

Python provides built-in functions for file operations.

Function Description
open(filename, mode) Opens a file
read() Reads file content
write(data) Writes data to a file
close() Closes the file

Example:
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()

(G) Logical and Boolean Functions

These functions help in evaluating expressions.

Function Description Example Output


all(iterable) Returns True if all elements are True all([True, True, False]) False
any(iterable) Returns True if at least one element is True any([False, False, True]) True

Example:
values = [True, False, True]
print(all(values)) # Output: False
print(any(values)) # Output: True

(H) Object Inspection Functions

Python provides functions to inspect objects.

Function Description
type(x) Returns the type of x
id(x) Returns the memory address of x
isinstance(x, type) Checks if x is of the specified type
Example:
x = 10
print(type(x)) # Output: <class 'int'>
print(id(x)) # Output: (Memory address)
print(isinstance(x, int)) # Output: True

Tracing function calls in memory model:

How Function Calls Work in Memory?

1. Function Call: A new stack frame is created in the call stack.


2. Execution: Local variables and parameters are stored in the stack frame.
3. Return Value: The function completes execution and its stack frame is removed.
4. Control Returns: The result is returned to the caller function.

Example:
def add(a, b):
result = a + b
return result

def main():
x = 10
y = 20
sum_value = add(x, y)
print("Sum:", sum_value)

main()

Memory Stack Flow:


Step 1: Call main() --> Stack: | main() |
Step 2: Call add(x, y) --> Stack: | add() | main() |
Step 3: Return from add() --> Stack: | main() |
Step 4: Return from main() (Stack Empty, Program Ends)

Tracing with print():


def add(a, b):
print(f"Entering add({a}, {b})")
result = a + b
print(f"Leaving add({a}, {b}) with result {result}")
return result

main()

Output:
Entering add(10, 20)
Leaving add(10, 20) with result 30
Sum: 30

Note:
Each function call creates a stack frame.
Stack memory is freed when the function returns.
Recursion creates multiple stack frames until the base case is met.
Omitting return statement
In Python, functions do not require a return statement, but if omitted, the function returns
None by default.

1. Example: Function Without return

def greet():
print("Hello, welcome to Python!")

result = greet()
print(result) # Output: None

2. Default Return Value (None)


def example():
pass # Empty function

print(example()) # Output: None

3. When to Omit return?

 When a function performs an action but does not need to return data.

def display_message():
print("Processing complete!")

 When using functions for logging or printing.


def log_error():
print("Error occurred!")

 For functions modifying mutable objects like lists.


def modify_list(lst):
lst.append(100) # Changes list in place

4. When return is Required?


If you need a value for further computations
def square(n):
return n * n # Required to use the result

Working with Text: Creating Strings of Characters, Using Special Characters in Strings,
Creating a Multiline String:
1. Creating Strings of Characters

Strings can be created using different methods:

Example: Using Single or Double Quotes

str1 = 'Hello'
str2 = "World"
print(str1, str2) # Output: Hello World

Example: Using Triple Quotes (Multiline Strings)


str3 = '''Python
is a powerful
language.'''
print(str3)

Output:
Python
is a powerful
language.

2. Using Special Characters in Strings


(Escape Sequences)

Python uses escape sequences (\) to include special characters.

Escape Sequence Meaning Example Output


\n New Line "Hello\nWorld" Hello World
\t Tab Space "Hello\tWorld" Hello World
\' Single Quote 'I\'m learning' I'm learning
\" Double Quote "Python is \"fun\"" Python is "fun"
\\ Backslash "C:\\Users\\Name" C:\Users\Name

Example: Using Escape Sequences:


print("Hello\nWorld") # New line
print("Hello\tWorld") # Tab space
print("I\'m learning Python") # Single quote
print("Python is \"fun\"") # Double quote
print("Path: C:\\Users\\Name") # Backslash

3. Creating a Multiline String

Multiline strings can be created using triple quotes (''' or """).

Example: Multiline String

message = """Python is easy to learn.


It is used for web development,
data science, and automation."""
print(message)

Output:
Python is easy to learn.
It is used for web development,
data science, and automation.

Choosing Statements to Execute


In Python, decision-making is controlled using conditional statements such as if, elif, and else.
These statements allow the program to execute different code blocks based on conditions.

1. if Statement (Simple Condition)

The if statement executes a block of code only if the condition is True.

Example: Checking a Number

num = 10
if num > 0: # Condition
print("The number is positive.") # Executed if condition is True

Output:
The number is positive.

2. if-else Statement (Two Choices)

The else block runs if the if condition is False.

Example: Checking Even or Odd

num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")

Output:
Odd number

3. if-elif-else Statement (Multiple Choices)

The elif (else if) statement checks multiple conditions.

Example: Checking Temperature

temperature = 25

if temperature > 30:


print("It's hot.")
elif temperature > 20:
print("It's warm.")
else:
print("It's cold.")

Output:
It's warm.
4. Nested if Statements

An if statement inside another if is called nesting.

Example: Checking Grade

marks = 85

if marks >= 50:


print("You passed!")
if marks >= 80:
print("Excellent score!")
else:
print("You failed.")

Output:
You passed!
Excellent score!

5. Using Logical Operators (and, or, not)

You can combine conditions using:

 and → Both conditions must be True


 or → At least one condition must be True
 not → Reverses the condition

Example: Checking Voting Eligibility

age = 20
citizen = True

if age >= 18 and citizen:


print("You are eligible to vote.")
else:
print("You cannot vote.")

Output:
You are eligible to vote.

Remembering the Results of a Boolean Expression Evaluation:

In Python, Boolean expressions return True or False. You can store these results in variables
and reuse them later to improve code efficiency and readability.

1. Storing Boolean Expressions in Variables

Instead of evaluating the same condition multiple times, you can store the result in a variable.

Example: Storing a Condition in a Variable

is_adult = (age >= 18) # Boolean expression result stored


if is_adult:
print("You are an adult.")
else:
print("You are a minor.")

2. Using Boolean Variables for Decision Making

Stored Boolean values can be used in if statements directly.

Example: Checking Login Status

is_logged_in = True

if is_logged_in:
print("Welcome, user!")
else:
print("Please log in.")

Output:
Welcome, user!

3. Using Boolean Expressions with Logical Operators

Boolean variables can be combined with and, or, and not.

Example: Checking Multiple Conditions

is_raining = False
has_umbrella = True

can_go_out = not is_raining or has_umbrella # Remembering Boolean evaluation

if can_go_out:
print("You can go outside.")
else:
print("Stay indoors.")

Output:
You can go outside.

4. Boolean Values in Lists and Dictionaries

Boolean values can be stored in data structures for quick lookups.

Example: Storing User Permissions in a Dictionary

user_permissions = {
"can_edit": True,
"can_delete": False,
"can_view": True
}

if user_permissions["can_edit"]:
print("User can edit the document.")

Output:
User can edit the document.

5. Short-Circuit Evaluation

Python stops evaluating conditions as soon as the result is determined.

Example: Short-Circuiting with or

is_admin = False
is_moderator = True
if is_admin or is_moderator:
print("Access granted.")

Output:
Access granted.

*****

You might also like