Ask your own question, for FREE!
MIT 6.189 A Gentle Introduction to Programming Using Python (OCW) 21 Online
OpenStudy (anonymous):

I'm trying the MT 6.189 Optional exercises (before looking at the recently posted answers) and I have a question - When it says implement this loop and understand what it does before moving on: for c in phrase: encoded_phrase = encoded_phrase + c There is something I don't quite understand - where is c coming from? It is not previously declared in any way, and it acts like a named keyword for a character, but I thought there was no "char" type variable in Python. What am I missing here? Why does this work?

ganeshie8 (ganeshie8):

'phrase' is a string of characters, right ?

OpenStudy (anonymous):

…and `c` is an element of `phrase` (as stated in the first line of code), right?

OpenStudy (espex):

Unlike C, C++, or Java, Python allows you to declare variables on the fly. The Python code: for c in phrase does the equivalent of the following C++ code: char c; string phrase = "Something"; for (int i = 0; i<(phrase.length - 1); i++){ c = phrase[i]; .... .... }

OpenStudy (anonymous):

OK. That seems... exactly like what it's doing. :) I appreciate the C++ reply, that helped a lot to understand. It functions just as if I had declared some kind of variable/object that is a character, and then used it to loop through all the characters in some previously declared string variable called phrase. The whole "declaring on the fly" part was just throwing me for a loop. I'll just roll with it for now - I'm sure this concept will come up again later and be explored in more detail, how that works, when it's great and when it's not, et cetera. Thanks for the help!

OpenStudy (e.mccormick):

It is not "just throwing [you] for a loop" it is throwing an undeclared variable for one! Hehe.

OpenStudy (espex):

@e.mccormick: Funny. :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!