Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for in loop
#1
s = "ball"
r = ""
for item in s:
    r = item.upper() +  r
print(r)
Output will be LLAB, i.e print from the back.
Why is that so?
Reply
#2
s = "ball"
r = ""
for item in s: # iterate over chars in s, i.e. value of item will change with each iteration of the loop
    print('item value -> {}'.format(item))
    r = item.upper() +  r # value of r will change, adding the value of item, upper case at the beginning of the old r value
    print('r value -> {}'.format(r))
print(r) # print the new value of r
I have added 2 print statements to show item and r values at each iteration.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020