acm init()- day 4
TRANSCRIPT
From last time• Loops!
• While loop- don't make them infinite!
• While-else
• For loops
• For-else loops exist as well
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
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 ':'!
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.
Function with arguments
This function computes the area of a rectangle. It takes two arguments: the lengths of the sides.
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!
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.
Importing
I'm lazy. I don't like constantly writing my own functions. Python has some built in for us! We have to import them though.
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.
The math librarymath has a lot of functions you can use. For example:
exponent log sin pi
factorial ...
https://docs.python.org/2/library/math.html
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
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.
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.
WarningBe 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()
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.