0% found this document useful (0 votes)
2 views

Functions_Unit2

The document explains various ways to pass arguments to functions in Python, including positional, default, keyword, arbitrary, and arbitrary keyword arguments. It also covers built-in functions, functions from standard and external libraries, and the use of default values and optional parameters in function definitions. Additionally, it discusses mixing required and default parameters, using None as a default value, and combining default arguments with *args and **kwargs.

Uploaded by

ansh.phy0205
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Functions_Unit2

The document explains various ways to pass arguments to functions in Python, including positional, default, keyword, arbitrary, and arbitrary keyword arguments. It also covers built-in functions, functions from standard and external libraries, and the use of default values and optional parameters in function definitions. Additionally, it discusses mixing required and default parameters, using None as a default value, and combining default arguments with *args and **kwargs.

Uploaded by

ansh.phy0205
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Functions

# Passing Arguments in a Python Function


In Python, you can pass arguments to functions in different ways. Here are the main types:

🔹 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)

✅ Output: Hello Alice, you are 25 years old.

🔹 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.")

greet("Bob") # Uses default age = 18


greet("Charlie", 22) # Overrides default

✅ 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.")

greet(age=30, name="David") # Order doesn't matter

✅ Output: Hello David, you are 30 years old.

🔹 4. Arbitrary Arguments (*args)


Used when the number of arguments is unknown.
def add_numbers(*numbers):
print(sum(numbers))

add_numbers(1, 2, 3, 4, 5)
✅ Output: 15

🔹 5. Arbitrary Keyword Arguments (**kwargs)


Used when passing multiple key-value pairs as arguments.
def person_info(**info):
for key, value in info.items():
print(f"{key}: {value}")

person_info(name="Eve", age=28, city="New York")

✅ Output:
name: Eve
age: 28
city: New York

# Library Functions in Python


Library functions in Python are pre-defined functions provided by the Python Standard Library
or external libraries. These functions help perform common operations without needing to write
code from scratch.

🔹 1. Built-in Functions (Python Standard Library)


These functions are available without importing any module.

✅ Common Built-in Functions


Category Function Description
Input/Output print() Displays output
input() Takes user input
Data Type & type() Returns the type of a variable
Conversion
int(), float(), str(),
Converts data types
bool()
Math Operations abs(x) Absolute value of x
pow(x, y) Returns x raised to y (same as x**y)
round(x, n) Rounds x to n decimal places
String Handling len(s) Returns length of string/list/dictionary
min(iterable),
List & Tuple Functions Returns smallest/largest item
max(iterable)
sum(iterable) Returns sum of elements
sorted(iterable) Returns sorted list
Set & Dictionary set(iterable) Creates a set
Functions
dict() Creates a dictionary
Category Function Description
File Handling open(filename, mode) Opens a file

🔹
read(), write() Reads/Writes a file
Example

print(len("Python")) # Output: 6
print(abs(-10)) # Output: 10
print(pow(2, 3)) # Output: 8

🔹 2. Functions from Standard Python Libraries


Python provides several modules (libraries) with additional functions. These need to be imported
before use.

✅ Common Python Standard Libraries


Library Functions Use Case
math sqrt(x), ceil(x), floor(x), log(x) Advanced math operations
random randint(a, b) Random number generation
datetime datetime.now() Date and time manipulation

🔹
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

🔹 3. Functions from External Libraries


Some useful external libraries (need installation using pip):

Library Functions Use Case


numpy numpy.array(), numpy.mean(), numpy.std() Scientific computing
pandas pandas.DataFrame(), pandas.read_csv() Data analysis
matplotlib matplotlib.pyplot.plot(), show() Data visualization

🔹
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.

✅ Example: Default Parameters


def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice") # Passes "Alice"


greet() # Uses default "Guest"

✅ 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.

✅ Example: Optional Parameters


def user_info(name, age=18, city="Unknown"):
print(f"Name: {name}, Age: {age}, City: {city}")

user_info("Bob") # Uses default age=18, city="Unknown"


user_info("Alice", 25) # Uses default city="Unknown"
user_info("Charlie", 30, "NYC") # No defaults used

✅ 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.

🔹 Mixing Required & Default Parameters


You can mix required and default parameters, but required parameters must come first.
❌ Incorrect: Default before Required (Error!)
def greet(message="Hello", name): # ❌ SyntaxError
print(f"{message}, {name}!")

✅ Corrected Version
def greet(name, message="Hello"): # Required `name` first
print(f"{message}, {name}!")

greet("Alice") # Uses default message


greet("Bob", "Hi") # Uses custom message

✅ Output:
Hello, Alice!
Hi, Bob!

🔹 Using None as a Default Value


Sometimes, you might want to distinguish between an argument that is intentionally missing and
an argument that has a default value.

✅ Example: Using None as Default


def display_message(msg=None):
if msg is None:
msg = "No message provided."
print(msg)

display_message("Hello!") # Uses provided message


display_message() # Uses default message

✅ Output:
Hello!
No message provided.

🔹 Here, None is used as a default value, and the function checks if an argument was provided.

🔹 Default Arguments with *args and **kwargs


You can mix default arguments with *args (for multiple positional arguments) and **kwargs
(for multiple keyword arguments).
def order_food(main="Pizza", *sides, drink="Water", **extras):
print(f"Main dish: {main}")
print(f"Sides: {sides}")
print(f"Drink: {drink}")
print(f"Extras: {extras}")

order_food("Burger", "Fries", "Salad", drink="Soda", sauce="Ketchup")

✅ 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.

You might also like