-->

def Statements with Parameters - Function [Python]

def Statements with Parameters - Function [Python]
def Statements with Parameters - Function [Python]

When you call the print() or len() function, you pass in values, called arguments in this context, by typing them between the parentheses. You can also define your own functions that accept arguments. Type this example into the file editor and save it as helloFunc2.py:


  1. The definition of the hello() function in this program has a parameter called name
  2. The program execution enters the function, and the variable name is automatically set to 'Alice', which is what gets printed by the print() statement
  3. A parameter is a variable that an argument is stored in when a function is called. The first time the hello() function is called, it’s with the argument 'Alice'
One special thing to note about parameters is that the value stored in a parameter is forgotten when the function returns. For example, if you added print(name) after hello('Bob') in the previous program, the program would give you a NameError because there is no variable named name. This variable was destroyed after the function call hello('Bob') had returned, so print(name) would refer to a name variable that does not exist.

This is similar to how a program’s variables are forgotten when the program terminates. I’ll talk more about why that happens later in the chapter, when I discuss what a function’s local scope is.

Return Values and return Statements

When you call the len() function and pass it an argument such as 'Hello', the function call evaluates to the integer value 5, which is the length of the string you passed it. In general, the value that a function call evaluates to is called the return value of the function.

When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:
  • The return keyword
  • The value or expression that the function should return

When an expression is used with a return statement, the return value is what this expression evaluates to. For example, the following program defines a function that returns a different string depending on what number it is passed as an argument. Type this code into the file editor and save it as magic8Ball.py:

  1. import random
  2. def getAnswer(answerNumber):
  3. if answerNumber == 1:
  4. return 'It is certain'
  5. elif answerNumber == 2:
  6. return 'It is decidedly so'
  7. elif answerNumber == 3:
  8. return 'Yes'
  9. elif answerNumber == 4:
  10. return 'Reply hazy try again'
  11. elif answerNumber == 5:
  12. return 'Ask again later'
  13. elif answerNumber == 6:
  14. return 'Concentrate and ask again'
  15. elif answerNumber == 7:
  16. return 'My reply is no'
  17. elif answerNumber == 8:
  18. return 'Outlook not so good'
  19. elif answerNumber == 9:
  20. return 'Very doubtful'
  21. r = random.randint(1, 9)
  22. fortune = getAnswer(r)
  23. print(fortune)

When this program starts, Python first imports the random module 1. Then the getAnswer() function is defined 2. Because the function is being defined (and not called), the execution skips over the code in it. Next, the random.randint() function is called with two arguments, 1 and 9 4. It evaluates to a random integer between 1 and 9 (including 1 and 9 themselves), and this value is stored in a variable named r.

The getAnswer() function is called with r as the argument 5. The program execution moves to the top of the getAnswer() function 3, and the value r is stored in a parameter named answerNumber. Then, depending on this value in answerNumber, the function returns one of many possible string values. The program execution returns to the line at the bottom of the program that originally called getAnswer() 5. The returned string is assigned to a variable named fortune, which then gets passed to a print() call 6 and is printed to the screen.

Note that since you can pass return values as an argument to another function call, you could shorten these three lines:
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
to this single equivalent line:
print(getAnswer(random.randint(1, 9)))
Remember, expressions are composed of values and operators. A function call can be used in an expression because it evaluates to its return value.

The None Value

In Python there is a value called None, which represents the absence of a value. None is the only value of the NoneType data type. (Other programming languages might call this value null, nil, or undefined.) Just like the Boolean True and False values, None must be typed with a capital N.

This value-without-a-value can be helpful when you need to store something that won’t be confused for a real value in a variable. One place where None is used is as the return value of print(). The print() function displays text on the screen, but it doesn’t need to return anything in the same way len() or input() does. But since all function calls need to evaluate to a return value, print() returns None. To see this in action, enter the following into the interactive shell:
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
Behind the scenes, Python adds return None to the end of any function definition with no return statement. This is similar to how a while or for loop implicitly ends with a continue statement. Also, if you use a return statement without a value (that is, just the return keyword by itself), then None is
returned.

Keyword Arguments and print()

Most arguments are identified by their position in the function call. For example, random.randint(1, 10) is different from random.randint(10, 1). The function call random.randint(1, 10) will return a random integer between 1 and 10, because the first argument is the low end of the range and the second argument is the high end (while random.randint(10, 1) causes an error).

However, keyword arguments are identified by the keyword put before them in the function call. Keyword arguments are often used for optional parameters. For example, the print() function has the optional parameters end and sep to specify what should be printed at the end of its arguments
and between its arguments (separating them), respectively.

If you ran the following program:
print('Hello')
print('World')
the output would look like this:
Hello
World
The two strings appear on separate lines because the print() function automatically adds a newline character to the end of the string it is passed. However, you can set the end keyword argument to change this to a different string. For example, if the program were this:
print('Hello', end='')print('World')
the output would look like this:
HelloWorld
The output is printed on a single line because there is no longer a newline printed after 'Hello'. Instead, the blank string is printed. This is useful if you need to disable the newline that gets added to the end of every print() function call.

Similarly, when you pass multiple string values to print(), the function will automatically separate them with a single space. Enter the following into the interactive shell:
>>> print('cats', 'dogs', 'mice')
cats dogs mice
But you could replace the default separating string by passing the sep keyword argument. Enter the following into the interactive shell:
>>> print('cats', 'dogs', 'mice', sep=',')cats,dogs,mice
You can add keyword arguments to the functions you write as well, but first you’ll have to learn about the list and dictionary data types in the next two chapters. For now, just know that some functions have optional keyword arguments that can be specified when the function is called.


0 Response to "def Statements with Parameters - Function [Python]"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel