Coding Question Functions in Python

Coding Question Functions in Python

Coding Question Functions in Python

Interested in above project ,Click Below
WhatsApp
Telegram
LinkedIn

Coding Question Functions in Python

1. Basic Function Practice

a. is_even(): Check if a number is even

def is_even(number):
    return number % 2 == 0

# Example usage:
print(is_even(4))  # Output: True
print(is_even(7))  # Output: False

b. factorial(): Calculate the factorial using a loop

def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# Example usage:
print(factorial(5))  # Output: 120
print(factorial(0))  # Output: 1

2. Function Arguments

a. greet_user(): Greeting with keyword arguments

def greet_user(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")

# Example usage with keyword arguments:
greet_user(first_name="John", last_name="Doe")
# Output: Hello, John Doe!

b. calculate_area(): Calculate the area of a circle with a default argument

def calculate_area(radius, pi=3.14159):
    return pi * radius * radius

# Example usage:
print(calculate_area(5))        # Output: 78.53975
print(calculate_area(5, 3.14))  # Output: 78.5 (using a different value of pi)

3. Working with Return Values

a. find_max(): Find the maximum value in a list

def find_max(numbers):
    if not numbers:
        return None
    max_value = numbers[0]
    for number in numbers:
        if number > max_value:
            max_value = number
    return max_value

# Example usage:
print(find_max([1, 2, 3, 4, 5]))  # Output: 5
print(find_max([-10, -20, -30]))  # Output: -10

b. reverse_string(): Reverse a string

def reverse_string(s):
    return s[::-1]

# Example usage:
print(reverse_string("hello"))  # Output: "olleh"
print(reverse_string("world"))  # Output: "dlrow"

4. Lambda Functions

a. List of squares using map()

squares = list(map(lambda x: x ** 2, range(1, 11)))

# Example usage:
print(squares)  # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

b. Filter words shorter than 5 characters using filter()

words = ["apple", "banana", "pear", "kiwi", "grape"]
long_words = list(filter(lambda word: len(word) >= 5, words))

# Example usage:
print(long_words)  # Output: ['apple', 'banana']

5. Advanced Lambda Usage

a. reduce(): Find the product of all elements in a list

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)

# Example usage:
print(product)  # Output: 120

b. Combine map() and filter(): Squares of even numbers from 1 to 20

squares_of_even_numbers = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, range(1, 21))))

# Example usage:
print(squares_of_even_numbers)  # Output: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

See also  Top 10 Final Year Project Ideas for Java

Â