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

(singke) #1
>>>

If you don’t provide any arguments, or if you provide the incorrect number of arguments, you get an
error message from Python, like this:


Click here to view code image


>>> total = addem()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
total = addem()
TypeError: addem() missing 2 required positional arguments: 'a' and 'b'
>>> total = addem(10, 20, 30)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
total = addem(10, 20, 30)
TypeError: addem() takes 2 positional arguments but 3 were given
>>>

If you pass string values as arguments, it’s important to remember to use quotes around the values, as
shown here:


Click here to view code image


>>> def greeting(name):
print('Welcome', name)

>>> greeting('Rich')
Welcome Rich
>>>

If you don’t place the quotes around the string value, Python thinks you’re trying to pass a variable, as
shown in this example:


Click here to view code image


>>> greeting(Barbara)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
greeting(Barbara)
NameError: name 'Barbara' is not defined
>>>

This brings up a good point: You can use variables as arguments when calling a function, as shown
here:


>>> x = 100
>>> y = 200
>>> total = addem(x, y)
>>> print(total)
300
>>>

Inside the addem() function, Python retrieves the value stored in the x variable in the main program
and stores it in the a variable inside the function. Likewise, Python retrieves the value stored in the y
variable in the main program and stores it in the b variable inside the function.


Watch Out!: Positional Parameters
Free download pdf