For Loop challenges!!¶
Write a for loop so that every item in the list is printed.¶
In [2]:
Ihatejesus=["koala", "cat", "fox", "panda", "chipmunk", "sloth", "penguin", "dolphin"]
#Type your answer here.
print (Ihatejesus)
['koala', 'cat', 'fox', 'panda', 'chipmunk', 'sloth', 'penguin', 'dolphin']
Write a for loop which print "Hello!, " plus each name in the list. i.e.: "Hello!, Sam"¶
In [9]:
item =["Sam", "Lisa", "Micha", "Dave", "Wyatt", "Emma", "Sage"]
#Type your code here.
for item in item:
print ("Hello, {}!".format(item))
Hello, Sam! Hello, Lisa! Hello, Micha! Hello, Dave! Hello, Wyatt! Hello, Emma! Hello, Sage!
In [ ]:
# Write a for loop that iterates through a string and prints every letter.
In [10]:
str="Antarctica"
#Type your code here.
for letter in str:
print(letter)
A n t a r c t i c a
Type a code inside the for loop so that counter variable named c is increased by one each time loop iterates. Can you guess how many times it will add 1?.¶
In [22]:
str="Civilization"
#Type your answer here.
c=0
for letterc in str:
c +=1
print(c)
1 2 3 4 5 6 7 8 9 10 11 12
Using a for loop and .append() method append each item with a Dr. prefix to the lst.¶
Info on the .append() method can be found at https://www.w3schools.com/python/ref_list_append.asp¶
In [23]:
lst1=["Phil", "Oz", "Seuss", "Dre"]
lst2=[]
#Type your answer here.
for name in lst1:
lst2.append("Dr. {}".format(name))
print(lst2)
['Dr. Phil', 'Dr. Oz', 'Dr. Seuss', 'Dr. Dre']
Write a for loop which appends the square of each number to the new list.¶
In [25]:
lst1=[3, 7, 6, 8, 9, 11, 15, 25]
lst2=[]
#Type your answer here.
for number in lst1:
lst2.append(number ** 2)
print(lst1)
print(lst2)
[3, 7, 6, 8, 9, 11, 15, 25] [9, 49, 36, 64, 81, 121, 225, 625]
Write a for loop using an if statement, that appends each number to the new list if it's positive.¶
In [35]:
lst1=[111, 32, -9, -45, -17, 9, 85, -10, 0]
lst2=[]
lst3=[]
#Type your answer here.
for number in lst1:
if number >= 0:
lst2.append(number)
else:
lst3.append(number)
print(lst2)
print(lst3)
print(lst1)
[111, 32, 9, 85, 0] [-9, -45, -17, -10] [111, 32, -9, -45, -17, 9, 85, -10, 0]
Write a for loop which appends the type of each element in the first list to the second list.¶
In [45]:
lst1=[3.14, 66, "Teddy Bear", True, ["hello", "goodbye"], {"goodbye", "hello"}]
lst2=[]
#Type your answer here.
for item in lst1:
itemtype = type(item)
lst2.append(item)
lst2.append(itemtype)
print(lst2)
[3.14, <class 'float'>, 66, <class 'int'>, 'Teddy Bear', <class 'str'>, True, <class 'bool'>, ['hello', 'goodbye'], <class 'list'>, {'hello', 'goodbye'}, <class 'set'>]
In [ ]: