This document includes both the 8:45am and 10:15am lectures.
Here’s a short program with one function definition and three function calls.
It’s in this repl: @PhillipConrad/spis2022-focs-0803-2
import math
def factor_limit(my_integer):
''' return highest factor we need to test when checking whether my_integer is prime '''
return int(math.sqrt(my_integer))
print("factor_limit(123)=", factor_limit(123))
print("factor_limit(127)=", factor_limit(127))
print("factor_limit(737)=", factor_limit(737))
Here’s another program that shows a couple of function definitions, and then how we can call functions using a variable, inside a for loop
import math
def factor_limit(my_integer):
''' return highest factor we need to test when checking whether my_integer is prime '''
return int(math.sqrt(my_integer))
def ask_for_number():
symbols = input("Enter a number: ")
number = int(symbols)
return number
print("Please enter lower limit to check")
lower_limit = ask_for_number()
print("Please enter upper limit to check")
upper_limit = ask_for_number()
for i in range(lower_limit, upper_limit + 1):
print("i=", i, "factor_limit(i)=", factor_limit(i))
Here’s the output when I enter 13 and 17. We’ll demonstrate that on this Repl: @PhillipConrad/spis2022-focs-0803-01
Please enter lower limit to check
Enter a number: 13
Please enter upper limit to check
Enter a number: 17
i= 13 factor_limit(i)= 3
i= 14 factor_limit(i)= 3
i= 15 factor_limit(i)= 3
i= 16 factor_limit(i)= 4
i= 17 factor_limit(i)= 4
Let’s talk about for loops for a minute.
There a couple of different kinds in Python; right now, we are going to
look just at the for i in range
kind.
We can also see different ways of using print
here:
https://replit.com/@PhillipConrad/spis2022-focs-3#main.py
print("for i in range(5):")
for i in range(5):
print(i)
print("")
print("for i in range(1,6):")
for i in range(1,6):
print("i=", i)
print("")
print("for i in range(2,7):")
for i in range(2,7):
print("i=", i, sep=", ", end="")
print("")
print("for i in range(3,12,2):")
for i in range(3,12,2):
print("i=", i, sep="; ", end=" ")
This repl shows how we can separate function definitions and function calls into two separate files
For now, while our programs are short, it may not be clear why this is a good idea.
Later on, when our programs get bigger, this will be essential.
@PhillipConrad/spis2022-focs-4
Can we write a function that, given an integer, either: (a) Finds a factor of the integer other than 1, and if so returns that factor. (b) If the integer is prime, just returns that integer itself.
We’ll call it first_factor(n)
I am doing this live (I prepared what problem I would solve, but I didn’t write the code in advance).
I want you to see the entire process.
We worked in this repl; you may like to fork it and try to play with the code yourself: