Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Last active October 6, 2024 17:59
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

Python Functions Tutorial

Table of Contents

  1. Basic Concepts
    1. Basic Function Definition and Calling
    2. Function with Parameters
    3. Function with Return Value
    4. Function with Multiple Parameters
    5. Function with Default Parameter
  2. Intermediate Concepts
    1. Function with Multiple Return Values
    2. Function with a List Parameter
    3. Function with Conditional Logic
    4. Function with a Loop and Accumulator
  3. Exercises
    1. Basic Exercises
    2. Intermediate Exercises
    3. Challenge Exercises

Basic Concepts

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.

2. 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.

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

4. 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.

5. 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.

Intermediate Concepts

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.

2. 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.

3. 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.

4. 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.

Exercises

Basic Exercises

  1. 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. Example input: calculate_grade(85)

  2. Write a function called calculate_average that takes a list of numbers as input and returns the average of those numbers. Example input: calculate_average([80, 90, 70, 60, 85])

  3. Create a function is_even that takes a number as input and returns True if it's even, and False if it's odd. Example input: is_even(7)

  4. Write a function reverse_string that takes a string as input and returns the reversed string. Example input: reverse_string("Hello, World!")

  5. Create a function 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. Example input: count_vowels("OpenAI")

Intermediate Exercises

  1. Write a function is_palindrome that takes a string as input and returns True if it's a palindrome (reads the same forwards and backwards), and False otherwise. Ignore spaces and capitalization. Example input: is_palindrome("A man a plan a canal Panama")

  2. Create a function find_largest that takes a list of numbers as input and returns the largest number in the list. Example input: find_largest([5, 2, 9, 1, 7])

  3. Write a function count_words that takes a sentence as input and returns the number of words in the sentence. Example input: count_words("The quick brown fox jumps over the lazy dog")

  4. Create a function celsius_to_fahrenheit that converts a temperature from Celsius to Fahrenheit. Example input: celsius_to_fahrenheit(25)

  5. Write a function generate_multiplication_table that takes a number n as input and prints the multiplication table for that number up to 10. Example input: generate_multiplication_table(7)

Challenge Exercises

  1. Create a function find_common_elements that takes two lists as input and returns a list of elements that are common to both input lists. Example input: find_common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])

  2. Create a function remove_duplicates that takes a list as input and returns a new list with duplicates removed, preserving the original order. Example input: remove_duplicates([1, 2, 2, 3, 4, 4, 5])

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