Loops and Functions Flashcards
Write a for loop that prints out the squares of the numbers 1 through 10.
for i in range(1, 11):
print(i ** 2)
Write a very basic function that calculates the squarte of a number
def square_number(x):
return x**2
Loop through the letters in the word “banana”:
for x in “banana”:
print(x)
Exit the loop when x is “banana”:
fruits = [“apple”, “banana”, “cherry”]
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
if x == “banana”:
break
- returns “apple” and “banana”
Exit the loop when x is “banana”, but this time the break comes before the print:
fruits = [“apple”, “banana”, “cherry”]
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
if x == “banana”:
break
print(x)
-returns just “apple”
Do not print banana:
fruits = [“apple”, “banana”, “cherry”]
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
if x == “banana”:
continue
print(x)
what does range() do?
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(6):
print(x)
Is range(6) the values of 0 to 6 or 0 to 5?
0-5
for x in range():
print(x)
convert to make the loop start at 2 and end at 5
for x in range(2, 6):
print(x)
for x in range():
print(x)
convert to make loop start at 2, end at 30, but loop in increments of 3
for x in range(2, 30, 3):
print(x)
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print(“Finally finished!”)
for x in range(6):
if x == 3: break
print(x)
else:
print(“Finally finished!”)
is the else block executed?
If the loop breaks, the else block is not executed.
What’s a nested loop?
A nested loop is a loop inside a loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
Print each adjective for every fruit:
adj = [“red”, “big”, “tasty”]
fruits = [“apple”, “banana”, “cherry”]
for x in adj:
for y in fruits:
print(x, y)
Define a function (my_function) that prints the first name from this list + the last name, Refsnes:
Emily, Tobias, Linus
def my_function(fname):
print(fname + “ Refsnes”)
my_function(“Emil”)
my_function(“Tobias”)
my_function(“Linus”)