comp 171: functions, for loops and range john barr section 03 slides by toby dragon
TRANSCRIPT
COMP 171:Functions, for loops and rangeJohn Barr
Section 03
Slides by Toby Dragon
What is a function?
a block of code that we can call with a single name. "Black Box"
defined in order to provide functionality without dealing with how it works
Some functions are provided to you: input (), print ()
Some functions you have written:drawRect(length, width)
Why functions?
break code into smaller, functional pieces testing parts before trying to solve everythingMake pieces that can be reused for multiple
purposes
simplify (abstract) to make your program easier to understand and to use
Functions: defining the "Black Box"
def drawInitials ():
Tell p
ython w
e're
defining a fu
nction
"Name" t
hat we decid
e
place fo
r parameters
(empty if n
one)
tells pyth
on that th
e functi
on
is sta
rting, e
veryt
hing indented
after t
his will
be part of th
e functi
on
Parameters
def drawInitials ():
def drawSquare (size):
def drawRect (length, width):
No parameters
One parameter
Two parameters
Parameters
Parameters answer questions the function has.e.g., drawRect needs to know the length and
width of the rectangle you want drawn
Use parameters only when necessary!
Practice
Write a function that takes the temperature in Fahrenheit and prints the temperature in Celsius.
To calculate Celsius from Fahrenheit: subtract 32 multiply by 5/9
Practice
Write a function that takes the temperature in Fahrenheit and prints the temperature in Celsius.
To calculate Celsius from Fahrenheit: subtract 32 multiply by 5/9
Functions: using the "Black Box"
when we use a function, we say we are calling the function.
Always end in parentheses! Otherwise, python treats it as a variable
Between parentheses you give values to the parameters
Calling functions and sending Parameters drawInitials ()
drawSquare (100)
sides=100 ends = 200 drawInitials (sides, ends)
the for loop
for num in range(0, 10, 1):
indented code below it will happen multiple times, each with num = a number from the range.
varia
ble you cr
eate
range functi
on
Repetition: the range function
range (10) – give each number,
starting at 0 to less than 10
range (3, 10) – give each number,
starting at 3 to less than 10
range (2, 20, 2) – give each number
starting at 2, to less than 20, and count by 2
name of the
range functi
on
Parameter(s)
Repetition: range practice
[0, 1, 2, 3, ..., 19]
[2, 4, 6, ..., 46, 48]
[50, 48, ..., 0]
Repetition: for loop practice
Write a for loop that prints:3
6
9
…
18
for loop practice
Write a program to print the Celsius equivalent of every 10 degrees Fahrenheit between 0 and 100.
Use your function from earlier!