+91 9873530045
admin@learnwithfrahimcom
Mon - Sat : 09 AM - 09 PM

Day 4: Python Functions, Scope & Modules


Step 1: Functions

Functions allow you to group code for reuse. They help organize your programs.

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

greet("Alisha")
greet("John")
Hello, Alisha
Hello, John

Step 2: Function Arguments & Return Values

Functions can accept arguments and return values:

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

result = add(5, 7)
print("Sum =", result)
Sum = 12

Step 3: Scope – Local vs Global

Variables defined inside a function are local. Variables outside are global.

x = 10 # global variable
def show():
  x = 5 # local variable
  print("Inside function:", x)

show()
print("Outside function:", x)
Inside function: 5
Outside function: 10

Step 4: Modules

Modules are Python files that contain functions, variables, or classes which can be reused in other programs.

Example: math module for mathematical operations:

import math
print("Square root of 16 =", math.sqrt(16))
print("Pi =", math.pi)
Square root of 16 = 4.0
Pi = 3.141592653589793

Step 5: PyCharm Project Example – Functions

Project layout and code demonstration:

MyPythonProject
├── functions.py
├── data.txt
└── requirements.txt
# functions.py
def greet(name):
    print("Hello,", name)

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

greet("Alisha")
print("Sum =", add(5,7))
Hello, Alisha
Sum = 12
✔ End of Day 4 – Functions, scope, and modules understood. You can now organize and reuse your code effectively!