Prerequisite -
Loops in PythonPredict the output of the following Python programs.
- 1) What is the output of the following program?
Output:Python x = ['ab', 'cd'] for i in x: i.upper() print(x)
['ab', 'cd']
Explanation: The function upper() does not modify a string in place, but it returns a new string which here isnât being stored anywhere. So we will get our original list as output. - 2) What is the output of the following program?
Output:Python x = ['ab', 'cd'] for i in x: x.append(i.upper()) print(x)
No Output
Explanation: The loop does not terminate as new elements are being added to the list in each iteration. So our program will stuck in infinite loop - 3) What is the output of the following program?
Output:Python i = 1 while True: if i%3 == 0: break print(i) i + = 1
No Output
Explanation: The program will give no output as there is an error in the code. In python while using expression there shouldnât be a space between + and = in +=. - 4) What is the output of the following program?
Output:Python x = 123 for i in x: print(i)
Error!
Explanation: Objects of type int are not iterable instead a list, dictionary or a tuple should be used. - 5) What is the output of the following program?
Python for i in [1, 2, 3, 4][::-1]: print (i)
Output:
4Explanation: Adding [::-1] beside your list reverses the list. So output will be the elements of original list but in reverse order.
3
2
1