Hi. I had one question. At the end of lecture 4 he executes that code that adds the digits for the str 1952. it looks like: sumDigits = 0 for c in str(1952): sumDigits += c print c I don't get why that works when C isn't defined. Moreover this works for any letter you put in. What relation does C have to the str 1952?
Hello huynhdq, You should refer to the for Statements in the documentation : "[...] Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence." (see: http://docs.python.org/tutorial/controlflow.html#for-statements). I think it should answer at your 2 questions. I didn't go through the lecture 4 sequence yet. However, I would presume that the code would be... sumDigits = 0 for c in str(1952): sumDigits += int(c) print sumDigits print c ... to calculate the new value of the addition of 1+9+5+2, instead of printing the last digit of this integer (aka 2).
when you have a for statement you don't need to have the _ in for _ in whatever defined you can say for c in something: for frog in something: for uncleFranksUnderpants in something: whatever is after the "for" is automatically interpreted by Python as the elements of the object after "in" (what I called "something")
all the syntax is is for <variable> in <variable>: <code> the second variable needs to be defined, but the first is taken automatically to be the elements of the other variable, be it a list, string, dictionary, or whatever.
Thanks. That clears that up perfectly.
Join our real-time social learning platform and learn together with your friends!