13. Quiz: For Loops
Quiz: Create Usernames
Write a for
loop that iterates over the names
list to create a usernames
list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for
loop over the list:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
should create the list:
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]
HINT: Use the .replace()
method to replace the spaces with underscores. Check out how to use this method in this Stack Overflow answer.
Start Quiz:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
# write your for loop here
print(usernames)
Why range
?
SOLUTION:
The printed output for the `names` list will look exactly like it did in the first lineQuiz: Modify Usernames with Range
Write a for
loop that uses range()
to iterate over the positions in usernames
to modify the list. Like you did in the previous quiz, change each name to be lowercase and replace spaces with underscores. After running your loop, this list
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
should change to this:
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]
Start Quiz:
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
print(usernames)
Quiz: Tag Counter
Write a for
loop that iterates over a list of strings, tokens
, and counts how many of them are XML tags. XML is a data language similar to HTML. You can tell if a string is an XML tag if it begins with a left angle bracket "<" and ends with a right angle bracket ">". Keep track of the number of tags using the variable count
.
You can assume that the list of strings will not contain empty strings.
Start Quiz:
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
# write your for loop here
print(count)
Quiz: Create an HTML List
Write some code, including a for
loop, that iterates over a list of strings and creates a single string, html_str
, which is an HTML list. For example, if the list is items = ['first string', 'second string']
, printing html_str
should output:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
That is, the string's first line should be the opening tag <ul>
. Following that is one line per element in the source list, surrounded by <li>
and </li>
tags. The final line of the string should be the closing tag </ul>
.
Start Quiz:
items = ['first string', 'second string']
html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, it does
# the characters that are after it in html_str are on the next line
# write your code here
print(html_str)