design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.
use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs
LO: To write functions that perform mathematical operations.
Now is the chance to see why Reeborg's world is a great environment to learn programming! We have seen how to write a function to teach Reeborg how to turn right:
#function to turn right in Reeborg's world def turn_right(): #we define the function and give it a name with no spaces followed by (): turn_left() #the commands in the function are indented turn_left() turn_left() #we remove the indent and call the function by its name turn_right()
Now we can write a simple function to perform an addition - and it follows exactly the same principles!
#function to add two numbers #here we use the print() command* to print out something to the screen def add_numbers(): print(7 + 3) #the commands in the function are indented #you can remove the indent by pressing return/enter twice add_numbers()
You can see the principle is the same, we have defined a function to carry out some commands and then called the function for it to perform those commands.
#function to show multiplication #here we use the print() command* to print out something to the screen def tables_7(): print(7 * 1) print(7 * 2) print(7 * 3) tables_7()
The interpreter is great for trying out ideas, but to write a program that can be edited you will need to create a Python file (ending with .py). To do this you need to go to File/New File in IDLE to create a blank text file.
You can now set the challenge of writing a function that prints out a multiplication table of a given number:
#Year group or class #name #date #Multiplication Tables def tables_7(): print(7 * 1) print(7 * 2) print(7 * 3) print(7 * 4) print(7 * 5) print(7 * 6) print(7 * 7) print(7 * 8) print(7 * 9) print(7 * 10) print(7 * 11) print(7 * 12) tables_7()
Once you have written your program you will need to save it (give it the same name you have given it in the comments section. Once the file is saved you can go to Run/Run Module to run your program.
Remember all of the things you have learnt from debugging in Reeborg to help you get your program running correctly!
* Using the interpretor in IDLE will run commands automatically and print out their results/values to the screen automatically. Once we start using the editor in IDLE then we have to use a command to tell the computer to print out something to the screen, we use the print() command.