Download presentation
Presentation is loading. Please wait.
1
Functions and Procedures
In today’s lesson we will look at: what functions and procedures are the difference between the two when we might want to use one creating functions and procedures in Python
2
Functions and Procedures
Functions and procedures are small sections of code used to perform a specific task. They are used for two reasons: they can be used to avoid repetition of commands within the program careful use of functions and procedures helps to define a logical structure for your program by breaking it down into a number of smaller modules – i.e. they are the building blocks of larger programs
3
Functions and Procedures
Are functions and procedures the same? Not usually. Generally... functions return a value – i.e. they calculate an answer and send it back procedures don’t return a value – they just perform an action However, in some programming languages there are only functions, and procedures are seen as a special case of a function, just as a square is a special type of rectangle
4
When Are Functions Useful?
You’ve probably used a function in a spreadsheet – e.g. =sum() returns the total value of the numbers in the range. We don’t need to write all of the code to do that. Blocks in Scratch are procedures – see how they are to simplify the Simple Spirograph program Functions and procedures can be used where you want to repeat the same action throughout your program without repeating all of the code.
5
Functions in Python Both functions and procedures are defined at the top of your program with the def command. Functions are called using their name, e.g. def double(x): return x*2 print(double(3)) Use the return command to return a value The main program is here
6
Procedures in Python Procedures in Python are really the same, except that they don’t return a value For example def hello(): print(“Hello World”) hello() Note that there is no return value – the procedure just finishes
7
Be Careful With Variables!
You can create and use variables inside a function or procedure, but these are called local variables Local variables: can’t be accessed by any other part of the program have their values reset each time the function or procedure is called Python assumes that all variables in a function or procedure are local – to use a global variable you need to “declare” it at the top, e.g. global score
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.