# last time: for loops
# get computer to print hello multiple times
for n in range(5):
print("hello")
range(5)
range(1,5) # can give range a starting point for list
# sum positive integers 1,...,9
run_sum = 0
for n in range(1,5):
run_sum = run_sum + n
print("n: ", n) # optional
print("run_sum: ", run_sum) # optional
print(run_sum)
# CHALLENGE: compute sum of all positive integers n less than 15 such that
# n^3 - 29*n > 18
run_sum = 0
for n in range(1,15):
if n^3 - 29*n > 18:
run_sum += n # shorthand for run_sum = run_sum + n
#print(run_sum)
print(run_sum)
# Goal: Print out all odd positive integers less than 15
# To test whether n is odd/even, use the remainder operator %
7 % 2 # remainder when 7 is divided by 2
14 % 5 # remainder when 14 is divided by 5
# n % 2 is 0 if n even
# is 1 if n odd
10 % 2
# Print out all odd positive integers less than 15
for n in range(1,15):
if n % 2 == 1:
print(n)
# CHALLENGE: find product of all positive even numbers less than 20
# 2*4*6*..*18
run_prod = 1 # for product, start with 1
for n in range(1,10):
if n % 2 == 0:
run_prod = run_prod * n # could use short-hand: run_prod *= run_prod
print(run_prod)
a= 5
a *= 3 # same as a = a*3
print(a)
# while loop
# Use while loop to print out hello many times
n = 0
while n<4:
print("hello")
n += 1
# WARNING: careful about infinite loop
# Below, we forget to increase n, so n<4 is always true
n = 0
while n<4:
print("hello")
# forgot to do n += 1
# Functions
# Bulit-in functions: print("hello"), factor(48)
print("hello") #python function
factor(48) # sage function
# we can define our own functions
def say_hello():
print("hello, welcome to MAT 331")
print("hello again")
say_hello() # calling the function
# write a function that tests whether a number n is "small"
def is_small(n):
"""Returns True if n < 100.78654321. Returns False otherwise."""
# above is Docstring, call view with is_small?
if n < 100.78654321:
return True # the value of is_small(n) will be True
else:
return False # the value of is_small(n) is False
is_small(500) # is_small(n) will be exactly n < 100.78654321
# CHALLENGE: write a function that computes sum of
# 1,...,n-1
def sum_integers(n):
"""Return 1+2+...+(n-1)."""
run_sum = 0 # local variable, only changes it for this function
# scope of variable is limited
for i in range(1,n):
run_sum += i
return run_sum
sum_integers(10) + 77 # value of sum_integers becomes 45
run_sum # this is the old value of run_sum that we changed at beginning of class