Nested for loops means having a loop inside another loop. The inner loop starts and finishes once for every iteration of the outer loop.
For each item, write code that produces the output shown.
1) Count from 1 to 4 three times. Print “Take it from the top” at the start of each count.
Output:
Take it from the top 1 2 3 4 Take it from the top 1 2 3 4 Take it from the top 1 2 3 4
2) Using two stepper variables x and y, produce the following output with 3 or 4 lines of code:
Output:
x: 0 y: 0 x: 1 y: 0 x: 2 y: 0 x: 0 y: 1 x: 1 y: 1 x: 2 y: 1 x: 0 y: 2 x: 1 y: 2 x: 2 y: 2 x: 0 y: 3 x: 1 y: 3 x: 2 y: 3
3) Starting with a list of words, print every letter of every word on a separate line. (requires 4 lines including the starter code)
Starter code:
words = ['potato', 'sand', 'kite', 'piano']
Output:
p o t a t o s a n d k i t e p i a n o
4) Create a list of random “words” made up a random letters. (see the python random page). It should create different words every time. The words don’t have to be real words – just a random string of letters.
5) Starting with a list of words, create a new list of words with all of the vowels removed from the original words. Create an outer loop that iterates through each word, and create an inner loop that iterates through each character of a word. The inner loop will build a new string to make a vowel-less word. The outer loop will build a new list of the new words.
Starter Code:
wordlist = ['hard','easy','yellow','pink'] new_list = [] for word in wordlist: new_word = '' #write code print(new_list)
Output:
['hrd', 'sy', 'yllw', 'pnk']
6) The following starter code shows how you can filter out the offensive word “can’t” and replace it with “find it difficult to.” Use the starter code that works for a single statement, and develop code that can modify an entire list of statements containing “can’t.” Create a new list of statements and print them all out.
Starter Code: (modifies only one statement)
lie = "I can't do my work." words = lie.split() for i in range(len(words)): if words[i] == "can't": words[i] = "find it difficult to" new_sentence = " ".join(words) print(new_sentence)
More Starter Code:
lies = ["I can't learn to program.", "I can't figure out my homework.", "I can't meet new people.", "I can't try new foods.", "I can't change my habits.", "I want to try, but I can't do it."]
Output:
I find it difficult to learn to program. I find it difficult to figure out my homework. I find it difficult to meet new people. I find it difficult to try new foods. I find it difficult to change my habits. I want to try, but I find it difficult to do it.