DEV Community

Aruna Arun
Aruna Arun

Posted on

Day 6:Python Programming

Python Function
1.What is a Function?
A function is a block of code that performs a specific task.
It helps to:
Avoid repeated code
Improve readability
Make code modular

2.How to Define a Function
def function_name():
# code
Example
def greet():
print("Hello, welcome to Python!")
Calling a Function
greet()
Function with Parameters
Parameters = inputs you pass to a function.

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

add(5, 3)

Function with Return Value
return sends a value back from the function.

def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result)

Types of Arguments
1.Positional Arguments
def info(name, age):
print(name, age)

info("Aruna", 22)

2.Keyword Arguments
info(age=22, name="Aruna")

3.Default Arguments
def greet(name="User"):
print("Hello", name)

greet()

4.Variable Length Arguments
*args → multiple values (tuple)
def total(*numbers):
print(sum(numbers))
total(1, 2, 3, 4)

kwargs → key-value pairs (dictionary)
def details(
data):
print(data)
details(name="Arun", place="Chennai")

3.Nested Functions
def outer():
def inner():
print("Inner function")
inner()

outer()

4.Anonymous Function (Lambda)
Small one-line function.
square = lambda n: n*n
print(square(5))

Python Modules & Packages

  1. What is a Module? A module is a Python file (.py) that contains: Functions Variables Classes Example: math.py, random.py

Importing a Module
1.Import entire module
import math
print(math.sqrt(25))
2.Import specific function
from math import sqrt
print(sqrt(36))
3.Import with alias name
import math as m
print(m.pi)

Built-in Modules
1.math
import math
print(math.pi)
print(math.sqrt(16))
print(math.factorial(5))
2.random
import random
print(random.random())
print(random.randint(1, 10))
print(random.choice(["apple", "banana", "orange"]))
3.datetime
import datetime
now = datetime.datetime.now()
print(now)
User-defined Module
Create a file mymath.py:
def add(a, b):
return a + b
Use it:
import mymath
print(mymath.add(3, 4))

2.What is a Package?
A collection of modules inside a folder with init.py.
Example structure:
mypackage/
init.py
add.py
multiply.py
Using it:
from mypackage.add import add_numbers

3.dir() Function (to list module items)
import math
print(dir(math))

Top comments (0)