3.5. Solutions to exercises#
Exercise 3.1
if 1:
print('The expression is true')
if 103.51:
print('The expression is true')
if -1:
print('The expression is true')
a = True
if a:
print('The expression is true')
b = -73.445
if b:
print('The expression is true')
Exercise 3.2
if 5 < 5.1:
print('The expression is true')
if 5 <= 5:
print('The expression is true')
if 5.1 > 5.1:
print('The expression is true')
if 5.1 >= 5.1:
print('The expression is true')
# "!=" is "not-equals"
if 5 != 5.1:
print('The expression is true')
Exercise 3.3 (a)
if 5 < 6 and 10 <= 9:
print("i don't think this is true")
(b)
if not False or True:
print("it is true?")
else:
print("it wasn't true?")
Exercise 3.4
def check_number(a):
if a <= 5:
print(a, "is less than or equal to 5")
elif a < 10:
# note we don't need to test if it's greater than 5 since the first if already took
# care of that for us
print(a, "is between 5 and 10")
else:
print(a, "is greater than or equal to 10")
# Testing your function
check_number(1)
check_number(5)
check_number(7)
check_number(10)
check_number(15)
Exercise 3.5
def factorial(a):
# f = our factorial result
f = 1
i = 2
while(i<=a):
f *= i
i += 1
return f
print(factorial(4))
print(factorial(2))
Exercise 3.6
# Your code here
s = 0
for i in range(11):
s += np.sin(i)**2
print("Sum is", s)
Exercise 3.7
s = 0
# Note the range should end at 101!
# It should also start at 1: range(101) will also execute
# the loop with i=0 (which won't matter here...)
for i in range(1,101):
s += i
print(s)
Exercise 3.8
# Solution
maxnum=1e6
i=0
while i <= maxnum:
if i*(i-10)==257024:
break
i+=1
print(i)
Exercise 3.9
def leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
return False
return True
return False
Exercise 3.10
## Solution
import numpy as np
y = np.array([2, 2, 3, 4, 5, 4, 3, 8, 6, 4])
for i in range(1, len(y)-1):
if y[i-1] < y[i] and y[i+1] < y[i]:
print('index:', i, '\t value:', y[i])
Exercise 3.11
password = 'practicum123'
tries = 0
from time import sleep
while True:
input_pw = input('What is the password?')
if input_pw == password:
break
if (tries+1)%3==0:
sleep(60+tries**3)
tries += 1