Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Created September 2, 2024 21:16
Show Gist options
  • Save cybersiddhu/388ddcef7767d95e48d3f67821b935c9 to your computer and use it in GitHub Desktop.
Save cybersiddhu/388ddcef7767d95e48d3f67821b935c9 to your computer and use it in GitHub Desktop.
python functions freshman continued ....
  1. Function with String Manipulation
def create_username(first_name, last_name):
    first_initial = first_name[0].lower()
    username = f"{first_initial}{last_name.lower()}"
    return username[:8]  # Limit username to 8 characters

# Using the function
username = create_username("John", "Doe")
print(f"Generated username: {username}")

Explanation:

  • This function takes a first name and last name as input.
  • It gets the first letter of the first name and makes it lowercase.
  • It combines this with the lowercase version of the last name.
  • The function returns only the first 8 characters of this combination.
  • This creates a simple username based on the person's name.
  1. Function with List Comprehension
def get_even_numbers(numbers):
    even_nums = [num for num in numbers if num % 2 == 0]
    return even_nums

# Using the function
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = get_even_numbers(number_list)
print(f"The even numbers are: {evens}")

Explanation:

  • This function takes a list of numbers as input.
  • It uses a list comprehension to create a new list.
  • The list comprehension checks each number in the input list.
  • If a number is even (divisible by 2 with no remainder), it's included in the new list.
  • The function returns this new list of even numbers.
  1. Function with Dictionary Parameter
def calculate_total_cost(items, tax_rate):
    subtotal = sum(items.values())
    tax = subtotal * (tax_rate / 100)
    total = subtotal + tax
    return round(total, 2)

# Using the function
shopping_cart = {"apple": 0.50, "banana": 0.75, "orange": 0.80}
total_cost = calculate_total_cost(shopping_cart, 8)
print(f"Total cost including tax: ${total_cost}")

Explanation:

  • This function takes a dictionary of items (with prices) and a tax rate.
  • It calculates the subtotal by summing all the prices in the dictionary.
  • It then calculates the tax amount based on the given tax rate.
  • The total is the sum of the subtotal and tax.
  • The function returns this total, rounded to 2 decimal places.
  1. Function with Error Handling
def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return "Error: Cannot divide by zero"

# Using the function
print(divide_numbers(10, 2))
print(divide_numbers(5, 0))

Explanation:

  • This function attempts to divide two numbers.
  • It uses a try-except block to handle potential errors.
  • If the division is successful, it returns the result.
  • If there's an attempt to divide by zero, it catches the error.
  • Instead of crashing, it returns an error message as a string.
  1. Function with Default Parameters and Type Hints
def create_greeting(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"

# Using the function
print(create_greeting("Alice"))
print(create_greeting("Bob", "Hi"))

Explanation:

  • This function uses type hints to indicate that name and greeting should be strings.
  • The -> str indicates that the function will return a string.
  • greeting has a default value of "Hello".
  • If no greeting is provided when calling the function, it uses "Hello".
  • The function combines the greeting and name into a single string.

Exercise: Create a function called analyze_text that takes a string as input. The function should return a dictionary containing the following information about the text:

  1. The number of characters (including spaces)
  2. The number of words
  3. The number of unique words (case-insensitive)

For example, if the input is "The quick brown fox jumps over the lazy dog", the output should be something like:

{
    "characters": 43,
    "words": 9,
    "unique_words": 8
}

These examples introduce concepts like string manipulation, list comprehensions, working with dictionaries, error handling, and type hinting. The explanations continue to break down each part of the function to help students understand the concepts step by step. The final exercise challenges students to combine several of these concepts into a more complex function.

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