2. From last time
• Loops!
• While loop- don't make them infinite!
• While-else
• For loops
• For-else loops exist as well
3. Functions
• A function is a reusable section of code written to
perform a specific task in a program.
• Why use functions?
• If there is a mistake in your program it is much easier
to debug if everything is separated out
• If you need to do the same thing over and over again
a function can reduce repetition
7. How do we write a function?
A function has two parts: a name and a body.
def function_name(optional args):
code you want to run
Don't forget the ':'!
9. How do we use a function?
Calling a function is easy! All you have to do is type the
function's name. For example, if we wanted a function that tells
us "Hi," we would do this:
The () are where you can put optional arguments.
10. Function with arguments
This function computes the area of a rectangle. It takes two
arguments: the lengths of the sides.
13. New challenge
Using the same multiply function, modify the program so it also
squares the product of the two numbers.
!
For example, if the input is (2,3) the result should be 36.
!
You cannot modify the multiply function!
15. Try this!
Write a by_three function that takes a single integer parameter,
num, and returns True if that number is evenly divisible by
three and False if not. Print out a statement with your results.
19. Fix it by importing a math
library
First tell Python we want to use the math library. Then
whenever you use a function from that library put 'math' in front
of it to access it!
This works.
20. The math library
math has a lot of functions you can use. For example:
exponent
log
sin
pi
factorial
...
https://docs.python.org/2/library/math.html
21. Let's be even lazier!
Typing math.function() constantly is annoying. If we only want
to use one function from a module, there is a shortcut!
from module import function
22. Import part 2
Typing 'from math import sqrt' allows us to use the sqrt
function without constantly typing math. We can only use the
sqrt function though.
23. Super lazy!
Is there a way to import every function from a module? Yep!
from module import *
Now we can use everything without having to type the module
name in front.
24. Warning
Be careful about universal imports. Some modules have a lot
of functions in them, so there is a risk you will try to define your
own function of the same name. This will cause issues.
!
Stick with importing individual functions or using
module.function()
25. Built-in functions
Python has some built in functions that we can use without
importing anything. We've seen a few already with strings: len,
lower, and upper.
26. max()
If you give max a list of numbers it will return the maximum
value.
27. min()
If you give min a list of numbers it will return the minimum
value.