Python, lesson 6
As programs grow, you'll notice the same few lines showing up in several places. A
function gives those lines a name so you can run them whenever you like. Functions also
make code easier to read: to_fahrenheit(20) says what is happening far better than the
formula it hides.
def starts the definition. name is a parameter: a variable that gets its value from
whatever you pass in the call. The value you pass, "Mia", is the argument. The function
body doesn't run when Python reads the def; it runs each time you call the function.
Printing shows something to the user. Returning hands a value back to the code that called the function, so it can store it, combine it or print it later.
return ends the function immediately. A function with no (or a bare )
gives back . A frequent beginner bug is printing inside a function and then wondering
why the caller got .
2 exercises to try what you just read.
returnreturnNoneNoneA parameter can have a default, used when the caller leaves it out:
Parameters with defaults must come after those without. Defaults are created once, when the
def runs, so never use a mutable value like [] as a default. Use None and create the
list inside the function instead.
You can annotate parameters and the return value with types, and describe the function in a docstring, a string on the first line of the body:
Python doesn't enforce hints at run time. They are documentation for people and for tools like editors and type checkers.
Variables created inside a function are local: they exist only while that call runs and can't be seen from outside. Each call gets a fresh set.
A function can read variables defined at the top level of the file (globals), but if it
assigns to a name, that name becomes local. The global keyword changes this, but passing
values in as arguments and returning results is almost always clearer.
A good habit is to keep functions small and focused: one function does one job, has a name that is a verb, and returns its result rather than printing it. Then the top level of your file reads like a short story of what the program does.
Finish the function to_fahrenheit(celsius) so it returns the temperature in °F using
F = C × 9 / 5 + 32. The rest of the program is written for you: it reads one Celsius value
per line until the input ends and prints each result with one decimal.
Sample input:
Sample output:
Write postage(weight, express=False). It returns the cost of sending a parcel: 4.00 plus
1.50 per kilogram. If express is true, the whole cost doubles.
Each input line holds a weight, optionally followed by the word express. The starter
already reads the lines and calls your function; print each cost with two decimals.
Sample input:
Sample output:
def greet(name):
print(f"Hello, {name}!")
greet("Mia")
greet("Sam")def area(width, height):
return width * height
room = area(4, 3) + area(2, 2)
print(room) # 16def price_with_tax(amount, rate=0.2):
return amount * (1 + rate)
price_with_tax(10) # uses rate=0.2
price_with_tax(10, 0.05) # positional
price_with_tax(10, rate=0) # keyword argument: clear about what 0 meansdef average(total: float, count: int) -> float:
"""Return the mean, or 0.0 when there is nothing to average."""
if count == 0:
return 0.0
return total / countdef add_bonus(score):
bonus = 10 # local
return score + bonus
print(add_bonus(5)) # 15
# print(bonus) # NameError: bonus only lived inside the function0
100
-4032.0
212.0
-40.02
2 express
07.00
14.00
4.00