def func1():
print('This is the first definition of the function name')
func1()
def func1():
print('This is a repeat of the same function name')
func1()
print('This is the end of the script')
When you run the script1203.py script, you should get this output:
Click here to view code image
pi@raspberrypi ~ $ python3 script1203.py
This is the first definition of the function name
This is a repeat of the same function name
This is the end of the script
pi@raspberrypi ~ $
The original definition of the func1() function works fine, but after the second definition of the
func1() function, any subsequent uses of the function use the second definition instead of the first
one.
Returning a Value
So far the functions that you’ve used have just output a string and ended. Python uses the return
statement to exit a function with a specific value. With the return statement, you can specify a
value that the function returns back to the main program after it finishes, and then it uses that value
back in the main program.
The return statement must be the last statement in the function definition, as shown here:
def func2():
statement1
statement2
return value
In the main program, you can assign the value returned by the function to a variable and then use it in
your code. Listing 12.4 shows the script1204.py script, which demonstrates how to do this.
LISTING 12.4 Returning a Value from a Function
Click here to view code image
#!/usr/bin/python3
def dbl():
value = int(input('Enter a value: '))
print('doubling the value')
result = value * 2
return result
x = dbl()
print('The new value is ', x)