In this article Functions in Python we give the information about Python provides many built-in functions that can be used directly without importing any module.
Functions in Python
- Built-in Functions
- Python provides many built-in functions that can be used directly without importing any module.
- Some categories:
Category | Examples |
Type conversion | int(), float(), str(), list(), tuple(), dict() |
Mathematical | abs(), pow(), round(), min(), max(), sum() |
Input/Output | print(), input() |
Sequence related | len(), sorted(), reversed(), enumerate(), range() |
Object related | id(), type(), isinstance(), dir() |
Others | help(), eval(), any(), all(), zip() |
Example:
nums = [5, 3, 8, 1]
print(len(nums)) # 4
print(max(nums)) # 8
print(sorted(nums)) # [1, 3, 5, 8]
- Function Definition and Call
Defining a function
Syntax:
def function_name(parameters):
“””Optional docstring”””
# function body
return value
Calling a function
function_name(arguments)
Example:
def add(a, b):
“””This function returns sum of two numbers”””
return a + b
result = add(5, 3)
print(“Sum:”, result)
-
Scope and Lifetime of Variables
Scope
- The scope of a variable defines where it can be accessed.
- Python follows LEGB Rule (Local → Enclosing → Global → Built-in).
Scope | Description |
Local | Declared inside a function, accessible only there. |
Enclosing | Variables in outer functions (nested function). |
Global | Declared outside all functions, accessible everywhere. |
Built-in | Predefined names like len, range. |
Example:
x = 10 # Global variable
def outer():
y = 20 # Enclosing variable
def inner():
z = 30 # Local variable
print(x, y, z)
inner()
outer()
Lifetime
- A variable’s lifetime is how long it exists in memory.
- Local variables → created when function is called, destroyed when function ends.
- Global variables → exist as long as the program runs.
- Default Parameters
- Functions can have parameters with default values.
- If no value is passed, the default is used.
Example:
def greet(name=”Student”):
print(“Hello,”, name)
greet(“Santosh”) # Hello, Santosh
greet() # Hello, Student
- Default parameters must be placed after non-default parameters.
def func(a, b=10): # Correct
return a + b
# def func(a=10, b): #Invalid
Summary
- Built-in functions: Ready-to-use like len(), sum(), print().
- User-defined functions: Created using def.
- Scope: Local, Enclosing, Global, Built-in (LEGB rule).
- Lifetime: Local variables die after function ends; global live till program ends.
- Default parameters: Allow flexible function calls.
Command Line Arguments in Python
- Command Line Arguments are values passed to the program when it is run from the terminal/command prompt.
- In Python, they are handled using the sys module.
Example
import sys
print(“Program name:”, sys.argv[0]) # first argument → script name
print(“Arguments:”, sys.argv[1:]) # remaining → user input
Running the program
If saved as demo.py:
python demo.py hello 123
Output
Program name: demo.py
Arguments: [‘hello’, ‘123’]
Notes:
- sys.argv is a list of strings.
- Must convert arguments if integers are needed:
num = int(sys.argv[1])
- Assert Statement
- The assert statement is used for debugging.
- It tests a condition, and if the condition is False, it raises an AssertionError.
Syntax
assert condition, “Error message”
Example:
x = 10
assert x > 0, “x must be positive” # Passes
y = -5
assert y > 0, “y must be positive” # Fails → AssertionError
- Importing User-defined Module
- A module is just a Python file (.py) containing functions, variables, or classes.
- User-defined modules can be created and imported.
Step 1: Create a module (mymath.py)
# mymath.py
def add(a, b):
return a + b
def sub(a, b):
return a – b
Step 2: Import and use in another file (main.py)
import mymath
print(mymath.add(10, 5)) # 15
print(mymath.sub(10, 5)) # 5
Other Import Methods
from mymath import add # imports only add
print(add(3, 2))
from mymath import * # imports all functions
print(sub(7, 4))
import mymath as m # alias
print(m.add(6, 2))
Summary
- Command Line Arguments → handled with sys.argv.
- Assert Statement → ensures conditions are true, else raises error.
- User-defined Module → create a .py file and import it in another program.
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System