0% found this document useful (0 votes)
8 views14 pages

Solutions

The document contains a collection of Python functions demonstrating various programming concepts such as arithmetic operations, string manipulation, recursion, and the use of lambda functions. Each function is accompanied by example calls and expected outputs. It serves as a comprehensive reference for basic to intermediate Python programming techniques.

Uploaded by

EBWW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

Solutions

The document contains a collection of Python functions demonstrating various programming concepts such as arithmetic operations, string manipulation, recursion, and the use of lambda functions. Each function is accompanied by example calls and expected outputs. It serves as a comprehensive reference for basic to intermediate Python programming techniques.

Uploaded by

EBWW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Add Two Numbers and Return the Result

def add(a, b):


return a + b

print(add(5, 3)) # Output: 8

2. Print String in Uppercase

def to_uppercase(s):
print([Link]())

to_uppercase("hello world") # Output: HELLO WORLD

3. Return the Square of a Number

def square(n):
return n * n

print(square(7)) # Output: 49

4. Return the Factorial of a Number

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

print(factorial(5)) # Output: 120

5. Greeting Message with Name

def greet(name):
print(f"Hello, {name}! Welcome!")

greet("Alice") # Output: Hello, Alice! Welcome!


6. Check Whether a Number is Even or Odd

def even_or_odd(n):
if n % 2 == 0:
print("Even")
else:
print("Odd")

even_or_odd(7) # Output: Odd


even_or_odd(8) # Output: Even

7. Return the Maximum of Three Numbers

def maximum(a, b, c):


return max(a, b, c)

print(maximum(10, 25, 15)) # Output: 25

8. Print Multiplication Table of a Number

def multiplication_table(n):
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")

multiplication_table(3)
# Output:
# 3 x 1 = 3
# 3 x 2 = 6
# ...
# 3 x 10 = 30

9. Calculate Area of a Circle

import math

def area_of_circle(r):
return [Link] * r * r

print(area_of_circle(5)) # Output: 78.53981633974483


10. Return the Number of Vowels in a String

def count_vowels(s):
vowels = 'aeiouAEIOU'
count = 0
for char in s:
if char in vowels:
count += 1
return count

# Example input and output


input_string = "Hello World"
print("Number of vowels:", count_vowels(input_string))
# Output: Number of vowels: 3

11. Greet User with Default Name "Guest"

def greet_user(name="Guest"):
print(f"Hello, {name}!")

greet_user("Alice") # Output: Hello, Alice!


greet_user() # Output: Hello, Guest!

12. Function with 2 Default Arguments (All Call Variants)

def show_info(name="Unknown", age=0):


print(f"Name: {name}, Age: {age}")

show_info("John", 25) # Positional


show_info("John") # One positional, one default
show_info() # Both default
show_info(age=30) # Keyword for age only
show_info(name="Lily") # Keyword for name only

13. Function Using Keyword Arguments

def display_info(name, age):


print(f"Name: {name}, Age: {age}")

display_info(name="David", age=22)
# Output: Name: David, Age: 22
14. Function power(base, exponent=2)

def power(base, exponent=2):


return base ** exponent

print(power(4)) # Output: 16 (4^2)


print(power(2, 3)) # Output: 8 (2^3)

15. Print String n Times (Default n=3)

def repeat_string(s, n=3):


for _ in range(n):
print(s)

repeat_string("Python") # Output: Python printed 3 times


repeat_string("Code", 2) # Output: Code printed 2 times

16. Print Student Details using Keyword Arguments

def student_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

student_details(name="Arjun", roll=101, grade="A")


# Output:
# name: Arjun
# roll: 101
# grade: A

17. Function with Three Parameters, Using Keywords

def describe_pet(name, type, age):


print(f"{name} is a {type} aged {age} years.")

describe_pet(type="Dog", name="Bruno", age=4)


# Output: Bruno is a Dog aged 4 years.

18. Simple Interest with Default Rate = 5%

def simple_interest(principal, time, rate=5):


return (principal * time * rate) / 100

print(simple_interest(1000, 2)) # Output: 100.0


print(simple_interest(1000, 2, 3)) # Output: 60.0
19. Keyword vs Positional Arguments

def order(item, quantity):


print(f"Item: {item}, Quantity: {quantity}")

order("Pen", 3) # Positional
order(quantity=5, item="Book") # Keyword

20. Reverse String with Optional Delimiter

def reverse_string(s, delimiter=None):


if delimiter:
parts = [Link](delimiter)
reversed_parts = parts[::-1]
return [Link](reversed_parts)
else:
return s[::-1]

print(reverse_string("Hello"))

# Output: olleH

print(reverse_string("apple,banana,grape", ","))

# Output: grape,banana,apple

21. Return Both Sum and Difference

def sum_and_diff(a, b):


return a + b, a - b

print(sum_and_diff(10, 4)) # Output: (14, 6)


22. Return Largest and Smallest from List

