Advanced Python Programming
UNIT – 1
Python Basics:
Identifiers
Definition:
An identifier is the name you use to identify variables, functions, classes, modules, etc.
Rules for Identifiers:
• Can only use letters (A-Z, a-z), digits (0-9), and underscore (_)
• Cannot start with a digit
• Cannot use Python keywords (like if, else, class) as names
Valid Identifiers:
myVar = 10
_name = "Leon"
age1 = 25
Invalid Identifiers:
1name = "Wrong" # Starts with a digit
class = "Invalid" # 'class' is a keyword
Keywords
Definition:
Keywords are reserved words in Python that have special meaning and cannot be used as identifiers.
Examples:
if, else, while, for, break, continue, True, False, def, return, import, class
Example:
if age > 18:
print("You are an adult")
You can’t do this:
def = 5 # 'def' is a keyword
Statements and Expressions
• A statement is a complete instruction in Python (like an entire sentence).
• An expression is a piece of code that produces a value (like a math formula).
Examples:
# Expression: produces value
5+3 # Output: 8
# Statement: complete instruction
x = 5 + 3 # A statement that includes an expression
All expressions can be inside a statement, but not all statements are expressions.
Variables
Definition:
A variable is a name that stores a value. It's like a container.
Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example:
name = "Leon"
age = 20
You can change variable values anytime:
age = 22 # updates the value
Variable Names:
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Example:
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Multi Words Variable Names:
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
1. Camel Case:
Each word, except the first, starts with a capital letter:
myVariableName = "John"
2. Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
3. Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This
is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables
The Python print() function is often used to output variables.
Example:
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with the + operator, Python will give you
an error:
Example
x=5
y = "John"
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples in the previous pages) are known as
global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example:
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will be local, and can only be used
inside the function. The global variable with the same name will remain as it was, global and with the original
value.
Example:
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that
function.
To create a global variable inside a function, you can use the global keyword.
Example:
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside a function.
Operators
Definition:
Operators are symbols that perform operations on variables or values.
Types of Operators:
Type Operators Example
Arithmetic + - * / % // ** a + b, a * b
Assignment = += -= x += 1 same as x = x + 1
Comparison == != > < >= <= a == b, x > y
Logical and or not x > 5 and x < 10
Bitwise `& ^ ~ << >>`
Examples:
a = 10
b=5
print(a + b) # 15
print(a > b) # True
print(a == 10 or b == 10) # True
What is Precedence?
Operator precedence means which operator is evaluated first when there are multiple operators in
one expression.
Think of it like math rules:
* (multiply) happens before + (add).
Example:
x=2+3*4
print(x) # Output: 14, not 20!
Why?
Because 3 * 4 = 12, then 2 + 12 = 14
What is Associativity?
Associativity is the direction in which operators are evaluated if they have the same precedence.
Most operators are left-to-right.
Some (like exponent **) are right-to-left.
Example:
# Left to Right
x = 10 - 5 + 2 # First: 10 - 5 = 5 → then: 5 + 2 = 7
# Right to Left
x = 2 ** 3 ** 2 # First: 3 ** 2 = 9 → then: 2 ** 9 = 512
Operator Precedence Table (High → Low)
Precedence Operators Associativity
Highest () (Parentheses) Left to Right
** (Exponent) Right to Left
+, - (Unary: -x, +x) Right to Left
*, /, //, % Left to Right
+, - (Addition/Subtraction) Left to Right
<, >, <=, >= Left to Right
==, != Left to Right
and Left to Right
or Left to Right
Lowest = (Assignment) Right to Left
More Examples
Example 1:
x = 10 + 2 * 3
# 2 * 3 = 6 → then 10 + 6 = 16
Example 2 (Associativity):
x = 2 ** 3 ** 2
# 3 ** 2 = 9 → 2 ** 9 = 512
Example 3 (Parentheses change everything):
x = (2 + 3) * 4 # 5 * 4 = 20
What Are Data Types?
A data type defines the kind of value a variable can store.
For example:
• A number like 5 is of type int
• Text like "Leon" is of type str
(Data Types In Python 1. Number 2. String 3. Boolean 4. List 5. Tuple 6. Set 7. Dictionary)
Basic Built-in Data Types in Python:
Data Type Description Example
int Integer numbers a = 10
float Decimal numbers b = 3.14
str Text / String name = "Leon"
bool Boolean (True or False) flag = True
list Ordered collection (can change) numbers = [1, 2, 3]
tuple Ordered collection (cannot change) t = (1, 2, 3)
set Unordered, unique items s = {1, 2, 3}
dict Key-value pairs d = {"name": "Leon"}
NoneType Represents “no value” x = None
1. int
x = 10
print(type(x)) # <class 'int'>
2. float
pi = 3.1415
print(type(pi)) # <class 'float'>
3. str
name = "Leon"
print(type(name)) # <class 'str'>
4. bool
is_alive = True
print(type(is_alive)) # <class 'bool'>
5. list
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # <class 'list'>
6. tuple
colors = ("red", "green", "blue")
print(type(colors)) # <class 'tuple'>
7. set
unique_nums = {1, 2, 3, 3}
print(unique_nums) # {1, 2, 3} (no duplicates)
print(type(unique_nums)) # <class 'set'>
8. dict
student = {"name": "Leon", "age": 21}
print(student["name"]) # Leon
print(type(student)) # <class 'dict'>
9. NoneType
x = None
print(type(x)) # <class 'NoneType'>
Complex Numbers in Python
What is a Complex Number?
A complex number is made up of:
• A real part (X)
• An imaginary part (Y)
• Written as:
X + Yj
Where j is the imaginary unit, same as √-1 in math.
Python Examples
Example 1: Only real part
a = complex(5) # Converts 5 to complex → 5 + 0j
print(a) # Output: (5+0j)
Example 2: Real and imaginary parts
b = complex(101, 23)
print(b) # Output: (101+23j)
You Can Also Access Real and Imaginary Parts:
z = complex(4, 5)
print("Real part:", z.real) # 4.0
print("Imaginary part:", z.imag) # 5.0
Output:
Real part: 4.0
Imaginary part: 5.0
Operations with Complex Numbers
a = complex(2, 3) # (2+3j)
b = complex(1, 4) # (1+4j)
print("Addition:", a + b) # (3+7j)
print("Multiplication:", a * b) # (-10+11j)
Notes:
• Complex numbers are immutable (cannot be changed).
• You cannot mix them directly with int or float in some operations without converting.
Getting the Data Type
You can get the data type of any object by using the type() function
Example:
Print the data type of the variable x:
x=5
print(type(x))
What is Mutability?
• A mutable object: its content can be changed after it's created.
• An immutable object: its content cannot be changed. Any change creates a new object.
Mutable Data Types:
These can be modified without creating a new object.
Mutable Types Description
list Ordered, changeable
dict Key-value pairs
set Unordered, unique, changeable
bytearray Like bytes, but changeable
Example:
my_list = [1, 2, 3]
print(id(my_list)) # e.g. 140503922458752
my_list.append(4)
print(id(my_list)) # Same ID → content changed
Immutable Data Types:
These cannot be changed once created.
Immutable Types Description
int, float Numeric types
complex Complex numbers
str Text (string)
tuple Ordered, unchangeable
frozenset Immutable version of set
bytes Immutable byte data
Example:
x = 10
print(id(x)) # e.g. 140503922428336
x = 20
print(id(x)) # Different ID → new object created
Example: Mutable vs Immutable with id()
# Immutable Example (int)
x = 10
print("x ID before:", id(x))
x = 20
print("x ID after:", id(x)) # New ID (new object)
# Mutable Example (list)
my_list = [1, 2, 3]
print("List ID before:", id(my_list))
my_list.append(4)
print("List ID after:", id(my_list)) # Same ID (modified in place)
What is Indentation?
Indentation means spaces or tabs used at the beginning of a line of code.
In Python, indentation is not optional — it defines the structure of your program.
Why is it important?
• It tells Python which lines belong together.
• Used mainly for blocks like if, for, while, functions, etc.
Basic Example:
Correct:
if 5 > 3:
print("Yes") # Indented under 'if'
Incorrect:
if 5 > 3:
print("Yes") # This will give an IndentationError
How much indentation?
• Use 4 spaces (recommended by Python)
• Or a tab, but do not mix both
Example:
x = 10
if x > 5:
print("x is greater than 5")
print("This is inside if block")
print("This is outside if block")
Common Blocks That Need Indentation:
Block Type Example
if, elif, else Control flow
for, while Loops
def Function definitions
class Class definitions
try/except Error handling
Example With Function:
def greet(name):
print("Hello", name)
print("Welcome!")
greet("Leon")
All lines inside the function are indented 4 spaces.
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
What are Comments?
Comments are lines in your code that Python ignores.
They are used to explain the code, make it readable, or temporarily disable lines during testing.
Types of Comments in Python
1. Single-line Comment
Starts with # and continues to the end of the line.
Example:
# This is a single-line comment
name = "Leon" # This sets the name
2. Multi-line Comment (unofficial way)
Python doesn't have a dedicated multi-line comment like other languages,
but we simulate it using triple quotes (''' or """).
Example:
'''
This is a multi-line comment.
Used to describe blocks of code.
'''
print("Hello")
Note: Python actually treats triple quotes as multi-line strings, but they are ignored if not assigned to a variable
— so we use them as multi-line comments.
Practical Use Case
# Calculate the area of a rectangle
length = 5
width = 3
area = length * width
# Print the result
print("Area is:", area)
Built-in Functions Console Input and Console Output
1. Console Input – input()
Purpose:
To take input from the user through the keyboard.
Syntax:
variable = input("Your message here: ")
Example:
name = input("Enter your name: ")
print("Hello,", name)
⚠ Note:
Everything from input() is taken as a string by default.
Example:
age = input("Enter your age: ")
print(age + 1) # Error: Can't add int to str
Solution: Convert input using int() or float():
age = int(input("Enter your age: "))
print(age + 1)
2. Console Output – print()
Purpose:
To display messages or variable values to the user.
Syntax:
print(value1, value2, ..., sep=' ', end='\n')
Examples:
print("Hello, world!") # Simple message
print("Name:", name, "Age:", age) # Print multiple values
Special Parameters:
Parameter Use Example
sep Separator between values print("A", "B", sep="-") → A-B
end What to print at the end print("Hello", end="!") → Hello! (no newline)
Complete Example: Input + Output
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hi", name + "!")
print("Next year, you will be", age + 1)
Sample Output:
Enter your name: Leon
Enter your age: 20
Hi Leon!
Next year, you will be 21
What is Type Conversion?
Type Conversion means changing one data type to another.
There are two types:
Type Description
Implicit Done automatically by Python
Explicit Done manually by the programmer using functions
Implicit Type Conversion (Automatic)
Python automatically converts data types when needed.
Example:
x = 10 # int
y = 2.5 # float
result = x + y
print(result) # 12.5 (float)
print(type(result)) # <class 'float'>
Python converted int to float automatically.
Explicit Type Conversion (Manual)
You force the conversion using built-in functions like:
Function Converts To
int() Integer
float() Float
str() String
bool() Boolean
Examples:
Convert string to int:
age = "20"
age = int(age)
print(age + 1) # 21
Convert int to string:
marks = 85
print("You scored " + str(marks)) # "You scored 85"
Convert float to int:
pi = 3.14
print(int(pi)) # 3 (decimal part removed)
Convert string to float:
height = "5.9"
print(float(height)) # 5.9
Not all conversions are valid.
num = "abc"
print(int(num)) # ValueError: invalid literal for int()
Mini Practice:
Try running this in IDLE:
x = input("Enter number 1: ")
y = input("Enter number 2: ")
# convert to int
x = int(x)
y = int(y)
print("Sum is:", x + y)
What is a Python Library?
A Python Library is a collection of pre-written code (functions, classes, modules) that you can use in your
programs — so you don’t have to write everything from scratch.
Think of it as a toolbox filled with useful tools.
Why Use Libraries?
• Save time
• Reuse tested code
• Access powerful features (math, file handling, web, etc.)
How to Use a Library
You import it in your code using the import statement.
Syntax:
import library_name
Common Built-in Libraries
Library Use Example
math Math functions sqrt(), pow(), floor()
random Random number generation randint(), choice()
datetime Working with dates and time date.today(), now()
os Interact with operating system os.mkdir(), os.getcwd()
sys System-specific info sys.argv, sys.exit()
Examples:
1. math library:
import math
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
2. random library:
import random
print(random.randint(1, 10)) # Random int between 1–10
print(random.choice(['A', 'B', 'C'])) # Random choice from list
3. datetime library:
import datetime
today = datetime.date.today()
print("Today's date:", today)
Aliasing (Optional but useful)
You can rename a library for short-hand:
import math as m
print(m.sqrt(25)) # 5.0
External Libraries
You can also install third-party libraries like:
Library Use Case
numpy Math with arrays
pandas Data analysis
matplotlib Graphs and plots
requests Working with web APIs
pygame Game development
Importing Libraries in Python
A library (or module) in Python is a file that contains ready-made functions and classes which you can reuse
instead of writing everything from scratch.
To use these, we import them into our program.
1. Basic Import
Use import followed by the library name.
import math # importing the math library
print(math.sqrt(25)) # Square root → 5.0
print(math.pi) # Value of π → 3.141592653589793
2. Import with an Alias
You can rename a library using as (shortcut name).
import math as m
print(m.sqrt(16)) # Output: 4.0
print(m.pi) # Output: 3.141592653589793
3. Import Specific Functions
You don’t need the whole library—just import what you need.
from math import sqrt, pi
print(sqrt(36)) # Output: 6.0
print(pi) # Output: 3.141592653589793
4. Import All Functions ( Not Recommended)
from math import *
print(sin(90)) # Uses sin() without math. prefix
Not recommended because it may conflict with other functions having the same name.
5. Importing Multiple Libraries
import math, random
print(math.factorial(5)) # 120
print(random.randint(1, 10)) # Random number between 1 and 10
6. Example with Standard & External Library
• Standard Library (comes with Python):
import datetime
today = datetime.date.today()
print("Today's date:", today)
• External Library (must install first using pip):
import numpy as np # NumPy is not built-in, needs pip install
arr = np.array([1, 2, 3])
print("Numpy array:", arr)
Summary
Method Example Use Case
Basic import import math Use full library
Alias import math as m Shortcuts
Specific function from math import sqrt Cleaner code
Import all from math import * Not recommended
Multiple libraries import math, random Use more than one
** Setting the Data Type **
In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
**Setting the Specific Data Type ***
If you want to specify the data type, you can use the following constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Python Control Flow
Introduction
In Python, control flow refers to the order in which individual statements, instructions, or function calls are
executed or evaluated in a program.
Normally, Python executes code line by line from top to bottom — this is called sequential execution.
However, sometimes we need to make decisions, repeat tasks, or jump to certain parts of code based on
conditions.
That’s where control flow statements come in.
Control flow helps a program to:
• Decide which block of code to execute.
• Repeat certain actions using loops.
• Control how the program exits or skips sections.
Types of Control Flow Statements
Python provides three main categories of control flow statements:
1. Decision-making statements (Selection statements)
2. Looping statements (Iteration statements)
3. Jump statements (Transfer of control)
Decision-Making Statements
Decision-making allows the program to take different paths based on conditions using logical or comparison
operators.
(a) if Statement
Used to execute a block of code only if a certain condition is true.
Syntax:
if condition:
statement
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
(b) if-else Statement
Provides an alternative when the condition is false.
Syntax:
if condition:
statement1
else:
statement2
Example:
age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Output:
Not eligible to vote
(c) if-elif-else Ladder
Used when there are multiple conditions.
Syntax:
if condition1:
statement1
elif condition2:
statement2
else:
statement3
Example:
marks = 75
if marks >= 90:
print("Grade A+")
elif marks >= 75:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Output:
Grade A
(d) Nested if Statement
An if inside another if. Used for checking multiple dependent conditions.
Example:
x = 10
y = 20
if x > 0:
if y > 10:
print("Both conditions are true")
Output:
Both conditions are true
4. Looping Statements (Iteration)
Loops allow you to repeat a block of code several times until a condition is false.
(a) while Loop
Repeats as long as the condition is true.
Syntax:
while condition:
statements
Example:
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
(b) for Loop
Used to iterate over a sequence (list, tuple, string, etc.).
Syntax:
for variable in sequence:
statements
Example 1:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2 (list iteration):
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
5. Jump Statements (Transfer of Control)
Jump statements are used to alter the normal sequence of execution inside loops.
(a) break Statement
Used to exit the loop immediately when a condition is met.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
(b) continue Statement
Skips the current iteration and moves to the next.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
(c) pass Statement
Used as a placeholder when no action is required.
Example:
for i in range(5):
if i == 2:
pass
else:
print(i)
Output:
0
1
3
4
6. Nested Loops
You can place one loop inside another.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
11
12
13
21
22
23
31
32
33
7. Summary Table
Statement Type Purpose Example
if Executes code if condition true if x>0:
if-else Executes one of two blocks if x>0: ... else: ...
for Loops through sequence for i in range(5):
while Loops until condition false while i<5:
break Exits loop early if x==5: break
continue Skips iteration if x==2: continue
pass Placeholder, does nothing pass
8. Example Program Combining All Concepts
for i in range(1, 11):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
This example uses for loop, if-else, and conditional checking together — showing real control flow in action.
9. Conclusion
Control flow is one of the most important concepts in Python programming.
It allows you to decide the order in which instructions are executed, making programs dynamic and
intelligent.
By combining decision statements, loops, and jump statements, we can create powerful logic for tasks like
data processing, automation, games, and AI programs.
In short, control flow gives your program the power to think and repeat — just like the human brain deciding
what to do next.
Strings: Creating and Storing Strings in Python
Introduction
A string in Python is a sequence of characters enclosed within quotes. Strings are one of the most commonly
used data types in programming and are used to store text data such as names, messages, or any sequence of
characters. Python treats strings as immutable, meaning once a string is created, its contents cannot be
changed.
Strings are widely used for displaying messages, reading user input, processing text files, and more.
Creating Strings
In Python, strings can be created by enclosing text in single quotes (‘ ’), double quotes (“ ”), or triple quotes
(‘’’ or “””).
Examples:
# Using single quotes
str1 = 'Hello World'
# Using double quotes
str2 = "Python Programming"
# Using triple quotes for multi-line string
str3 = '''This is a
multi-line string
in Python.'''
All three methods create string objects. The difference is mainly for convenience—for instance, triple quotes
allow multiple lines of text without using the newline character \n.
Storing Strings in Memory
When you create a string in Python, it is stored as an object in memory. Each string object has:
• A unique memory address (ID)
• A reference variable pointing to it
For example:
name = "Leon"
print(id(name))
This will print the memory address (ID) where the string "Leon" is stored.
Python uses a concept called string interning, which means that identical string literals may share the same
memory location to optimize memory usage.
Accessing String Characters in Python
Introduction
A string in Python is a sequence of characters enclosed within quotes. Since strings are sequences, each
character in a string has a fixed position known as an index.
Accessing string characters means retrieving individual letters or groups of letters (substrings) from the
string based on their position.
Python provides several ways to access characters — such as indexing, negative indexing, and slicing.
1. Indexing in Strings
In Python, every character in a string is assigned a unique index value that indicates its position.
Indexing starts from 0 for the first character and increases by 1 for each next character.
Example:
text = "PYTHON"
Character P Y T H O N
Index (forward) 0 1 2 3 4 5
Index (backward) -6 -5 -4 -3 -2 -1
2. Accessing Characters Using Positive Indexing
Positive indexing starts from 0 and counts from left to right.
Example:
word = "HELLO"
print(word[0]) # Output: H
print(word[1]) # Output: E
print(word[4]) # Output: O
Here,
• word[0] accesses the first character,
• word[1] the second, and so on.
If you try to access an index beyond the string length, Python will raise an IndexError.
Example:
print(word[10]) # Error: Index out of range
3. Accessing Characters Using Negative Indexing
Python also supports negative indexing, where indexing starts from the right end of the string.
Index -6 -5 -4 -3 -2 -1
Char P Y T H O N
Example:
text = "PYTHON"
print(text[-1]) # Output: N
print(text[-3]) # Output: H
print(text[-6]) # Output: P
This feature is helpful when you want to access characters from the end of a string without knowing its length.
4. Accessing a Range of Characters (Slicing)
Slicing allows you to access a group of characters (substring) from a string.
Syntax:
string[start:end:step]
• start → index where slicing begins
• end → index where slicing stops (not included)
• step → interval between characters (optional)
Example 1: Basic Slicing
text = "PYTHON"
print(text[0:3]) # Output: PYT
print(text[2:5]) # Output: THO
Example 2: Omitting Start or End
print(text[:4]) # Output: PYTH (from beginning to index 3)
print(text[3:]) # Output: HON (from index 3 to end)
Example 3: Using Step
print(text[0:6:2]) # Output: PTO (every 2nd character)
5. Accessing Characters Using Loops
Sometimes you may want to access each character one by one. You can use a for loop to iterate over the
string.
Example:
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
This approach is useful when you want to perform actions like counting vowels, checking occurrences, etc.
6. Accessing Characters Using while Loop
You can also use a while loop with an index counter.
Example:
text = "HELLO"
i=0
while i < len(text):
print(text[i])
i += 1
Output:
H
E
L
L
O
7. Accessing Characters Using Functions
Python provides some useful built-in functions to handle string data efficiently.
Function Description Example
len() Returns the number of characters in the string len("Python") → 6
max() Returns the highest character (alphabetically) max("apple") → p
min() Returns the smallest character min("apple") → a
ord() Returns Unicode value of a character ord('A') → 65
chr() Returns character for given Unicode value chr(97) → a
Example:
text = "BCA"
print(len(text)) # Output: 3
print(max(text)) # Output: C
print(ord('B')) # Output: 66
8. Two Complete Examples
Example 1: Using Indexing and Slicing
name = "LEONARD"
print("First character:", name[0])
print("Last character:", name[-1])
print("Middle part:", name[2:6])
Output:
First character: L
Last character: D
Middle part: ONAR
Example 2: Loop and Functions
word = "PROGRAM"
print("Characters in the string:")
for ch in word:
print(ch, end=" ")
print("\nLength of word:", len(word))
print("Maximum character:", max(word))
print("Unicode of 'P':", ord('P'))
Output:
Characters in the string:
PROGRAM
Length of word: 7
Maximum character: R
Unicode of 'P': 80
9. Common Errors While Accessing Strings
Error Cause Example
IndexError Accessing index out of range "Hello"[10]
TypeError Using non-integer index "Python"['a']
ValueError Invalid operation while slicing "abc"[1:0:-2] (uncommon)
Conclusion
Accessing string characters is one of the most important concepts in Python programming.
It allows you to retrieve, manipulate, and analyze text data efficiently.
Python provides multiple methods — like indexing, negative indexing, and slicing — making string handling
powerful and flexible.
Using loops and functions together with string operations makes it possible to process any form of text data in
real-world applications like data analysis, natural language processing, and file handling.
The str() Function in Python
Introduction
In Python, the str() function is a built-in function used to convert values into a string (text) format.
It takes any data type (like integer, float, list, or tuple) and converts it into a string representation.
This is especially useful when you want to display or combine values with text, or when working with
input/output operations.
Syntax
str(object)
Parameter:
• object → Any value, variable, or data type that you want to convert into a string.
Returns:
• A string version of the given object.
Example 1: Converting Numbers to Strings
num = 100
text = str(num)
print(text)
print(type(text))
Output:
100
<class 'str'>
Here, str(num) converts the integer 100 into a string "100".
Now it can be used for string operations like concatenation.
Example 2: Converting Float to String
pi = 3.14159
pi_str = str(pi)
print("Value of Pi is " + pi_str)
Output:
Value of Pi is 3.14159
The float value is converted into text and easily joined with another string.
Example 3: Converting List or Tuple to String
data = [10, 20, 30]
result = str(data)
print(result)
print(type(result))
Output:
[10, 20, 30]
<class 'str'>
Even though the output looks similar, it is now stored as a string, not a list.
Example 4: Using str() for Display or Concatenation
name = "Leon"
age = 21
print("My name is " + name + " and I am " + str(age) + " years old.")
Output:
My name is Leon and I am 21 years old.
Without converting age to string, this line would cause an error, because you cannot directly join a number with
a string.
Example 5: Converting Boolean to String
status = True
text = str(status)
print(text)
print(type(text))
Output:
True
<class 'str'>
The Boolean True is converted to a string "True".
Difference Between str() and repr()
Function Purpose Example
str() Gives a user-friendly string form str(10.5) → '10.5'
repr() Gives an unambiguous form (for debugging) repr(10.5) → '10.5'
Generally, str() is used for displaying readable output, while repr() is used by developers for debugging.
Common Use Cases
1. Converting numbers to strings for display.
2. Combining text and variable values in output messages.
3. Reading or writing numeric data in text files.
4. Converting any data type into a printable string format.
Conclusion
The str() function is one of the most commonly used functions in Python.
It helps convert any data type into a string, allowing smoother interaction between text and other data types.
Whether printing variables, writing data to files, or formatting output, str() ensures compatibility and prevents
type errors.
Operations on Strings – Concatenation
Introduction
Concatenation means joining two or more strings together to form a single string.
Python allows us to combine strings easily using the + operator or with string formatting methods.
Concatenation is one of the most common string operations and is useful when displaying messages,
combining user input, or building sentences dynamically.
1. Using the + Operator
The simplest way to join strings is by using the + symbol.
Syntax:
string1 + string2
Example 1:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
Output:
Hello World
Here, both strings are joined with a space " " in between.
2. Concatenating More Than Two Strings
You can concatenate multiple strings at once.
Example 2:
a = "Python"
b = "is"
c = "fun"
print(a + " " + b + " " + c)
Output:
Python is fun
3. Concatenation with Numbers (Type Error)
You cannot directly concatenate a string with a number (int or float).
If you try, Python will show an error.
Example 3:
name = "Leon"
age = 21
print("My name is " + name + " and I am " + age + " years old.")
Output:
TypeError: can only concatenate str (not "int") to str
To fix this, convert the number using str():
print("My name is " + name + " and I am " + str(age) + " years old.")
Output:
My name is Leon and I am 21 years old.
4. Using the join() Method
The join() method can also combine multiple strings (especially lists of strings).
Syntax:
'separator'.join(iterable)
Example 4:
words = ["Python", "is", "awesome"]
result = " ".join(words)
print(result)
Output:
Python is awesome
5. Using f-Strings (Modern Method)
From Python 3.6 onwards, we can use f-strings for a clean and readable way to join strings and variables.
Example 5:
name = "Leon"
course = "BCA"
print(f"My name is {name} and I am studying {course}.")
Output:
My name is Leon and I am studying BCA.
6. Using format() Method
Another method for concatenation is using the format() function.
Example 6:
name = "Leon"
age = 21
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
Output:
My name is Leon and I am 21 years old.
7. Example with User Input
Example 7:
first = input("Enter first name: ")
last = input("Enter last name: ")
full_name = first + " " + last
print("Full Name:", full_name)
Output:
Enter first name: Leon
Enter last name: Marak
Full Name: Leon Marak
8. Example – Concatenating Strings in a Loop
Example 8:
words = ["Python", "Programming", "Language"]
sentence = ""
for w in words:
sentence += w + " "
print(sentence)
Output:
Python Programming Language
9. Advantages of Concatenation
• Easy to merge text dynamically.
• Useful in building output messages.
• Helpful in combining variables with strings.
• Can join list of strings efficiently using join().
10. Summary Table
Method Description Example
+ operator Basic string joining "Hello" + "World"
join() Joins strings from iterable " ".join(["A","B"])
f-string Concise variable insertion f"My name is {name}"
format() Flexible text formatting "{} is {}".format(a,b)
Conclusion
String concatenation in Python allows you to combine text and variable values efficiently.
It can be done using the + operator, join() method, format() function, or f-strings.
Understanding these methods helps in dynamic text generation, report creation, and user interface
messages.
String Comparison in Python
In Python, strings can be compared using comparison operators such as ==, !=, <, >, <=, and >=.
The comparison is lexicographical, meaning it is based on the Unicode value of each character (similar to
dictionary order).
Common Comparison Operators
Operator Description Example
== Checks if two strings are equal "apple" == "apple" → True
!= Checks if two strings are not equal "apple" != "banana" → True
< Checks if left string is smaller "apple" < "banana" → True
> Checks if left string is greater "grape" > "apple" → True
<= Checks if left string is smaller or equal "cat" <= "dog" → True
>= Checks if left string is greater or equal "dog" >= "dog" → True
Example 1: Basic Comparison
str1 = "apple"
str2 = "banana"
print(str1 == str2) # False
print(str1 != str2) # True
print(str1 < str2) # True (because 'a' < 'b')
Example 2: Case Sensitivity
String comparison in Python is case-sensitive.
For example, "Apple" is not equal to "apple".
s1 = "Apple"
s2 = "apple"
print(s1 == s2) # False
print(s1 < s2) # True (because uppercase 'A' has a smaller Unicode value)
Example 3: Ignoring Case in Comparison
To compare strings without considering case, convert both to lowercase (or uppercase) first:
a = "HELLO"
b = "hello"
print(a.lower() == b.lower()) # True
Summary:
• Python compares strings character by character using Unicode values.
• Comparisons are case-sensitive by default.
• Use .lower() or .upper() to perform case-insensitive comparisons.
Slicing and Joining Strings in Python
1. String Slicing
Slicing in Python allows you to extract a portion (substring) of a string using index positions.
The syntax for slicing is:
string[start:end:step]
• start → index where the slice begins (inclusive)
• end → index where the slice ends (exclusive)
• step → how many characters to skip (optional)
Example 1: Basic Slicing
text = "Python Programming"
print(text[0:6]) # Output: Python
print(text[7:]) # Output: Programming
print(text[:6]) # Output: Python
Example 2: Negative Indexing
You can use negative indices to slice from the end of a string.
text = "Python"
print(text[-6:-1]) # Output: Pytho
print(text[-3:]) # Output: hon
Example 3: Step Value
You can also specify a step to skip characters.
text = "Python"
print(text[::2]) # Output: Pto
print(text[::-1]) # Output: nohtyP (reverses the string)
2. String Joining
The join() function is used to combine (join) elements of a list or tuple into a single string.
It is especially useful when you have multiple strings that you want to connect with a separator.
Syntax:
'separator'.join(iterable)
Example 1: Joining with Spaces
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Output: Python is fun
Example 2: Joining with Commas
fruits = ["Apple", "Banana", "Cherry"]
result = ", ".join(fruits)
print(result) # Output: Apple, Banana, Cherry
Example 3: Joining Without Separator
letters = ['H', 'e', 'l', 'l', 'o']
word = "".join(letters)
print(word) # Output: Hello
Summary:
Concept Description Example
Slicing Extracting parts of a string using index "Python"[0:3] → 'Pyt'
Negative Indexing Access from end of string "Hello"[-2:] → 'lo'
Step Slicing Skip characters "Python"[::2] → 'Pto'
join() Combine list of strings " ".join(['I', 'love', 'Python']) → 'I love Python'
Traversing Strings in Python
Traversing a string means accessing each character of the string one by one, usually with a loop.
Since strings in Python are sequences, you can easily loop through them using for or while loops.
1. Traversing using a for loop
The most common and simple way to traverse a string is by using a for loop.
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
Each character is accessed and printed one at a time.
2. Traversing with an Index
You can also use a for loop with range() to access each character by its index.
text = "Python"
for i in range(len(text)):
print("Index", i, "=", text[i])
Output:
Index 0 = P
Index 1 = y
Index 2 = t
Index 3 = h
Index 4 = o
Index 5 = n
Here, len(text) gives the total number of characters, and we access each character using text[i].
3. Traversing using a while loop
You can also use a while loop to traverse strings.
text = "Hello"
i=0
while i < len(text):
print(text[i])
i += 1
Output:
H
e
l
l
o
The loop continues until i reaches the length of the string.
4. Traversing in Reverse Order
To print the string backwards, you can traverse it from the end using negative indexing.
text = "Python"
for i in range(len(text) - 1, -1, -1):
print(text[i])
Output:
n
o
h
t
y
P
Summary:
Method Description Example
For Loop Traverse each character directly for c in "Hello": print(c)
For with Index Access using index for i in range(len(s))
While Loop Use counter variable while i < len(s)
Reverse Traversal Loop from end to start for i in range(len(s)-1, -1, -1)
In short:
Traversing helps you inspect, process, or modify each character of a string — an essential concept for tasks
like counting vowels, reversing strings, or searching characters.
Format Specifiers in Python
Definition:
Format specifiers are symbols or codes used to control how values are displayed or formatted in strings.
They help format text, numbers, and other data types to make output more readable and well-structured.
Python supports format specifiers mainly in three ways:
1. Using the percent (%) operator
2. Using the str.format() method
3. Using f-strings (formatted string literals)
1. Using % (Percent) Formatting
This is the old-style of formatting strings (similar to C language).
You use % followed by a format code to specify how a value should appear.
Syntax:
print("format text %specifier" % (value))
Common Specifiers:
Specifier Description Example Output
%d Integer (decimal) 25
%f Floating-point number 25.500000
%.2f Floating-point (2 decimal places) 25.50
%s String Hello
%c Character A
Example:
name = "Leon"
age = 20
marks = 88.567
print("Name: %s, Age: %d, Marks: %.2f" % (name, age, marks))
Output:
Name: Leon, Age: 20, Marks: 88.57
2. Using str.format() Method
Introduced in Python 3, this is a more flexible and modern way to format strings.
Syntax:
print("My name is {} and I am {} years old.".format(name, age))
Example:
name = "Leon"
age = 20
marks = 88.567
print("Name: {}, Age: {}, Marks: {:.2f}".format(name, age, marks))
Output:
Name: Leon, Age: 20, Marks: 88.57
You can also use index numbers or variable names inside {}:
print("Name: {0}, Age: {1}".format("Leon", 20))
print("Name: {n}, Age: {a}".format(n="Leon", a=20))
3. Using f-Strings (Python 3.6 and Above)
f-strings are the most efficient and readable way to format strings.
Syntax:
print(f"My name is {name} and I scored {marks:.2f}")
Example:
name = "Leon"
age = 20
marks = 88.567
print(f"Name: {name}, Age: {age}, Marks: {marks:.2f}")
Output:
Name: Leon, Age: 20, Marks: 88.57
You can even perform expressions inside {}:
print(f"Next year I will be {age + 1} years old.")
Output:
Next year I will be 21 years old.
4. Common Formatting Options
Code Meaning Example Output
:.2f 2 decimal places f"{3.14159:.2f}" 3.14
:>10 Right align in width 10 f"{'Hi':>10}" " Hi"
:<10 Left align in width 10 f"{'Hi':<10}" "Hi "
:^10 Center align f"{'Hi':^10}" " Hi "
:05d Pad integer with zeros f"{42:05d}" 00042
Summary:
Method Example Output
% Formatting "Name: %s, Age: %d" % ('Leon', 20) Name: Leon, Age: 20
str.format() "Name: {}, Age: {}".format('Leon', 20) Name: Leon, Age: 20
f-String f"Name: {name}, Age: {age}" Name: Leon, Age: 20
In short:
Format specifiers allow you to control how data looks when printed, including alignment, precision, and
data type representation, making your program’s output neat, readable, and professional.
Escape Sequences in Python
Definition:
Escape sequences are special characters in Python strings that represent characters that are difficult or
impossible to type directly, such as newline, tab, backslash, or quotes.
They start with a backslash \ followed by a character.
Escape sequences are used to format text in output or to include special characters in strings.
Common Escape Sequences
Escape Sequence Meaning Example
\n Newline (line break) "Hello\nWorld" → prints on two lines
\t Horizontal tab "Name:\tLeon" → adds space like a tab
\\ Backslash "C:\\Users\\Leon" → prints C:\Users\Leon
\' Single quote 'It\'s fun' → prints It's fun
\" Double quote "He said, \"Hi\"" → prints He said, "Hi"
\r Carriage return "Hello\rWorld" → overwrites beginning of line
\b Backspace "Hello\bWorld" → deletes last character before b
\f Formfeed Rarely used, moves to next page in printers
\v Vertical tab Moves text vertically
Example 1: Newline and Tab
print("Hello\nWorld")
print("Name:\tLeon\nAge:\t21")
Output:
Hello
World
Name: Leon
Age: 21
Example 2: Including Quotes
print('It\'s a sunny day')
print("He said, \"Python is fun\"")
Output:
It's a sunny day
He said, "Python is fun"
Example 3: File Paths and Backslash
path = "C:\\Users\\Leon\\Documents"
print(path)
Output:
C:\Users\Leon\Documents
Using \\ avoids errors caused by a single backslash.
Example 4: Raw Strings
To ignore escape sequences, use a raw string by adding r before the string.
path = r"C:\Users\Leon\Documents"
print(path)
Output:
C:\Users\Leon\Documents
Here, \ is treated literally instead of as an escape character.
Example 5: Backspace and Carriage Return
print("Hello\bWorld") # Backspace removes the last character before b
print("12345\rABCDE") # Carriage return overwrites the beginning
Output:
HellWorld
ABCDE5
Summary
• Escape sequences start with \.
• They allow insertion of special characters in strings.
• Commonly used sequences: \n, \t, \\, \', \".
• Use raw strings (r"...") to ignore escape sequences.
Escape sequences are essential for formatting text, handling file paths, and writing readable output in
Python programs.
Python String Methods
Python provides a wide variety of built-in string methods that allow you to manipulate, analyze, and modify
strings easily.
These methods do not change the original string (strings are immutable), but they return a new string or a
value depending on the method.
1. Changing Case
Method Description Example Output
upper() Converts string to uppercase "hello".upper() "HELLO"
lower() Converts string to lowercase "HELLO".lower() "hello"
capitalize() Capitalizes first character "python".capitalize() "Python"
title() Capitalizes first character of each word "python programming".title() "Python Programming"
swapcase() Swaps case of each character "PyTHon".swapcase() "pYthON"
Example:
text = "python programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.title()) # Python Programming
print(text.swapcase()) # PYTHON PROGRAMMING → pYTHON PROGRAMMING
2. Searching in Strings
Method Description Example Output
find(sub) Returns first index of substring, -1 if not found "hello".find("l") 2
index(sub) Returns first index of substring, error if not found "hello".index("l") 2
count(sub) Counts occurrences of substring "hello".count("l") 2
startswith(sub) Checks if string starts with substring "Python".startswith("Py") True
endswith(sub) Checks if string ends with substring "Python".endswith("on") True
Example:
text = "hello world"
print(text.find("o")) #4
print(text.count("l")) # 3
print(text.startswith("he")) # True
3. Modifying and Replacing Strings
Method Description Example Output
replace(old, new) Replaces old substring with new substring "hello".replace("l","L") "heLLo"
strip() Removes leading & trailing spaces " hello ".strip() "hello"
lstrip() Removes leading spaces " hello".lstrip() "hello"
rstrip() Removes trailing spaces "hello ".rstrip() "hello"
Example:
text = " Python "
print(text.strip()) # Python
print(text.replace("Py","Ju")) # Juthon
4. Splitting and Joining Strings
Method Description Example Output
split(sep) Splits string into a list using separator "a,b,c".split(",") ['a','b','c']
join(iterable) Joins elements of a list or tuple into string " ".join(["Python","Rocks"]) "Python Rocks"
Example:
text = "Python is fun"
words = text.split() # Split by space
print(words) # ['Python', 'is', 'fun']
sentence = "-".join(words)
print(sentence) # Python-is-fun
5. Checking Content of Strings
Method Description Example Output
isalpha() Checks if all characters are letters "Python".isalpha() True
isdigit() Checks if all characters are digits "123".isdigit() True
isalnum() Checks if all characters are letters or digits "Python123".isalnum() True
isspace() Checks if all characters are whitespace " ".isspace() True
istitle() Checks if string is in title case "Python Programming".istitle() True
Example:
print("Python123".isalnum()) # True
print(" ".isspace()) # True
print("Python Programming".istitle()) # True
6. Formatting Strings
Method Description Example Output
format() Inserts values into placeholders "My name is {}".format("Leon") "My name is Leon"
f-string Embeds expressions inside {} f"My age is {21}" "My age is 21"
Example:
name = "Leon"
age = 21
print(f"My name is {name} and I am {age} years old")
Output:
My name is Leon and I am 21 years old
Summary
• String methods help in modifying, formatting, and analyzing strings.
• Strings are immutable, so all methods return new values.
• Common method categories:
1. Case Conversion: upper(), lower(), title()
2. Searching: find(), count(), startswith()
3. Modification: replace(), strip(), join()
4. Splitting & Joining: split(), join()
5. Checking Content: isalpha(), isdigit(), isalnum()
Python Functions: Types of Functions
Definition:
A function in Python is a block of code that performs a specific task.
Functions help avoid repetition, make code organized, and improve readability.
They can take inputs (parameters) and may return an output (return value).
Syntax of a Function
def function_name(parameters):
# code block
return value # optional
• def → keyword used to define a function
• function_name → any valid identifier
• parameters → values passed to the function (optional)
• return → sends a result back (optional)
Types of Functions in Python
Python functions can be categorized into two main types:
1. Built-in Functions
• Python provides many ready-to-use functions that are built into the language.
• Examples include: print(), len(), input(), type(), str(), int(), sum(), max(), min()
Example:
text = "Python"
print(len(text)) # Output: 6
num = 10.5
print(int(num)) # Output: 10
2. User-Defined Functions
• Functions that we create ourselves to perform specific tasks.
• Helps in reusing code multiple times.
Example 1: Simple Function
def greet():
print("Hello, welcome!")
greet()
Output:
Hello, welcome!
Example 2: Function with Parameters
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
Output:
Sum: 30
3. Anonymous Functions (Lambda Functions)
• Lambda functions are small, single-line, unnamed functions.
• Defined using the lambda keyword.
• Usually used for short operations or functional programming.
Syntax:
lambda parameters: expression
Example:
square = lambda x: x**2
print(square(5)) # Output: 25
Example 2: Lambda with multiple parameters
multiply = lambda a, b: a * b
print(multiply(3, 4)) # Output: 12
4. Recursive Functions
• A recursive function is a function that calls itself until a base condition is met.
• Useful in mathematical calculations, such as factorial, Fibonacci series, etc.
Example: Factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
Summary Table: Types of Functions
Type Description Example
Built-in Predefined functions in Python len(), print(), input()
User-defined Functions created by user def add(a, b): return a+b
Lambda (Anonymous) Single-line unnamed functions lambda x: x**2
Recursive Function calling itself def factorial(n)
Key Points:
• Functions reduce code repetition.
• They can take parameters and return results.
• Lambda functions are quick, one-line functions.
• Recursive functions require a base case to avoid infinite recursion.
Python Function: Definition and Syntax
Definition of a Function
A function in Python is a named block of code that performs a specific task. Functions help to:
• Organize code logically
• Avoid repetition
• Make programs easier to read and maintain
• Return values for further use
Syntax of a Function
def function_name(parameters):
"""
Optional docstring: description of the function
"""
# Code block (statements)
return value # optional
Components:
Part Description
def Keyword used to define a function
function_name Name of the function (must be a valid identifier)
parameters Optional input values passed to the function (can be zero or more)
: Colon indicates the start of the function block
Docstring Optional multi-line string describing the function
Code Block Statements that perform the task
return Optional statement to return a value to the caller
Example 1: Simple Function
def greet():
print("Hello, welcome to Python!")
greet()
Output:
Hello, welcome to Python!
Example 2: Function with Parameters
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
Output:
Sum: 30
Key Points
• Functions are defined once and can be called multiple times.
• If a function does not return anything, it returns None by default.
• Function parameters are optional; you can define functions without parameters.
Function Calling in Python
Definition:
After defining a function in Python, you need to call it to execute the code inside it. Function calling is simply
invoking the function by its name and passing required parameters (if any).
Syntax:
function_name(arguments)
• function_name → name of the function defined using def
• arguments → values passed to the function parameters (optional, depending on function definition)
1. Calling a Function Without Parameters
def greet():
print("Hello! Welcome to Python.")
greet()
Output:
Hello! Welcome to Python.
Here, greet() calls the function, executing the print() statement inside it.
2. Calling a Function With Parameters
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
Output:
Sum: 30
Values 10 and 20 are passed to parameters a and b when the function is called.
3. Calling a Function Multiple Times
You can call a function as many times as needed:
def greet(name):
print(f"Hello, {name}!")
greet("Leon")
greet("Alice")
greet("Bob")
Output:
Hello, Leon!
Hello, Alice!
Hello, Bob!
4. Calling Functions With Return Values
A function can return a value that can be stored in a variable or used directly:
def square(x):
return x ** 2
print(square(5)) # 25
result = square(7)
print(result) # 49
5. Using Function Call Inside Another Function
Functions can also be called inside other functions:
def add(a, b):
return a + b
def multiply_and_add(x, y, z):
return add(x, y) * z
print(multiply_and_add(2, 3, 4)) # (2+3)*4 = 20
Key Points
• A function must be defined before it is called.
• Functions can be called with or without arguments depending on definition.
• A function returns None if no return statement is used.
• Functions can be nested (called inside other functions).
Passing Parameters/Arguments in Python Functions
In Python, parameters are variables defined in a function, and arguments are the actual values passed to the
function when it is called.
Python provides multiple ways to pass arguments to functions.
1. Positional Arguments
• Values are passed in the same order as parameters are defined.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Leon", 21)
Output:
Hello Leon, you are 21 years old.
Order matters! Swapping the values will change the output.
2. Keyword Arguments
• Values are passed using parameter names, so the order does not matter.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=21, name="Leon")
Output:
Hello Leon, you are 21 years old.
3. Default Arguments
• Parameters can have default values, which are used if no argument is provided during the function call.
def greet(name, age=18):
print(f"Hello {name}, you are {age} years old.")
greet("Leon") # Uses default age
greet("Alice", 25) # Overrides default age
Output:
Hello Leon, you are 18 years old.
Hello Alice, you are 25 years old.
4. Arbitrary (Variable-Length) Arguments
• Use *args for any number of positional arguments
• Use **kwargs for any number of keyword arguments
Example with *args
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1, 2, 3, 4)) # 10
Example with **kwargs
def student_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
student_info(name="Leon", age=21, course="BCA")
Output:
name: Leon
age: 21
course: BCA
5. Combination of Arguments
• Positional, default, *args, and **kwargs can be combined, but in this order:
1. Positional arguments
2. Default arguments
3. *args (variable positional)
4. **kwargs (variable keyword)
def demo(a, b=10, *args, **kwargs):
print(a, b, args, kwargs)
demo(1, 2, 3, 4, x=5, y=6)
Output:
1 2 (3, 4) {'x': 5, 'y': 6}
Summary Table
Type Description Example
Positional Values assigned by position greet("Leon", 21)
Keyword Values assigned by name greet(age=21, name="Leon")
Default Parameter has default value def greet(name, age=18)
Arbitrary *args Any number of positional args add_numbers(1,2,3)
Arbitrary **kwargs Any number of keyword args student_info(name="Leon")
Key Points:
• Always define default arguments after positional ones.
• Use *args for lists of unknown length.
• Use **kwargs for unknown keyword arguments.
• Combining argument types allows flexible and reusable functions.
Return Statement in Python Functions
Definition:
The return statement is used in a Python function to send a value back to the caller.
It allows the function to produce a result that can be stored, printed, or used in expressions.
If a function does not use return, it returns None by default.
Syntax
def function_name(parameters):
# code block
return value
• value can be any data type, including numbers, strings, lists, tuples, dictionaries, or even other
functions.
• The return statement terminates the function, so any code after it is not executed.
1. Simple Return Example
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
2. Returning Multiple Values
Python functions can return multiple values as a tuple:
def arithmetic(a, b):
sum_ = a + b
diff = a - b
return sum_, diff
s, d = arithmetic(10, 5)
print("Sum:", s)
print("Difference:", d)
Output:
Sum: 15
Difference: 5
3. Using Return in Conditional Statements
def check_even(num):
if num % 2 == 0:
return True
else:
return False
print(check_even(8)) # True
print(check_even(7)) # False
4. Returning Data Structures
A function can return lists, dictionaries, or other objects:
def create_student(name, age):
return {"name": name, "age": age}
student = create_student("Leon", 21)
print(student)
Output:
{'name': 'Leon', 'age': 21}
5. Return vs Print
• return gives a value back to the caller.
• print only displays the value on the screen but does not pass it to other parts of the program.
def add(a, b):
return a + b
def add_print(a, b):
print(a + b)
result = add(5, 10)
print(result) # 15
add_print(5, 10) # 15 (printed inside function)
Summary
• The return statement ends the function and passes a value to the caller.
• You can return multiple values (they become a tuple).
• Returning values makes functions more reusable and flexible.
• Without return, a function returns None by default.
Default Parameters in Python Functions
Definition:
A default parameter is a function parameter that has a default value.
If the caller does not provide a value, the default is used.
If a value is provided, it overrides the default.
Default parameters make functions flexible and easier to use.
Syntax
def function_name(param1=default1, param2=default2):
# code block
• Default parameters must be defined after positional parameters.
• You can mix default and non-default parameters in a function.
1. Example: Single Default Parameter
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Uses default
greet("Leon") # Overrides default
Output:
Hello, Guest!
Hello, Leon!
2. Example: Multiple Default Parameters
def student_info(name="Unknown", age=18, course="BCA"):
print(f"Name: {name}, Age: {age}, Course: {course}")
student_info() # All defaults
student_info("Leon", 21) # Override first two
student_info(age=22, course="MCA") # Override by keyword
Output:
Name: Unknown, Age: 18, Course: BCA
Name: Leon, Age: 21, Course: BCA
Name: Unknown, Age: 22, Course: MCA
3. Rules for Default Parameters
1. Non-default parameters must come before default parameters:
def func(a, b=10): # Correct
pass
def func(a=10, b): # Incorrect → SyntaxError
pass
2. Default values can be any data type: int, float, string, list, dict, etc.
4. Example: Using List as Default Parameter (Careful!)
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] → Default list is shared
Better way:
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [2]
Summary
• Default parameters allow optional arguments.
• If a value is not provided, the default is used.
• Always place default parameters after non-default ones.
• Be careful with mutable default values like lists or dictionaries.
Recursive Functions in Python
Definition:
A recursive function is a function that calls itself to solve a smaller version of the original problem.
Recursion is often used in problems that can be broken down into similar sub-problems, such as factorials,
Fibonacci numbers, or tree traversal.
Key Concepts of Recursion
1. Base Case:
o The condition at which the function stops calling itself.
o Without a base case, recursion leads to infinite calls and a RecursionError.
2. Recursive Case:
o The part of the function where it calls itself with a smaller or simpler input.
Syntax
def function_name(parameters):
if base_condition:
return value
else:
# Recursive call
return function_name(modified_parameters)
1. Example: Factorial using Recursion
The factorial of a number n is calculated as:
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n-1) # Recursive case
print(factorial(5)) # Output: 120
Explanation:
• factorial(5) calls factorial(4)
• factorial(4) calls factorial(3) … until factorial(0)
• Then the function returns back through all calls, calculating 5*4*3*2*1 = 120
2. Example: Fibonacci Series using Recursion
The Fibonacci series is: 0, 1, 1, 2, 3, 5, 8 …
Each term = sum of previous two terms.
def fibonacci(n):
if n <= 1: # Base case
return n
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive case
for i in range(10):
print(fibonacci(i), end=" ")
Output:
0 1 1 2 3 5 8 13 21 34
3. Example: Sum of Numbers using Recursion
def sum_numbers(n):
if n == 0:
return 0
else:
return n + sum_numbers(n-1)
print(sum_numbers(5)) # 15 (5+4+3+2+1)
Advantages of Recursion
1. Makes code shorter and easier to read for problems like factorial, Fibonacci, tree traversal, and
sorting.
2. Naturally models problems that are self-similar.
Disadvantages of Recursion
1. May lead to high memory usage due to multiple function calls.
2. Can cause stack overflow if the recursion depth is too high.
3. Sometimes iterative solutions are faster.
Summary
• A recursive function calls itself to solve smaller parts of a problem.
• Must have a base case to stop recursion.
• Widely used in mathematical problems, data structures, and algorithms.
• Python has a default recursion limit (usually 1000 calls). You can check using: