Parameters and Arguments

So far we’ve seen functions that require argument or arguments for their execution and functions that work without arguments. For example, when you call a trigonometric function such as sin or cos from math library then you type:
>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi)
-1.0

In empty brackets you need to pass a number as an argument. Some function take more than one argument
>>> math.pow(2,2)
4.0
This function takes two arguments the base and exponent. Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:
def print_twice(Tom):
 print Tom
 print Tom
a = 4
print_twice(a)
a = “This is a string” 
print_twice(a)
4
4
This is a string
This is a string
Print_twice function assigns the argument to a parameter named Tom. When the function is called, it prints the value of the parameter (whatever it is) twice. The function works with any value that can be printed.
Same rules of composition that apply to built-in functions also apply to user defined functions, so we can use any kind of expression as an argument for function print_twice:
a = 'String ' * 16
print_twice(a)
String String String String String String String String String String String String String String String String
String String String String String String String String String String String String String String String String
The argument is evaluated before the function is called, so in the examples the expressions ‘Spam ‘ * 16 are only evaluated once. 

Nema komentara:

Objavi komentar