0% found this document useful (0 votes)
3 views6 pages

Python Basics Part3 Functions

Uploaded by

makoyeelias0753
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)
3 views6 pages

Python Basics Part3 Functions

Uploaded by

makoyeelias0753
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

■ Python Basics

Part 3 — Functions
■ Functions ■ Parameters & Args

■ Return Statement ■ Lambda Functions

■ Recursion Basics ■ Variable Scope

■ Modules ■ Import Statements

■ 1. What is a Function?

A function is a named, reusable block of code that performs a specific task. Instead of repeating the same logic,
define it once and call it anywhere.

1 def greet():
2 print("Welcome to Python")
3
4 greet()

OUTPUT
Welcome to Python

✔ def keyword creates a function. The name is followed by () and a colon.

■ 2. Function Parameters

Parameters allow a function to accept input values, making it flexible and reusable.

1 def greet(name):
2 print("Hello", name)
3
4 greet("Python")

OUTPUT
Hello Python

The value passed when calling the function is called an argument.

■ 3. Multiple Parameters

1 def add(a, b):


2 print(a + b)
3
4 add(10, 20)

OUTPUT
30
■ Separate multiple parameters with commas inside the parentheses.

■ 4. Return Statement

The return statement sends a value back to the caller. This is essential in real projects where you need to use
the result.

1 def square(num):
2 return num * num
3
4 result = square(5)
5 print(result)

OUTPUT
25

Without return, a function gives back None by default.

■ 5. Default Parameters

Assign default values to parameters — they are used when the caller does not provide a value.

1 def country(name="India"):
2 print(name)
3
4 country()
5 country("Japan")

OUTPUT
India
Japan

■ Default parameters must come AFTER non-default ones.

■ 6. Lambda Functions

A lambda is a small, anonymous function written in a single line. Commonly used in data analysis, sorting, and
automation.

1 square = lambda x: x * x
2
3 print(square(4))

OUTPUT
16

Regular Function Lambda Function

Uses def keyword Uses lambda keyword


Can have multiple lines Single expression only

Has a name Anonymous (no name)

Good for complex logic Good for simple, short tasks

■ 7. Recursion Basics

Recursion is when a function calls itself. Every recursive function needs a base case — a condition that stops
the recursion — otherwise it runs forever.

1 def countdown(n):
2 if n == 0:
3 return
4 print(n)
5 countdown(n - 1)
6
7 countdown(5)

OUTPUT
5
4
3
2
1

■ Always define a base case -- missing it causes infinite recursion (stack overflow).

■ 8. Variable Scope

Scope determines where a variable can be accessed in your code.

Type Defined Accessible

Local Inside a function Only inside that function

Global Outside functions Anywhere in the file

Local variable example:

1 def test():
2 value = 100
3 print(value)
4
5 test()

OUTPUT
100

Global variable example:


1 message = "Python"
2
3 def show():
4 print(message)
5
6 show()

OUTPUT
Python

■ 9. Modules in Python

A module is a file containing Python code (functions, variables, classes) that you can reuse in other programs.

1 import math
2
3 print([Link](25))

OUTPUT
5.0

■ 10. Import Statements

Use from … import to pull specific items from a module without loading everything.

1 from random import randint


2
3 print(randint(1, 10))

OUTPUT
7 # (random number)

Syntax Effect

import math Imports entire module

from math import sqrt Imports only sqrt

from math import * Imports everything (avoid)

import numpy as np Imports with an alias

■ Practice Programs — Try These!

■ Calculator using Functions

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


2 def sub(a,b): return a-b
3 def mul(a,b): return a*b
4 def div(a,b): return a/b if b!=0 else 'Error'
■ Factorial Program

1 def factorial(n):
2 if n == 0 or n == 1:
3 return 1
4 return n * factorial(n - 1)
5
6 print(factorial(5)) # 120

■ Prime Number Checker

1 def is_prime(n):
2 if n < 2: return False
3 for i in range(2, int(n**0.5)+1):
4 if n % i == 0: return False
5 return True
6
7 print(is_prime(17)) # True

■ Common Beginner Mistakes

■ Forgetting indentation Python uses indentation to define blocks. Always indent inside def.

■ Missing return statement Without return, your function silently returns None.

■ Confusing parameters & args Parameter = variable in def. Argument = value passed when calling.

■ Infinite recursion Always write a base case — if n == 0: return — to stop recursion.

■ Pro Tips for Clean Functions

■ Write small, focused functions — each should do ONE thing.

■ Use descriptive names: calculate_area() is better than func1().

■ Add docstrings to explain what your function does.

■ Keep functions reusable — avoid hard-coding values inside them.

■ Good functions make code cleaner, easier to test, and easier to debug.

■ Quick Reference Cheatsheet


Concept Syntax Purpose

Define function def name(): Create a reusable block

Parameter def add(a, b): Input variable

Return value return result Send value back

Default param def f(x="hi"): Fallback value

Lambda f = lambda x: x*2 One-line function

Recursion def f(n): ... f(n-1) Function calls itself

Local variable Inside def block Only in that function

Global variable Outside all defs Accessible everywhere

Import module import math Use built-in library

From import from math import sqrt Import specific item

Python Basics — Part 3: Functions • DIT Computer Studies • BENG25COE

You might also like