0% found this document useful (0 votes)
108 views2 pages

Python Function Practice Questions

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)
108 views2 pages

Python Function Practice Questions

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

Python Function Practice Questions (50)

Level 1: Basics (Q1-Q20)

1. Write a function to return the square of a number.

2. Write a function greet() that prints "Hello, World!".

3. Write a function that returns the sum of two numbers.

4. Write a function that calculates the average of two numbers.

5. Write a function that checks whether a number is even.

6. Write a function that checks whether a number is odd.

7. Write a function that returns the length of a given string.

8. Write a function to calculate the area of a rectangle.

9. Write a function to convert Celsius to Fahrenheit.

10. Write a function to calculate the cube of a number.

11. Write a function to find the greater of two numbers.

12. Write a function to return the first character of a string.

13. Write a function to return the last element of a list.

14. Write a function to return the largest number in a list.

15. Write a function to reverse a string.

16. Write a function that takes a name and returns 'Hello, <name>!'.

17. Write a function to calculate the area of a circle (use pi = 3.14).

18. Write a function to count the vowels in a string.

19. Write a function to check if a number is divisible by 5.

20. Write a function to return the sum of all elements in a list.

Level 2: Intermediate (Q21-Q40)

21. Write a function that returns all even numbers in a list.

22. Write a function that returns all odd numbers in a list.

23. Write a function to return only positive numbers from a list.

24. Write a function to check whether a string is a palindrome.

25. Write a function that counts how many times a word appears in a list.

26. Write a function to remove duplicates from a list.

27. Write a function to find the factorial of a number.

28. Write a function that returns True if a number is prime.


Python Function Practice Questions (50)

29. Write a function that returns a dictionary with words and their lengths.

30. Write a function to sum only the even numbers from a list.

31. Write a function that returns the common elements in two lists.

32. Write a function that checks whether two strings are anagrams.

33. Write a function that accepts a list of numbers and returns the median.

34. Write a function to return the maximum of three numbers.

35. Write a function that returns a list of all divisors of a number.

36. Write a function that returns the count of uppercase letters in a string.

37. Write a function that counts the number of words in a sentence.

38. Write a function that converts a list into a comma-separated string.

39. Write a function to calculate the simple interest (P, R, T).

40. Write a function that checks if a character is a vowel.

Level 3: Advanced / Functional (Q41-Q50)

41. Use map() and a lambda to square all numbers in a list.

42. Use filter() and a lambda to get only even numbers from a list.

43. Write a function using *args that returns the product of all inputs.

44. Write a function using **kwargs to print key-value pairs.

45. Write a function to return a list of tuples (number, square).

46. Use zip() to pair names with scores in a dictionary.

47. Write a function that returns a dictionary of even numbers and their cubes.

48. Write a recursive function to compute the nth Fibonacci number.

49. Write a function that takes a DataFrame column and returns the mean (pandas).

50. Write a function that plots a list using matplotlib.

Common questions

Powered by AI

Using *args and **kwargs in Python allows functions to accept arbitrary numbers of positional and keyword arguments, enhancing flexibility. For example, `def add(*args): return sum(args)` can sum an unspecified number of numbers. Similarly, `def print_kwargs(**kwargs):` allows key-value pairs to be passed and printed: `for key, value in kwargs.items(): print(f'{key} = {value}')`. This makes functions more reusable by accommodating varied input patterns .

To create a function that reverses a string in Python, you can define a function that uses slicing: `def reverse_string(s): return s[::-1]`. When reversing strings with special characters, such as Unicode characters, you should consider their representation. Python handles Unicode natively, so the reversal should work correctly as long as the input encoding is properly handled .

To determine if two strings are anagrams, you can sort both strings and check for equality: `sorted(str1) == sorted(str2)`. Alternatively, you can use a frequency count of characters using a dictionary or collections.Counter, comparing the two counts. The sorting approach has a time complexity of O(n log n), while using counts is O(n), making it more efficient for large strings .

To check if a string is a palindrome, you can normalize it by removing non-alphanumeric characters and converting it to lower case, then compare it to its reverse. For example, use `s = ''.join(filter(str.isalnum, s)).lower()` followed by checking `s == s[::-1]`. This approach ensures that case differences and non-letter/number characters do not affect the outcome .

The recursive computation of the nth Fibonacci number (e.g., `def fib(n): return n if n<=1 else fib(n-1) + fib(n-2)`) illustrates recursion's conceptual simplicity and elegance in expressing iterative processes. However, it highlights weaknesses such as exponential time complexity and stack overflow risks for large n, due to repeated calculations. Iterative or memoized recursive solutions can address these inefficiencies .

To convert Celsius to Fahrenheit in Python, use the formula `F = (C * 9/5) + 32`. The function can be defined as `def celsius_to_fahrenheit(c): return (c * 9/5) + 32`. Precision is crucial in this conversion, especially in scientific contexts, as small errors can propagate, affecting further calculations or decisions based on temperature data .

To convert a list to a comma-separated string in Python, use the `join()` method: `','.join(map(str, my_list))`. This process requires that all list elements be strings or are converted to strings, which might alter data representation if not handled carefully. Special characters in list elements, like commas, can inadvertently affect the integrity of the output .

The `zip()` function pairs elements from lists: `zip(list1, list2)`. For example, `zip([1, 2, 3], ['a', 'b', 'c'])` results in `[(1, 'a'), (2, 'b'), (3, 'c')]`. A limitation is that it stops at the shortest list, which can lead to data loss if not all elements are paired; thus, unequal lengths require careful handling, such as using `itertools.zip_longest` to ensure all elements are included .

Using map() with a lambda function to square numbers is concise and functional, as it applies the lambda expression to each element in the list without an explicit loop: `map(lambda x: x**2, my_list)`. This approach increases readability and can be more efficient with large datasets. However, it may reduce clarity for beginners unfamiliar with lambda syntax and map usage, and it returns a map object in Python 3 rather than a list, requiring conversion with `list()` .

Efficiently counting vowels in a string can be achieved by iterating once and using a set to check membership: e.g., `sum(1 for char in s if char.lower() in 'aeiou')`. Computational efficiency is important, especially with large strings, to minimize processing time and resource usage, which is critical for real-time applications or systems with limited resources .

You might also like