Quiz: Loops – for

Hello,

For the question below:

x = 'abcd'
for i in x:
    print(i)
    x.upper()

the correct answer was given as:

A
B
C
D

However, when I executed it in Python Editor, the answer I got was:

a
‘ABCD’
b
‘ABCD’
c
‘ABCD’
d
‘ABCD’

Please check.

Could you please supply me with a link to the lab in question?

Just checking the python you give me, here’s the result I get in ipython:

Python 3.9.18 (main, Nov  2 2023, 17:01:24)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.30.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: x = 'abcd'
   ...: for i in x:
   ...:     print(i)
   ...:     x.upper()
   ...:
a
b
c
d

So if that’s not what’s in the lab, yeah, the lab would be wrong.

The correct answer would be

a
b
c
d

so the lab is incorrect in saying that they are capitals.

The difference between @adityarv 's and @rob_kodekloud 's outputs are down to the python interpreter being used. There are some command line based ones lthat will output the return value of any function that returns a value to the console if nothing consumes the return value - mine is the same - you’re getting the output of
abcd.upper()
with each time round the loop.

If you put that code into a file e.g. test.py and run it with

python test.py

then the output would always be

a
b
c
d

@rob_kodekloud, @Alistair_KodeKloud

Thank you for the help. Whatever you explained was correct.

My apologies. Looks like I mentioned the wrong answer.

@Alistair_KodeKloud - I’ve a question though.

As you mentioned, There are some command line based interpreters that will output the return value of any function that returns a value to the console if nothing consumes the return value.

In that case is it better to put code (be it few lines) in a .py file instead of trying on the command line itself. Please advise.

If you don’t want to be confused by what is actual printed output and what is being emitted by the interactive interpreter, then yes.

Much better to use VSCode on your machine and install the Python extensions. Then you have a debugger too so you can step the code one line at a time and see the effect on variables.