for element in list:
code inside the loop
code outside the loop
Break means "stop the loop, don't do anymore iterations -- even if we weren't done yet"
Continue means "skip the rest of this iteration of the loop and start the next iteration"
for n in [1,2,3,4,5]:
print (n)
print("\U0001F600")
for w in [1,2,3]:
print(w)
print("lol - I do know my numbers")
for i in range(20,41):
if i % 2 == 0:
continue # returns control to the beginning of the loop
if i % 3 == 0:
print(i)
lst = [2,5,34,67,22,45,56]
nbr_even=0
for i in lst:
if i%2 == 0:
x = i%2
nbr_even = nbr_even +1 #nbr_even + = 1
print(nbr_even)
while condition:
code inside the loop
code outside the loop
If the condition is True, run the code in the while loop, and then start back at the beginning of the while loop.
If the condition is False, skip the code in the while loop.
#Find the square root of a given perfect square
x= 16
ans = 0
while ans*ans < x:
print(f"Value of multiplication = {ans*ans}")
print(f" Incrementing loop variable {ans + 1}")
ans += 1 # ans = ans + 1
print (ans)
print("S")
print("SS")
print("SSS")
print("S" * 1)
print("S" * 2)
print("S" * 3)
current_step = 1 # initialize counter
while current_step < 10: # condition
print("clap " * current_step) # body
current_step += 1 # increment counter current_step = current_step + 1
EX: 0, 2, 4, ... 20
i = 0
while i < 21:
if i % 2 == 0:
print(i)
i += 1
EX: 1,3,5, . . . 19
i = 0
while i < 21:
if i % 2 != 0:
print(i)
i += 1
n = 5
i = 0
while i < n:
if i % 2 == 0:
print(i)
i += 1
We decide how many arguments a function has when we define it
def function_name(arg1, arg2):
if arg1 == "":
if arg2 == "":
return None
return arg1+" " +arg2
print(function_name("Hello", "again"))
function_name("Hello", "again") + ", nice to see you"
def even(lst):
nbr_even=0
for i in lst:
if i%2 == 0:
x = i%2
nbr_even = nbr_even +1 #nbr_even + = 1
return nbr_even
even([2,5,34,67,22,45,56,44]) # try and put +1
print(even([2,5,34,67,22,45,56,44])) #try and put +1
# This is an example of a function with two arguments
def sumTwo(x, y):
return x + y
sumTwo(1, 2)
sumTwo(sumTwo(4,5), sumTwo(2,3)) + 5
# You can have functions that call functions
def sumThree(x, y, z):
return x + sumTwo(y, z)
sumThree(1, 2, 3)
# You can have functions that call functions that call functions
def sumFour(a, b, c, d):
return a + sumThree(b, c, d)
sumFour(1, 2, 3, 4)
What happens if there are two return statement in a function?
Now see a function that calls itself!!
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
def factorial2(n):
if n==1:
return 1
return n * factorial(n-1)
print(factorial(5))
print(factorial2(5))
# Definition of factorial: n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
# Also, 1! = 1
# How can you turn this into a recursion?
# Recursive case:
# Base case: 1! = 1
#n! = n * (n - 1)!
For example:
$f(x) = x$
$g(x,y) = x + y$
$h(x,y,z) = x+y+z$