Translate

Monday, October 13, 2025

PP_Functions and Methods

A Python function is a reusable block of code designed to perform a specific operation. The function is typically dependent on inputs (parameters) and arguments (values of the parameters). A function is defined using the def keyword, the function name, a pair of parentheses (), and a colon (:). The code block for the function must be indented.

The Syntax:

def function_name(parameter1, parameter2):

   # Function body

   # Code to be executed

  return expression 

 

Where: 

§ parameters: Placeholders for the data you pass into a function (optional).

§ def: The keyword shows that it is a function definition.

§ function_name: Descriptive name of the function (Also see Lecture on data types and variables).

§ return: Exits a function and returns a value to the caller. (Locally defined variables are lost if not saved somewhere after execution of the function)

Calling a Function

To call a function means to execute the function that has been defined either directly from the Python prompt or through another function (in the case of nested functions).  A function is called using the function name followed by parentheses ().

Example:

def greet(name):

  #A function that greets

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

  #Calling the function

greet("Aggrey") # Output should be -  Hello, Aggrey!

Parameters & Arguments

A parameter is one of the variables listed inside the function parentheses in the function definition. While an argument is the value assigned to the parameters and are sent to the function when it is called. For example the function defined below adds two numbers a and b. The parameters are a and b, while the argiments are the values defined for a and b.

 

def add(a, b):

Types of Arguments

1.Default Arguments: These are arguments assumed by the variable if no argument is provided for that parameter.

def say_hello(name="User"):

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

 

say_hello() # Output will be "Hello, User!" since no argument is specified.

say_hello("Bob") # Outputs "Hello, Bob!" since the provided argument is Bob

2.                 Positional arguments are arguments that need to be included in the proper position or order. And so should the arguments be passed in the same order as the parameters are defined.

def add(a, b):

  return a - b

 

result = add(5, 3) # 5 and 3 are positional arguments

print(result) # Output should be 2

3.                 Keyword Arguments: This mode eliminates the need to specify the order with which the arguments are provided. 

def subtract(a, b):

  return a - b

 

result = subtract(b=5, a=15) # a and b are keyword arguments

print(result) # Output should be 10

4.                 Arbitrary Arguments

    *args is used to pass a variable number of non-keyword arguments to a function. The arguments are packed into a tuple.

def calculate_sum(*args):

  total = 0

  for num in args:

          total += num

  return total

print(calculate_sum(1, 2, 3, 4, 5)) # Output: 15

    **kwargs pass a variable number of keyword arguments. packing them into a dictionary

def print_info(**kwargs):

  for key, value in kwargs.items():

          print(f"{key}: {value}")

 

print_info(name="Michael", age=60) # Output: name: Michael, age: 60

 

Global and Local Variables

Variables declared inside a function have a local scope, they are therfore only accessible from within that particular function. While Global variables are defined from outside the function and can be accessed from anywhere in the program.

A local variable can however be modified to allow access from outside the function as follows;

x = 120 # This is a Global variable defined outside the function

 

def scope_function():

  y = 5 # This is a local variable only accessed from within the scope_function

  print(x) # This call can access the global variable x

  print(y) # This call can access the local variable y since it is defined within the scope_function

 

scope_function()

# print(y) # This would cause an error because y is only defined in the local scope and not defined in the global scope

 

We thus have to modify this;

 

def scope_function1():

  global x

  x = 120 # Modifies the global variable x

 

scope_function1()

print(x) # The output should now give: 120

 

Reading: What is a Lambda Function, and where is it used? 

 

METHODS

A method is a function that is associated with a particular object or class. Methods are defined within a class and are looked at as objects of that class. In Python, both functions and methods are blocks of reusable code, however a method is a function that belongs to an object.

Some of the key distinguishing characteristics of a function are that a function is standalone, uses the "def" keyword, and can be called from anywhere in the program. Methods, on the other hand, are;

§ Belongs to a particular class and performs operations on that data within the class alone

§ Methods use the dot(.) notation instead of the "def" keyword

§ Associated with a specific object or data type, and

§ Have the object instance (self) as their first parameter

Example 1.

# Note that 'upper()' is a string method (Remember from the previous lecture "String" was one of the primitive data types)

name = "tutorialsarc"

print(name.upper()) # Output should be "TUTORIALSARC"

In this example, upper cannot be applied on an "int" data type. It is thus a method only applicable on the string data type

 

Example 2.

# 'append()' is a list method and therefore applicable on lists

our_list = [1, 2, 3, 4, 5]

our_list.append(6)

print(my_list) # Output: [1, 2, 3, 4, 5]

 

In conclusion, although methods and functions sound similar, they are different and are used in different scenarios. Functions are used when the operation does not require access to the internal state of a specific object. While methods are used when the operation is specific to an object data

 

CLASS ACTIVITY - METHODS

Creating and Modifying a Gradebook

Activity 1: Creating a Student Gradebook

Task: Create a class named Student that takes two pieces of information: the student's name and their score. These pieces of information are attributes of the student object. The new student's name is "Jane" with a starting score of 82.

student1 = Student("Jane", 82)

Print the student's name and score to confirm that it worked.

print(f"{student1.name}'s initial score is {student1.score}")

Activity 2: Adding a New score

Add a method to the Student class to perform the modification. An instance method is a function that belongs to an object and can change the object's data.

We create a method and give it a name add_score. It will take a new score (an integer) and add to the existing. (Use self to access the object's attributes). In this case add 10 marks to Jane

We use the add_score method to give Alex 10 extra points.  Confirm by printing the new mark.

student1.add_score(10)

 

# Print the new score

print(f"{student1.name}'s new score is {student1.score}")

Activity 3: Calculating the Average

Assuming a student has two scores. Add a new method to  Student class called get_average_score. Note that the method does not take any more arguments.

Create a second student named "Mia" with an initial score of 70. Use the add_score method to give Mia 60 points. Then, call the get_average_score method for Mia and print the returned average.

# Your code here...

student2 = Student("Mia", 70)

student2.add_score(60)

 

# Calculate and print the average

average = student2.get_average_score()

print(f"{student2.name}'s average score is {average}")

 


What is the purpose of the len() method when applied to a string in Python?

No comments:

Post a Comment