This lesson is about functions, look at the code below and run it - there are some errors.
- Research what these errors may be and try to solve them, can you make the code run?
- What does float do on line 3?
- In line one change the convertor() to a different name, what else do you need to change to make the program work?
- Now create your own Function.
Student Learning Activites
Sometimes you may create a block of code which is useful, for example converting CM into Inches or pounds into ounces or Kilometres into Miles. You may want to use this code again but don’t want to have to type it out again. If you create a Function you can call that whole block of code by a simple name and use it whenever you want to.
1. Load up the program Problem Function program, it will not yet work, why? Discuss with another student what the errors are, how many can you find? Now correct the code, can you get it to work? What changes did you need to make - check with another student. Input / data can be added to a function using variables, look at the Example 1: letter code, what does it do?: 2. Variables can separate from the function, this means you can use them in several different functions. You can also use or call a function within another function, look at Example 2 letters. Your Turn: Now create your own functions, stuck for ideas? How about a currency converter?, BMI calculator, VAT calculator, area of a triangle, or the number of days you have been alive?
|
How to define a Function (def)
It is easy:
To create a function follow these simple steps, 1. Type def 2. Then the name of the function def name 3. The add brackets and a colon def name(): 4. Then indent the next lines of code and add your block of code def name(): your_name = raw_input(“what is your name? “) print “hello”, your_name Then you call the function by typing the function name in def name(): your_name = raw_input(“what is your name? “) print “hello”, your_name name() |