《Python》
Experiment Report
Name :
Student ID :
Python Experiment Report — Functions
I. Experiment Objectives
1. Understand how to define and call functions in Python
2. Learn the use of parameters and return values
3. Practice different types of arguments (positional, keyword, default, variable-
length)
4. Improve modularity and reusability through function decomposition
II. Experiment Environment
1. Operating System: Windows
2. Python Version: Python 3.8
3. IDE: PyCharm Community Edition
4. Anaconda
III. Experiment Content
1. Function Definition and Return Value
Objective: Define and call basic functions that accept input and return computed
results.
Procedure:
Create a function named square() that takes one parameter and returns its square.
Call the function with different arguments and display the result.
(Input your codes here!)
2. Default and Keyword Arguments
Objective: Learn to define functions with default parameter values and call them
using keyword arguments.
Procedure:
Write a function called greet() that takes name and message, with message having a
default value.
Call the function with both positional and keyword arguments.
(Input your codes here!)
3. Variable-length Arguments
Objective: Use *args for multiple positional arguments and **kwargs for multiple
keyword arguments.
Procedure:
Create a function sum_all() using *args to sum any number of numbers.
Create another function print_info() using **kwargs to print key-value pairs.
(Input your codes here!)
4. Function Nesting and Scope
Objective: Understand how variable scope works using nested functions and the
nonlocal or global keywords.
Procedure:
Define an outer function with a local variable.
Define an inner function that modifies the outer variable.
Demonstrate scope rules using nonlocal or global.
(Input your codes here!)
5. Lambda and Higher-order Functions
Objective: Use anonymous functions (lambda) and pass functions as arguments.
Procedure:
Create a lambda function to multiply two numbers.
Use map() to apply a function to each item in a list.
Use filter() to keep only even numbers from a list.
(Input your codes here!)
Examples
1
def square(x):
return x * x
print("Square of 5 is:", square(5))
print("Square of 10 is:", square(10))
2
def greet(name, message="Welcome!"):
print(f"Hello, {name}. {message}")
greet("Alice")
greet("Bob", message="Good to see you!")
3
def sum_all(*args):
return sum(args)
print("Sum:", sum_all(1, 2, 3, 4, 5))
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=20, city="New York")
4
def outer():
count = 0
def inner():
nonlocal count
count += 1
print("Count:", count)
inner()
inner()
outer()
5
multiply = lambda x, y: x * y
print("Multiply 3 and 4:", multiply(3, 4))
numbers = [1, 2, 3, 4, 5, 6]
squared = list(map(lambda x: x ** 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Squared:", squared)
print("Even numbers:", evens)