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.
| Input | Output |
|---|---|
| Hello :) | Hello 🙂 |
| Goodbye :( | Goodbye 🙁 |
Module 0 · Functions, Variables · Lesson 5 of 5
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.
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))?
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.
| Input | Output |
|---|---|
| Hello :) | Hello 🙂 |
| Goodbye :( | Goodbye 🙁 |
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.
| Input | Output |
|---|---|
| $50.00 ⏎ 15% | Leave $7.50 |
| $100.00 ⏎ 18% | Leave $18.00 |