Python_6
Python_6
Today, you'll begin exploring one of Python’s most powerful features: functions. Functions let you
encapsulate code into reusable blocks, making your programs more organized and modular. You’ll
also get a first look at modules, which allow you to group related functions together or import useful
code from Python’s standard library.
• Definition:
A function is a reusable block of code that performs a specific task. Functions help reduce
repetition, improve readability, and make maintenance easier.
• Benefits:
• Syntax Example:
def greet():
greet()
Here, def starts the function definition, greet is the function name, and () holds any parameters
(none in this simple case).
• Parameters:
Variables defined in a function’s signature.
• Arguments:
Values you pass into the function when calling it.
• Example:
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice")
B. Return Values
• Purpose:
Use the return keyword to send data back from a function.
• Example:
return a + b
result = add(3, 5)
• Default Parameters:
Allow you to set default values for parameters if no argument is provided.
• Example:
def greet(name="there"):
print(f"Hello, {name}!")
• Keyword Arguments:
Allow you to specify arguments by the parameter name.
• Example:
describe_pet(animal_type="dog", pet_name="Buddy")
describe_pet(pet_name="Whiskers", animal_type="cat")
• Global Variables:
Variables defined outside of functions. They can be accessed inside functions, although it’s
best to use them sparingly.
• Example:
# Global variable
def print_message():
# Local variable
print(message)
• Definition:
Modules are files containing Python code (functions, classes, variables) that you can import
into your program to reuse code. The Python Standard Library contains many useful modules
(e.g., math, random, datetime).
import math
number = 16
sqrt_value = math.sqrt(number)
return a * b
import mymodule
product = mymodule.multiply(4, 5)
1. Task:
Create a function named calculate_area that accepts two parameters, width and height, and
returns the area of a rectangle.
2. Steps:
o Call the function with sample values and print the output.
3. Sample Code:
area = calculate_area(5, 3)
1. Task:
Write a function introduce that prints an introduction message. The function should have
default parameters for name (default "Guest") and age (default 0).
2. Sample Code:
1. Task:
Write a script that imports the random module to generate a random number between 1
and 100. Then, create a function guess_game that compares a user-provided guess to the
random number and prints whether the guess is too high, too low, or correct.
2. Hints:
3. Sample Code:
import random
def guess_game(user_guess):
print("Too low!")
print("Too high!")
else:
print("Correct!")
guess_game(50)
python
print(say_hi())
return x + y
import math
exit()