For Loops With Strings
Вставка
- Опубліковано 14 лют 2017
- MIT 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016
View the complete course: ocw.mit.edu/6-0001F16
Instructor: Dr. Ana Bell
This in-class question demonstrates how loops can be used with strings in Python.
License: Creative Commons BY-NC-SA
More information at ocw.mit.edu/terms
More courses at ocw.mit.edu
great lecture, thanks, MIT
thank you ,mit
00:23
Thank you for your lecture. I was confused by this code. I think it is because I am confused about char1 and char2. char2 does not refer to the 2nd character in s2. Is char undefined? Python knows what char refers to? Thanks again for your lecture. It is very helpful.
"char1" and "char2" are just the names of temporary variables that will represent each character in the strings s1 and s2, respectively, because of the for loops.
Another thing that could be potentially confusing is that the print statement says "common letter" but the code actually is comparing every character, including the " " characters, hence "common letter" being printed 7 times for the matches "m", "i", "t", " ", "u", " ", "r"
Are the spaces include?
Where are included? In string every symbol considered an element and it's part of string. For example string "nice day" will have 8 symbols. " nice day " - 10 symbols.
@@funnyh0rr0r31 If you mean if the loop checks if the spaces are equal then yes
@@shokobata Then why is the answer not 10? m = 1, i = 2, t = 1, space = 2, u = 1, space = 2, r = 1
OK I think I get it now, it's because of the break, it only counts the 1st instance of each letter, so it's just m + i + t + space + u + space + r once each
@@thewryreport thanks, i also think the answer is 10 before
do we count the 2 spaces?
Yes, you're absolutely right! It prints "common letter" for "m", "i", "t", " ", "u", " ", and "r", which is quite misleading, because it is checking every CHARACTER in the string, not just letters.
@@alcikelly2496 gotcha thanks
The for loop really should have an else: statement in case the result is false.