Question: Find the output of the following Python program.
s="welcome2kv"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)
Code language: Python (python)
Output:
vELCcME#Kk
Code language: CSS (css)
Also Read: How to Print a Circle Pattern in Java – Best 2 Ways
Explanation:
In the above python program, we have the given String s = ” welcome2kv”.
First, we have found the length of the given string by using the len( ) function and we have declared one empty string m=””. Then we have used for loop iteration.
Iteration-1:
Current Values | Operation |
s = “welcome2kv” n = 10 m = “” i = 0 | As i = 0 and s[0] = w, So m = m + s[i-1] m = “” + s[0-1] = “” + s[-1] = “” + v = v |
Iteration-2:
Current Values | Operation |
s = “welcome2kv” n = 10 m = v i = 1 | As i = 1 and s[1] = e, So m = m + s[i].upper() m = v + s[1].upper() = v + E = vE |
Iteration-3:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vE i = 2 | As i = 2 and s[2] = l, So m = m + s[i].upper() m = vE + s[2].upper() = vE + L = vEL |
Iteration-4:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vEL i = 3 | As i = 3 and s[3] = c, So m = m + s[i].upper() m = vEL + s[3].upper() = vEL + C = vELC |
Iteration-5:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELC i = 4 | As i = 4 and s[4] = o, So m = m + s[i-1] m = vELC + s[4-1] = vELC + c = vELCc |
Iteration-6:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELCc i = 5 | As i = 5 and s[5] = m, So m = m + s[i].upper() m = vELCc + s[5].upper() = vELCc + M = vELCcM |
Iteration-7:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELCcM i = 6 | As i = 6 and s[6] = e, So m = m + s[i].upper() m = vELCcM + s[6].upper() = vELCcM + E = vELCcME |
Iteration-8:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELCcME i = 7 | As i = 7 and s[7] = 2, So m = m +’#’ m = vELCcME + # = vELCcME + # = vELCcME# |
Iteration-9:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELCcME# i = 8 | As i = 8 and s[8] = k, So m = m + s[i].upper() m = vELCcME# + s[8].upper() = vELCcME# + K = vELCcME#K |
Iteration-10:
Current Values | Operation |
s = “welcome2kv” n = 10 m = vELCcME#K i = 9 | As i = 9 and s[9] = v, So m = m + s[i-1] m = vELCcME#K + s[9-1] = vELCcME#K + k = vELCcME#Kk |
So as per the last iteration, the value of m will be vELCcME#Kk. Finally, by using the print method( print(m) ), we have displayed the output to the user.