Python Programming Questions and Answers
Python Programming Questions and Answers
The program 'for x in (10, 20, 30): print("Hello World")' prints "Hello World" three times, once for each element in the tuple (10, 20, 30). The loop iterates through each element, executing the print statement each time .
The output of the snippet 'set_A={'A', 2, 4, 'D'}; set_B={'A', 'B', 'C', 'D'}; print(set_A & set_B)' is {'A', 'D'}. The expression 'set_A & set_B' computes the intersection of the two sets, which includes only the elements present in both sets .
The syntax of the if..else statement in Python is: ```python if condition: statement(s) else: statement(s) ``` The 'if' statement evaluates a condition (an expression that returns True or False). If the condition is True, it executes the block of code under the 'if'. If the condition is False, the code under the 'else' is executed. This allows for conditional branching in Python programs .
Python's list comprehension '[x**2 for x in range(1,11)]' generates a list by iterating through numbers in the range from 1 to 10, squaring each number, and collecting the results in a list. The output will be the list: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
The slicing operation 'str1[::-3]' with 'str1' initialized as "welcome" reverses the string and selects every third character starting from the end. The output will be 'eoe'. This is because it starts from the last character and moves backwards in steps of three .
In Python, the colon within square brackets is used for slicing strings. 'str1[:2]' takes the first two characters of 'str1'. 'str2[len(str2)-2:]' extracts the last two characters of 'str2'. Concatenating these slices results in a new string composed of these selected segments .
The 'capitalize()' method in Python returns a copy of a string with the first character converted to uppercase and all other characters converted to lowercase. For example, using '"hello world".capitalize()' will return 'Hello world'. This method helps standardize strings to a title-case format .
The code 'for x in range(1, 6): print('C' * x)' iteratively prints strings composed of the character 'C', increasing in length with each iteration. The final output would be: C CC CCC CCCC CCCCC Each line adds one more 'C' than the previous line, resulting in an incremental pyramid pattern of 'C's .
The list comprehension '[2**x for x in range(5)]' produces the output [1, 2, 4, 8, 16]. This is because it iterates over the range 0 to 4, and for each 'x', it calculates 2 raised to the power of 'x', collecting these powers of two in a list .
The expression 'str1="WELCOME"; print(str1.islower())' calls the 'islower()' method on the string 'str1'. This method returns True if all alphabetic characters in the string are lowercase and there is at least one alphabetic character. Since "WELCOME" is entirely uppercase, 'str1.islower()' evaluates to False, so the output is 'False' .