Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


#!/usr/bin/python3
count = 1
print('This line comes before the function definition')

def func1():
print('This is an example of a function')

while(count <= 5):
func1()
count = count + 1

print('This is the end of the loop')
func2()
print('Now this is the end of the script')

def func2():
print('This is an example of a misplaced function')

When you run the script1202.py function, you should get an error message:


Click here to view code image


pi@raspberrypi ~ $ python3 script1202.py
This line comes before the function definition
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
Traceback (most recent call last):
File "script1202.py", line 14, in <module>
func2()
NameError: name 'func2' is not defined
pi@raspberrypi ~ $

The first function, func1(), is defined after a couple of statements in the script, which is perfectly
fine. When the func1() function is used in the script, Python knows where to find it.


However, the script attempts to use the func2() function before it is defined. Because the
func2() function isn’t defined yet when the script reaches the place where you use it, you get an
error message.


You also need to be careful about function names. Each function name must be unique, or you have
problems. If you redefine a function, the new definition overrides the original function definition,
without producing any error messages. Take a look at the script1203.py script in Listing 12.3
for an example of this.


LISTING 12.3 Trying to Redefine a Function


Click here to view code image


#!/usr/bin/python3
Free download pdf