def find_min_max(lst):
return min(lst), max(lst)

print(find_min_max([3, 8, 1, 9])) # Output: (1, 9)

23. Prime Number Checker

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

print(is_prime(7)) # Output: True


print(is_prime(10)) # Output: False

24. Average of a List

def average(lst):
return sum(lst) / len(lst)

print(average([2, 4, 6])) # Output: 4.0

25. Count Digits and Alphabets

def count_chars(s):
digits = sum([Link]() for c in s)
alphabets = sum([Link]() for c in s)
return digits, alphabets

print(count_chars("abc123")) # Output: (3, 3)


26. Length of Longest Word

def longest_word_len(sentence):
words = [Link]()
return len(max(words, key=len))

print(longest_word_len("I love programming in Python")) #


Output: 11

27. Count Even and Odd Numbers

def count_even_odd(lst):
even = sum(1 for x in lst if x % 2 == 0)
odd = len(lst) - even
return even, odd

print(count_even_odd([1, 2, 3, 4, 5])) # Output: (2, 3)

28. Count Words in a Sentence

def word_count(sentence):
return len([Link]())

print(word_count("Python is awesome")) # Output: 3

29. Celsius to Fahrenheit

def celsius_to_fahrenheit(c):
return (c * 9/5) + 32

print(celsius_to_fahrenheit(0)) # Output: 32.0


print(celsius_to_fahrenheit(100)) # Output: 212.0
30. Sum of Squares of First n Natural Numbers

def sum_of_squares(n):
return sum(i*i for i in range(1, n+1))

print(sum_of_squares(3)) # Output: 14 (1^2 + 2^2 + 3^2)

31. Sum of *args

def total_sum(*args):
return sum(args)

print(total_sum(1, 2, 3, 4)) # Output: 10

32. Print Each String from *args

def print_strings(*args):
for s in args:
print(s)

print_strings("Hello", "World", "Python")

33. Print Employee Details (**kwargs)

def employee_details(**kwargs):
for k, v in [Link]():
print(f"{k}: {v}")

employee_details(name="Sam", id=101, dept="IT")


34. Max Among *args

def max_in_args(*args):
return max(args)

print(max_in_args(5, 2, 10, 7)) # Output: 10

35. Print Key-Value Pairs from **kwargs

def print_kwargs(**kwargs):
for k, v in [Link]():
print(f"{k} = {v}")

print_kwargs(a=1, b=2)

36. Multiply All Numbers in *args

def multiply_all(*args):
result = 1
for num in args:
result *= num
return result

print(multiply_all(2, 3, 4)) # Output: 24


37. Total Marks from **kwargs

def total_marks(**kwargs):
return sum([Link]())

print(total_marks(math=90, sci=85, eng=88))

# Output: 263

38. Separate Even/Odd from *args

def separate_even_odd(*args):
even = [x for x in args if x % 2 == 0]
odd = [x for x in args if x % 2 != 0]
return even, odd

print(separate_even_odd(1, 2, 3, 4, 5)) # Output: ([2, 4],


[1, 3, 5])

39. Check if status in **kwargs

def check_status(**kwargs):
return "status" in kwargs

print(check_status(name="Alex", status="Active")) # Output:


True
print(check_status(user="Tom")) # Output:
False
40. Count of args and kwargs

def count_args_kwargs(*args, **kwargs):


return len(args), len(kwargs)

print(count_args_kwargs(1, 2, a=3, b=4)) # Output: (2, 2)

41. Modify Global Variable

count = 0

def increment():
global count
count += 1

increment()
print(count) # Output: 1

42. Nested Function: Add then Square

def outer(a, b):


def inner(x, y):
return x + y
return inner(a, b) ** 2

print(outer(2, 3)) # Output: 25


43. Function Inside Function

def outer():
def inner():
print("Inner function called")
inner()

outer()

44. Lambda to Square a Number

square = lambda x: x ** 2
print(square(5)) # Output: 25

45. map() with Lambda for °C to °F

temps = [0, 10, 20, 30]


f_temps = list(map(lambda c: (c * 9/5) + 32, temps))
print(f_temps) # Output: [32.0, 50.0, 68.0, 86.0]

46. filter() with Lambda to Keep Evens

nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4]

47. reduce() to Find Product

from functools import reduce

nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24
48. Recursive Sum of First n Numbers

def recursive_sum(n):
if n == 0:
return 0
return n + recursive_sum(n - 1)

print(recursive_sum(5)) # Output: 15

49. Recursive String Reversal

def reverse_string(s):
if len(s) == 0:
return ""
return reverse_string(s[1:]) + s[0]

print(reverse_string("hello")) # Output: olleh

50. nonlocal Keyword Demonstration

def outer():
x = 5
def inner():
nonlocal x
x += 1
print("Inner x:", x)
inner()
print("Outer x:", x)

outer()
# Output:
# Inner x: 6
# Outer x: 6

You might also like