Unit II To V Python Programs With Answers
Unit II To V Python Programs With Answers
Number reversal in Python can be achieved using string slicing. By converting the number to a string, slicing syntax allows for reversal. The expression `s[::-1]` creates a new string that is the reverse of `s`. For example, with `n=input()`, calling `n[::-1]` returns the reversed string, effectively reversing the digits of the number .
Default arguments provide a mechanism to define functions with optional parameter values, making function calls more versatile. For instance, `def greet(name='User'):` defaults the parameter `name` to 'User' if no argument is passed during the function call, allowing flexible use of the function `greet()`, which will simply print 'User', but if a name is provided, it will print the given name. This feature supports user-friendly API design by decreasing the need for function overloading .
The algorithm uses modulo operation to determine if a number is even or odd. Specifically, it checks the remainder of the number when divided by 2; if the remainder is 0, the number is even, otherwise it's odd. This logic is encapsulated in the Python expression `n%2==0`, which evaluates to True for even numbers and False for odd numbers .
List comprehensions provide a compact way of generating lists. To create a list of squares of integers from 1 to n inclusive, one can use the syntax `[i*i for i in range(1, n+1)]`. This expression iteratively computes the square of each integer i in the specified range and collects them into a new list. This approach is not only concise but also more efficient and readable compared to the traditional loop-based list creation .
A nested loop can be used to iterate over different rows and columns to construct the multiplication table. The outer loop iterates over the multiplicand (typically from 1 to n), while the inner loop iterates over a static range (e.g., 1 to 10) representing the multiplier. For example, `for i in range(1, 11): print(n, 'x', i, '=', n*i)` effectively calculates and prints `n` times each number `i`, forming a structured table. This systematic approach leverages the repetitive nature of the task .
To check and count vowels in a string, Python's comprehension and built-in functions are utilized. The string is first converted to lowercase to ensure uniformity during checks. Using a generator expression, the program iterates over the string and sums instances where a letter matches any vowel ('a', 'e', 'i', 'o', 'u'). This is expressed as `sum(1 for c in s if c in 'aeiou')`, which counts each occurrence efficiently .
Recursive functions handle repetitive tasks by breaking down the problem into smaller instances of the same problem. In summing natural numbers, recursion is employed by defining a function that returns the sum of `n` plus the sum of `n-1`. The base case is `n=0`, which returns 0, ending the recursion. This method elegantly captures the natural reduction of the problem and is succinctly expressed with `def sum_n(n): return n+sum_n(n-1) if n > 0 else 0` .
Python dictionaries are versatile for storing hierarchical information due to their key-value structure. A nested dictionary can encapsulate multiple layers of data, resembling complex datasets. For example, a student score record could be organized as `d={'s1':{'math':90, 'science':95}}`, where 's1' is the student ID, and the nested dictionary stores scores in subjects. Accessing `d['s1']['math']` retrieves the math score, demonstrating easy access and storage of related data through keys .
Python utilizes the built-in `max()` function to compare values and determine the largest one. Given three numbers, a, b, and c, the expression `max(a, b, c)` evaluates these numbers and returns the one with the maximum value using simple comparison internally, which is efficient for this task .
Lambda functions in Python serve as a concise way to define anonymous functions used for simple tasks. Unlike regular functions created with `def`, lambda functions do not require naming and are limited to a single expression which is evaluated and returned. For example, `sq=lambda x: x*x` quickly defines a square function without additional structure. Lambda functions favor brevity and are often used for short-term purposes like inline function arguments due to their simplicity and speed in being defined and executed .