Functions_Unit2
Functions_Unit2
🔹 1. Positional Arguments
Arguments are passed in the same order as defined in the function.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25)
🔹 2. Default Arguments
You can assign default values to function parameters.
def greet(name, age=18):
print(f"Hello {name}, you are {age} years old.")
✅ Output:
Hello Bob, you are 18 years old.
Hello Charlie, you are 22 years old.
🔹 3. Keyword Arguments
You can pass arguments using parameter names.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
add_numbers(1, 2, 3, 4, 5)
✅ Output: 15
✅ Output:
name: Eve
age: 28
city: New York
🔹
read(), write() Reads/Writes a file
Example
print(len("Python")) # Output: 6
print(abs(-10)) # Output: 10
print(pow(2, 3)) # Output: 8
🔹
statistics mean(), median(), stdev() Statistical operations
Example
import math
print(math.sqrt(25)) # Output: 5.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10
🔹
requests requests.get(url), requests.post(url) Web requests
Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print(np.mean(arr)) # Output: 2.5
# Default Values & Optional Parameters in Python Functions
In Python, default values and optional parameters allow you to define functions with flexible
arguments.
🔹 Default Parameters
A function parameter can have a default value, which is used when no argument is passed for that
parameter.
✅ Output:
Hello, Alice!
Hello, Guest!
🔹 Here, "Guest" is the default value of name. If no argument is given, it is used automatically.
🔹 Optional Parameters
Optional parameters are parameters that have default values, meaning they don’t require an
argument when calling the function.
✅ Output:
Name: Bob, Age: 18, City: Unknown
Name: Alice, Age: 25, City: Unknown
Name: Charlie, Age: 30, City: NYC
🔹 Here, age and city are optional parameters because they have default values.
✅ Corrected Version
def greet(name, message="Hello"): # Required `name` first
print(f"{message}, {name}!")
✅ Output:
Hello, Alice!
Hi, Bob!
✅ Output:
Hello!
No message provided.
🔹 Here, None is used as a default value, and the function checks if an argument was provided.
✅ Output:
Main dish: Burger
Sides: ('Fries', 'Salad')
Drink: Soda
Extras: {'sauce': 'Ketchup'}
🔹 main and drink have default values, while *sides and **extras allow additional
arguments.