Module 0 · Functions, Variables · Lesson 5 of 5

Writing your own functions

You can define your own functions with def. Everything indented under the def line is the function's body.

def hello(to="world"):
    print("hello,", to)

hello()          # hello, world
hello("Sam")     # hello, Sam

to is a parameter with a default value, just like print's sep.

print vs return. print shows something on screen. return hands a value back to whoever called the function, so they can store it or use it in more math. A function with no return gives back None.

def square(n):
    return n * n

print(square(3) + 1)   # 10

The main pattern. A common habit is to put the program's main logic in a function called main and call it on the last line. That way every helper function is defined before main runs, in whatever order you wrote them.

Scope: a variable created inside a function only exists inside it. To share a value, pass it in as an argument or return it.

Try it

Edit freely · Ctrl+Enter runs

Quick check0 of 3 right

What does a function without a return statement give back?

Why call main() on the last line instead of the first?

def f(n): return n * 2 What is f(f(3))?

Practice0 of 2 solved

1. Emoji converterTo do

Write a function convert(text) that returns the text with every :) turned into 🙂 and every :( turned into 🙁. Then main reads input and prints the converted text.

InputOutput
Hello :)Hello 🙂
Goodbye :(Goodbye 🙁

2. Tip calculatorTo do

main is written for you. Finish the two helper functions: dollars_to_float("$50.00") should return 50.0, and percent_to_float("15%") should return 0.15.

InputOutput
$50.00 ⏎ 15%Leave $7.50
$100.00 ⏎ 18%Leave $18.00