Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python_6

This document introduces the concepts of functions and modules in Python. It covers the definition, benefits, and syntax of functions, including parameters, arguments, return values, and scope. Additionally, it explains modules, how to import them, and provides hands-on exercises for practical application.

Uploaded by

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

Python_6

This document introduces the concepts of functions and modules in Python. It covers the definition, benefits, and syntax of functions, including parameters, arguments, return values, and scope. Additionally, it explains modules, how to import them, and provides hands-on exercises for practical application.

Uploaded by

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

Day 6: Functions & Modules (Part I)

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.

Step 1: Understanding Functions

What Are Functions?

• 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:

o Reusability: Write once, use anywhere.

o Abstraction: Hide complex code behind a simple interface.

o Modularity: Break down large problems into smaller, manageable pieces.

Defining and Calling a Function

• Syntax Example:

def greet():

print("Hello, welcome to Python learning!")

# Calling the function

greet()

Here, def starts the function definition, greet is the function name, and () holds any parameters
(none in this simple case).

Step 2: Function Parameters, Arguments, and Return Values

A. Function Parameters and Arguments

• 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")

Here, name is a parameter, and "Alice" is the argument.

B. Return Values

• Purpose:
Use the return keyword to send data back from a function.

• Example:

def add(a, b):

return a + b

result = add(3, 5)

print("The sum is:", result)

C. Default Parameters and Keyword Arguments

• Default Parameters:
Allow you to set default values for parameters if no argument is provided.

• Example:

def greet(name="there"):

print(f"Hello, {name}!")

greet() # Uses default value: "there"

greet("Bob") # Overrides default with "Bob"

• Keyword Arguments:
Allow you to specify arguments by the parameter name.

• Example:

def describe_pet(animal_type, pet_name):

print(f"I have a {animal_type} named {pet_name}.")

describe_pet(animal_type="dog", pet_name="Buddy")

describe_pet(pet_name="Whiskers", animal_type="cat")

Step 3: Function Scope

Local vs. Global Variables


• Local Variables:
Variables defined inside a function. They are only accessible within that function.

• Global Variables:
Variables defined outside of functions. They can be accessed inside functions, although it’s
best to use them sparingly.

• Example:

# Global variable

message = "Hello, world!"

def print_message():

# Local variable

message = "Hello from inside the function!"

print(message)

print_message() # Prints the local variable value

print(message) # Prints the global variable value

Step 4: Introduction to Modules

What Are Modules?

• 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).

Importing and Using a Module

• Example with the math Module:

import math

# Using the math.sqrt function to compute the square root

number = 16

sqrt_value = math.sqrt(number)

print("Square root of", number, "is", sqrt_value)

• Creating Your Own Module:


You can create a file (e.g., mymodule.py) with functions, then import it in another script:
# In mymodule.py

def multiply(a, b):

return a * b

Then, in another file:

import mymodule

product = mymodule.multiply(4, 5)

print("Product is:", product)

Step 5: Hands-On Exercises

Exercise 1: Writing Simple Functions

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 Define the function with parameters.

o Use multiplication to compute the area.

o Return the result.

o Call the function with sample values and print the output.

3. Sample Code:

def calculate_area(width, height):

return width * height

# Test the function

area = calculate_area(5, 3)

print("The area of the rectangle is:", area)

Exercise 2: Function with Default and Keyword Arguments

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:

def introduce(name="Guest", age=0):


print(f"My name is {name} and I am {age} years old.")

introduce() # Uses default values

introduce(name="Alice", age=28) # Overrides default values

Exercise 3: Exploring Modules

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:

o Use random.randint(1, 100) to generate the random number.

o Use conditionals (if, elif, else) to compare the guess.

3. Sample Code:

import random

def guess_game(user_guess):

number = random.randint(1, 100)

if user_guess < number:

print("Too low!")

elif user_guess > number:

print("Too high!")

else:

print("Correct!")

# Test the function with a sample guess

guess_game(50)

Step 6: Experiment in the Interactive Shell

1. Open the Python Interactive Shell:

python

2. Try Out Function Commands:

# Define a simple function


def say_hi():

return "Hi there!"

print(say_hi())

# Function with parameters

def add_numbers(x, y):

return x + y

print("3 + 4 =", add_numbers(3, 4))

# Using a module function from math

import math

print("Square root of 25:", math.sqrt(25))

3. Exit the Shell:

exit()

You might also like