🐍 Moving Beyond Basic Python
Advanced Python programming helps us write larger, smarter and
more organised programs.
Instead of writing all instructions in one place, we can divide
programs into reusable parts and work with different types of data.
⚙️ Functions
A function is a named block of code designed
to perform a particular task.
Functions help us avoid repeating the same code again and again.
def greet():
print("Hello, World!")
greet()
📝 Creating a Function
In Python, the def keyword is used to define a function.
def function_name():
statement
The indented statements form the body of the function.
📥 Function Parameters
A parameter is a value that a function receives
to perform its task.
def greet(name):
print("Hello", name)
greet("Anant")
➕ Multiple Parameters
A function can receive more than one parameter.
def add(a, b):
print(a + b)
add(10, 20)
↩️ Returning a Value
The return statement sends a result back from a
function.
def add(a, b):
return a + b
answer = add(10, 20)
print(answer)
📍 Local Variables
A variable created inside a function is usually called a
local variable.
def show():
message = "Hello"
print(message)
show()
🌍 Global Variables
A variable created outside a function can generally be accessed
from different parts of the program.
school = "My School"
def show():
print(school)
show()
📦 Modules
A module is a Python file containing useful
functions, variables or other code that can be imported into
another program.
📥 Importing a Module
The import keyword is used to include a module in
a Python program.
import math
print(math.sqrt(25))
🎲 The random Module
The random module can be used to generate random
values.
import random
number = random.randint(1, 10)
print(number)
🔤 Working with Strings
A string is a sequence of characters.
name = "Python"
print(name)
Python provides many useful methods for working with strings.
🔧 Common String Methods
text = "python programming"
print(text.upper())
print(text.lower())
print(text.title())
print(text.replace("python", "Python"))
📏 Finding String Length
The len() function returns the number of characters
in a string.
name = "Python"
print(len(name))
📋 Lists
A list is used to store multiple values in a
single variable.
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
🔢 Accessing List Items
List items are accessed using their index number.
fruits = ["Apple", "Banana", "Mango"]
print(fruits[0])
print(fruits[1])
Python indexing begins with 0.
➕ Adding Items to a List
The append() method adds an item to the end of a list.
fruits = ["Apple", "Banana"]
fruits.append("Mango")
print(fruits)
➖ Removing List Items
The remove() method removes a specified item.
fruits = ["Apple", "Banana", "Mango"]
fruits.remove("Banana")
print(fruits)
📏 List Length
The len() function can also be used to count the
number of items in a list.
numbers = [10, 20, 30, 40]
print(len(numbers))
🔄 Looping Through a List
A for loop can process every item in a list.
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
📖 Dictionaries
A dictionary stores data as
key-value pairs.
student = {
"name": "Ravi",
"class": 8,
"marks": 90
}
🔑 Accessing Dictionary Values
Dictionary values can be accessed using their keys.
student = {
"name": "Ravi",
"marks": 90
}
print(student["name"])
print(student["marks"])
➕ Adding Dictionary Data
New key-value pairs can be added to a dictionary.
student = {
"name": "Ravi"
}
student["class"] = 8
print(student)
✏️ Updating Dictionary Data
Assign a new value to an existing key to update its value.
student = {
"name": "Ravi",
"marks": 80
}
student["marks"] = 95
print(student)
🗂️ Organising Data
Lists and dictionaries can be combined to organise more
complex information.
students = [
{"name": "Ravi", "marks": 90},
{"name": "Riya", "marks": 95}
]
print(students[0]["name"])
🔒 Tuples
A tuple is a collection of values that is
generally not modified after creation.
colours = ("Red", "Green", "Blue")
print(colours)
🎯 Sets
A set is a collection that stores unique values.
numbers = {1, 2, 3, 3, 4}
print(numbers)
Duplicate values are not stored as separate items in a set.
📁 File Handling
File handling allows a program to save information permanently
in a file and read it later.
📂 Opening a File
The open() function is used to open a file.
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()
✍️ Writing to a File
The "w" mode can be used to write data to a file.
file = open("notes.txt", "w")
file.write("Welcome to Python!")
file.close()
➕ Appending to a File
The "a" mode adds new data to the end of an
existing file.
file = open("notes.txt", "a")
file.write("\nAdvanced Python")
file.close()
🛡️ Using the with Statement
The with statement is a convenient way to work
with files because the file is automatically closed afterwards.
with open("notes.txt", "r") as file:
content = file.read()
print(content)
⚠️ Exceptions
An exception is an error that occurs while a
program is running.
Python provides tools to handle certain errors without abruptly
stopping the program.
🛠️ try and except
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Please enter a valid number.")
🔄 Type Conversion
Type conversion changes a value from one data type to another.
age = "14"
age = int(age)
print(age + 1)
🔢 Common Type Conversion Functions
int() – converts to an integer.
float() – converts to a decimal number.
str() – converts to a string.
list() – converts to a list where applicable.
🔍 Variable Scope
Scope refers to the part of a program where
a variable can be accessed.
Understanding scope helps programmers organise variables and
functions correctly.
📚 Documentation with Docstrings
A docstring can describe the purpose of a
function or module.
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
📝 Chapter Summary
Advanced Python programming helps us create larger and more
organised programs.
Functions allow code to be reused. Parameters and arguments allow
functions to work with different values, while the
return statement sends results back to the program.
Modules provide reusable Python code. Collections such as lists,
tuples, sets and dictionaries help us organise multiple values.
File handling allows Python programs to save and retrieve
information. Exception handling helps programs deal with expected
errors more safely.
By combining functions, collections, modules, files and exception
handling, we can create more powerful and useful Python applications.