# last time loops, for loop
# get computer to print hello many times
for i in range(5):
print("hello")
range(10)
# use loops to compute sums
# sum of numbers between 0 and 9 (including 0 and 9)
run_sum = 0 # this will keep track of the total so far
for i in range(10):
# at every step, add i to run_sum
run_sum = run_sum + i
print(run_sum) # intermediate check
print("The total is:")
print(run_sum)
# CHALLENGE: compute sum of all positive integers n less than 15 such that
# n^3 - 29*n > 18
run_sum = 0 # this will keep track of the total so far
for n in range(1,15):
# at every step, add i to run_sum
if n^3 - 29*n > 18:
run_sum = run_sum + n
print(run_sum) # intermediate print statement
print("The total is:")
print(run_sum)
# print out all odd numbers less than 15
# use the more general remainder operator %
9 % 2 # remainder when we divide 9 by 2
7 % 3 # remainder when divide 7 by 3
10 % 2
# to test whether number n is even/odd
# look at n % 2
# value is 0 if n is even
# and 1 if n is odd
# print out all odd numbers less than 15
for n in range(15):
if n % 2 == 1:
print(n)
# CHALLENGE: find the product of all positive even numbers less than 20
run_prod = 1 # since we are doing a product, start with 1
for n in range(1,20):
if n % 2 == 0:
run_prod = run_prod * n
print(run_prod)
a = 4
a += 5 # Equivalent to a = a + 5
print(a)
# while loop
# print hello many times using while loop
n=0
while n<5:
print("hello")
print(n)
n += 1 # increase n by 1
# WARNING: easy to get into infinite loops with while,
# if you forget to change n
n=0
while n<5:
print("hello")
print(n)
# n += 1 # increase n by 1
# Functions
# Built-in functions
print("hello")
factor(18) # sage function
# Define a function say_hello using def keyword
def say_hello():
print("hello")
print("hello again")
say_hello()
# write a function that tests whether a number is "small"
def is_small(n):
"""Return true if n is less than 100. Otherwise return false."""
# Docstring: is_small? will give this info
if n<100:
return True # this means the value of is_small(n) becomes True in this case
else:
return False
is_small(150) # will be same as 150<100
if is_small(90):
print("90 is small")
# CHALLENGE: make a function that computes sum of 1,...,n-1
def sum_integers(n):
"""Return sum 1,...,n-1"""
run_sum = 0 # variable only exists inside function (called scope)
for i in range(1,n):
run_sum += i
return run_sum
sum_integers(10)
sum_integers(7)
run_sum # this will print the old value that we changed at the beginning of class