Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Last active September 2, 2024 21:10
Show Gist options
  • Save cybersiddhu/5f02b7c3763bb0aaddfe2e9115d99d73 to your computer and use it in GitHub Desktop.
Save cybersiddhu/5f02b7c3763bb0aaddfe2e9115d99d73 to your computer and use it in GitHub Desktop.
Learning python function for freshman
  1. Basic Function Definition and Calling
def say_hello():
    print("Hello, friend!")

# Using the function
say_hello()

Explanation:

  • We define a function called say_hello using the def keyword.
  • The function doesn't take any parameters (that's why the parentheses are empty).
  • Inside the function, we have one line of code that prints a message.
  • To use (or "call") the function, we write its name followed by parentheses.
  1. Function with Parameters
def greet(name):
    print(f"Hello, {name}!")

# Using the function
greet("Alice")
greet("Bob")

Explanation:

  • This function, greet, takes one parameter called name.
  • When we call the function, we provide a value for name inside the parentheses.
  • The function uses this name to create a personalized greeting.
  • We can call the function multiple times with different names.
  1. Function with Return Value
def add_five(number):
    result = number + 5
    return result

# Using the function
answer = add_five(10)
print(answer)  # This will print 15

Explanation:

  • This function add_five takes a number as input.
  • It adds 5 to this number and stores it in result.
  • The return statement sends this result back to wherever the function was called.
  • When we use the function, we can store its returned value in a variable (like answer).
  1. Function with Multiple Parameters
def calculate_rectangle_area(length, width):
    area = length * width
    return area

# Using the function
rectangle1_area = calculate_rectangle_area(5, 3)
print(f"The area of the rectangle is: {rectangle1_area}")

Explanation:

  • This function takes two parameters: length and width.
  • It multiplies these values to calculate the area of a rectangle.
  • The calculated area is then returned.
  • When calling the function, we need to provide two values, one for each parameter.
  1. Function with Default Parameter
def greet_with_title(name, title="Mr."):
    print(f"Hello, {title} {name}!")

# Using the function
greet_with_title("Smith")
greet_with_title("Johnson", "Dr.")

Explanation:

  • This function has two parameters: name and title.
  • title has a default value of "Mr.". This means if we don't provide a title, it will use "Mr.".
  • In the first function call, we only provide the name, so it uses the default title.
  • In the second call, we provide both a name and a title, overriding the default.

Exercise: Create a function called calculate_grade that takes a student's score as a parameter. The function should return "A" for scores 90 and above, "B" for scores 80-89, "C" for 70-79, "D" for 60-69, and "F" for anything below 60.

These examples and explanations should be more suitable for high school freshmen. They introduce basic concepts of functions step-by-step, with clear explanations of what each part does. The exercise at the end allows students to apply what they've learned in a practical scenario.


  1. Function with Multiple Return Values
def get_name_parts(full_name):
    parts = full_name.split()
    first_name = parts[0]
    last_name = parts[-1]
    return first_name, last_name

# Using the function
first, last = get_name_parts("John Doe Smith")
print(f"First name: {first}")
print(f"Last name: {last}")

Explanation:

  • This function takes a full name as input.
  • It uses the split() method to separate the name into parts.
  • It then assigns the first part to first_name and the last part to last_name.
  • The function returns both of these values.
  • When calling the function, we can assign both returned values to separate variables at once.
  1. Function with a List Parameter
def find_longest_word(word_list):
    longest_word = ""
    for word in word_list:
        if len(word) > len(longest_word):
            longest_word = word
    return longest_word

# Using the function
words = ["apple", "banana", "cherry", "date", "elderberry"]
longest = find_longest_word(words)
print(f"The longest word is: {longest}")

Explanation:

  • This function takes a list of words as input.
  • It uses a for loop to go through each word in the list.
  • It compares the length of each word with the current longest word.
  • If a longer word is found, it becomes the new longest word.
  • After checking all words, the function returns the longest one found.
  1. Function with Conditional Logic
def classify_temperature(temp):
    if temp < 0:
        return "Freezing"
    elif temp < 10:
        return "Cold"
    elif temp < 20:
        return "Cool"
    elif temp < 30:
        return "Warm"
    else:
        return "Hot"

# Using the function
temperature = 25
classification = classify_temperature(temperature)
print(f"{temperature} degrees is classified as: {classification}")

Explanation:

  • This function takes a temperature value as input.
  • It uses a series of if-elif-else statements to classify the temperature.
  • Each condition checks if the temperature is below a certain threshold.
  • The function returns the appropriate classification as a string.
  • When we call the function, it evaluates the input and returns the classification.
  1. Function with a Loop and Accumulator
def sum_even_numbers(numbers):
    total = 0
    for num in numbers:
        if num % 2 == 0:  # Check if the number is even
            total += num
    return total

# Using the function
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sum = sum_even_numbers(number_list)
print(f"The sum of even numbers is: {even_sum}")

Explanation:

  • This function takes a list of numbers as input.
  • It initializes a total variable to keep track of the sum.
  • It loops through each number in the list.
  • For each number, it checks if it's even by using the modulo operator (%).
  • If the number is even, it's added to the total.
  • After checking all numbers, the function returns the total sum of even numbers.

Exercise: Create a function called count_vowels that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels.

These examples introduce slightly more complex concepts like working with lists, using loops within functions, and implementing more detailed logic. The explanations break down each part of the function to help students understand what's happening step by step. The exercise at the end challenges students to apply these concepts in a new context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment