dictionary
x = { 'name': 'python' }
functions in python
- A Function is a resuable unit/block of code
- syntax
def <func-name>():
....
....
....
Docstrings
Activity
- Lets create a calculator program
- create a new folder and a new file called as calc.py
- in python module refers to a file in this case the module name is
calc
"""Calculator with basic operations.
This module provides simple arithmetic functions such as addition,
subtraction, and multiplication. Each function accepts two integers
and returns an integer result.
"""
def add(a: int, b: int) -> int:
"""Add two integers.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of `a` and `b`.
"""
return a + b
def sub(a: int, b: int) -> int:
"""Subtract one integer from another.
Args:
a (int): The number to subtract from.
b (int): The number to subtract.
Returns:
int: The result of `a - b`.
"""
return a - b
def mul(a: int, b: int) -> int:
"""Multiply two integers.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The product of `a` and `b`.
"""
return a * b
- calling functions from same module
- watch classroom recording for debugging
- calling functions from other module
- Create main.py
- We need to use import
- import example
import calc
result = calc.add(5,6)
print(result)
result = calc.sub(6,4)
print(result)
from calc import add
result = add(5,6)
print(result)
from calc import add, sub
result = add(5,6)
print(result)
result = sub(6,4)
print(result)
from calc import add as c_add
def add():
pass
result = c_add(6,5)
print(result)
- Refer Here for changes
-
Refer Here for problems solved
-
Exercise:
- create following functions
- is_prime -> returns bool
is_prime(5) => True
- factors -> returns list[int]
factors(20) => [1,2,4,5,10]
- prime_factors -> returns list[int]
prime_factors => [2,5]
Like this:
Like Loading...