Unit converter
Write your own functions, and use them in a converter that changes centimetres to inches, kilograms to pounds, and Celsius to Fahrenheit.
Start here: open pygwide. On the home page, choose Tutorials, then Python Toolkit, then Lesson 2: Unit converter.
This lesson takes about an hour. The extensions take about 30 minutes more.
What you will learn
- How to make your own function with
def. - How to give a function something to work with, called a parameter.
- How a function gives back an answer with
return. - How to use numbers with a decimal point, with
float()andround().
What you need from before
input()and f-strings, from Python Basics, Lesson 2.if,elifandelse, from Python Basics, Lesson 3.whileloops, from Python Basics, Lesson 5.
Step 1: Your first function
A function is a set of lines with a name. You write it once, then use it whenever you like by calling it. Type this and run it:
def show_menu():
print("1. Centimetres to inches")
print("2. Kilograms to pounds")
print("3. Celsius to Fahrenheit")
print("4. Quit")
show_menu()
show_menu()
def makes the function. Its lines are indented, like an if. Nothing
happens until you call it with show_menu(), so the menu prints twice.
In Scratch
A function is like a block you make in My Blocks. def is like the
pink define hat block.
Step 2: Give it something to work with
A function can take parameters, which are like variables that you fill in when you call it:
def greet(name):
print(f"Hello, {name}!")
greet("Sam")
greet("Priya")
Step 3: Give back an answer
return gives an answer back to the line that called the function:
def double(number):
return number * 2
answer = double(21)
print(answer)
Step 4: The converters
Now replace your code with three converters and the menu. float() is like
int(), but it lets you type numbers with a decimal point, such as 12.5:
def centimetres_to_inches(centimetres):
return centimetres / 2.54
def kilograms_to_pounds(kilograms):
return kilograms * 2.205
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def show_menu():
print()
print("1. Centimetres to inches")
print("2. Kilograms to pounds")
print("3. Celsius to Fahrenheit")
print("4. Quit")
Step 5: The menu loop
After your functions, add a loop that shows the menu until you choose 4.
round(number, 1) rounds a number to 1 decimal place, so you get 11.8
instead of 11.811023622047244:
choice = ""
while choice != "4":
show_menu()
choice = input("Choose 1, 2, 3 or 4: ")
if choice == "1":
amount = float(input("How many centimetres? "))
print(f"That is {round(centimetres_to_inches(amount), 1)} inches.")
elif choice != "4":
print("Please choose 1, 2, 3 or 4.")
print("Goodbye!")
Run it, then add elif parts for choices 2 and 3, before the last
elif.
Check your code
# Unit converter
def centimetres_to_inches(centimetres):
return centimetres / 2.54
def kilograms_to_pounds(kilograms):
return kilograms * 2.205
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def show_menu():
print()
print("1. Centimetres to inches")
print("2. Kilograms to pounds")
print("3. Celsius to Fahrenheit")
print("4. Quit")
choice = ""
while choice != "4":
show_menu()
choice = input("Choose 1, 2, 3 or 4: ")
if choice == "1":
amount = float(input("How many centimetres? "))
print(f"That is {round(centimetres_to_inches(amount), 1)} inches.")
elif choice == "2":
amount = float(input("How many kilograms? "))
print(f"That is {round(kilograms_to_pounds(amount), 1)} pounds.")
elif choice == "3":
amount = float(input("How many degrees Celsius? "))
print(f"That is {round(celsius_to_fahrenheit(amount), 1)} degrees Fahrenheit.")
elif choice != "4":
print("Please choose 1, 2, 3 or 4.")
print("Goodbye!")
Extensions
A calculator
Make a calculator with a function for each sum: add(), subtract(),
multiply() and divide(). Each takes two numbers and returns the answer.
in checks whether something is in a list, so
choice in ["+", "-", "*", "/"] is true for any of the four signs.
What should happen if the second number is 0? Try dividing by 0 in Python to find out!
One way to do it
# Calculator
def add(first, second):
return first + second
def subtract(first, second):
return first - second
def multiply(first, second):
return first * second
def divide(first, second):
return first / second
def ask_number(question):
return float(input(question))
choice = ""
while choice != "q":
print()
print("+ add - subtract * multiply / divide q quit")
choice = input("Choose: ")
if choice in ["+", "-", "*", "/"]:
first = ask_number("First number: ")
second = ask_number("Second number: ")
if choice == "+":
print(f"The answer is {add(first, second)}")
elif choice == "-":
print(f"The answer is {subtract(first, second)}")
elif choice == "*":
print(f"The answer is {multiply(first, second)}")
elif second == 0:
print("You can't divide by zero!")
else:
print(f"The answer is {divide(first, second)}")
print("Goodbye!")
More converters
Add more choices to the converter, such as metres to feet (1 metre is about 3.28 feet), or the other way round, inches to centimetres.
Extra bits
Did you know?
An inch is exactly 2.54 centimetres. Your thumb is about an inch wide, which is where the inch came from.
Export your project
pygwide keeps your work in this web browser, but club computers can forget it. Press ⇩ Export to save your project as a zip file. Keep it somewhere safe, such as a USB stick or your school drive.
Next time, choose ⇪ Import a project on the home page to carry on with it.