Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Last active October 6, 2024 17:59
Show Gist options
  • Select an option

  • Save cybersiddhu/5f02b7c3763bb0aaddfe2e9115d99d73 to your computer and use it in GitHub Desktop.

Select an option

Save cybersiddhu/5f02b7c3763bb0aaddfe2e9115d99d73 to your computer and use it in GitHub Desktop.
Learning python function for freshman

Python Functions Tutorial

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

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

Additional Exercises

  1. Write a function called calculate_average that takes a list of numbers as input and returns the average of those numbers.

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

  3. Write a function fibonacci that takes a number n as input and returns the nth number in the Fibonacci sequence.

  4. Create a function prime_factors that takes a number as input and returns a list of its prime factors.

  5. Write a function reverse_words that takes a sentence as input and returns the sentence with each word reversed, but the order of words in the sentence remains the same.

  6. Create a function caesar_cipher that takes a string and a shift value as input, and returns the string encoded using the Caesar cipher technique.

  7. Write a function binary_to_decimal that converts a binary number (given as a string) to its decimal equivalent.

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

  9. Write a function is_anagram that takes two strings as input and returns True if they are anagrams (contain the same letters in different orders), and False otherwise.

  10. Create a function generate_password that takes a length as input and generates a random password of that length, including uppercase and lowercase letters, numbers, and special characters.

  11. Write a function flatten_list that takes a nested list as input and returns a flattened version of the list.

  12. Create a function word_frequency that takes a string as input and returns a dictionary with words as keys and their frequencies as values.

  13. Write a function remove_duplicates that takes a list as input and returns a new list with duplicates removed, preserving the original order.

  14. Create a function matrix_transpose that takes a 2D list (matrix) as input and returns its transpose.

  15. Write a function validate_email that takes a string as input and returns True if it's a valid email address, and False otherwise.

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