Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Non-Programmer's Tutorial for Python 2.6/Defining Functions

From Wikibooks, open books for an open world
<Non-Programmer's Tutorial for Python 2.6

Creating Functions

[edit |edit source]

To start off this chapter I am going to give you an example of what you could do but shouldn't (so don't type it in):

a=23b=-23ifa<0:a=-aifb<0:b=-b#Or use the command: elif (if+else)ifa==b:print"The absolute values of",a,"and",b,"are equal"else:print"The absolute values of",a,"and",b,"are different"

with the output being:

The absolute values of 23 and 23 are equal

The program seems a little repetitive. Programmers hate to repeat things -- that's what computers are for, after all! (Note also that finding the absolute value changed the value of the variable, which is why it is printing out 23, and not -23 in the output.) Fortunately Python allows you to create functions to remove duplication. Here is the rewritten example:

defabsolute_value(n):ifn<0:n=-nreturnna=23b=-23ifabsolute_value(a)==absolute_value(b):print"The absolute values of",a,"and",b,"are equal"else:print"The absolute values of",a,"and",b,"are different"

with the output being:

The absolute values of 23 and -23 are equal

The key feature of this program is thedef statement. Thedef keyword(short for "define") starts a function definition. "def" is followed by the name of the function "absolute_value". Next, comes the single function parameter named, "n". A parameter holds a value passed into the function from the program that "calls" the function. Parameters of a function in thedef statement, must be enclosed within a parenthesis. The value that is passed to a function parameter is called an argument. So for now, a parameter and argument points to the same thing. The block of indented statements after the ":" are then executed whenever the function is used. The statements within the function continue to be run until either the indented statements end, or a "return" statement is encountered. Thereturn statement returns a value back to the place where the function was called in the calling program.

Notice how the values ofa andb are not changed. Functions can be used to repeat tasks that don't return values. Here are some examples:

defhello():print"Hello"defarea(w,h):returnw*hdefprint_welcome(name):print"Welcome",namehello()hello()print_welcome("Fred")w=4h=5print"width =",w,"height =",h,"area =",area(w,h)

with output being:

HelloHelloWelcome Fredwidth = 4 height = 5 area = 20

That example shows some more stuff that you can do with functions. Notice that you can use one or more parameters, or none at all. Notice also that a function doesn't necessarily need to "return" a value, so areturn statement is optional.

Variables in functions

[edit |edit source]

When eliminating repeated code, you often notice that variables are repeated in the code. In Python, these are dealt with in a special way. So far, all variables we have seen are global variables. Functions work with a special type of variables called local variables. These variables only exist within the function and only while the function is running. When a local variable has the same name as another variable (such as a global variable), the local variable hides the other. Sound confusing? Well, these next examples (which are a bit contrived) should help clear things up.

a=4defprint_func():a=17print"in  print_func a = ",aprint_func()print"a = ",a,"which is global variable assigned prior to the function print_func"

When run, we will receive an output of:

in print_func a = 17a = 4 which is global variable assigned prior to the function print_func

Variable assignments inside a function do not override global variables, they exist only inside the function. Even thougha was assigned a new value inside the function, this newly assigned value exists only within theprint_func function. After the function finishes running and the value of ana variable is printed again, we see the value assigned to the globala variable being printed.

Complex example

[edit |edit source]
a_var=10b_var=15c_var=25defa_func(a_var):print("in a_func a_var = ",a_var)b_var=100+a_vard_var=2*a_varprint("in a_func b_var = ",b_var)print("in a_func d_var = ",d_var)print("in a_func c_var = ",c_var)returnb_var+10c_var=a_func(b_var)print("a_var = ",a_var)print("b_var = ",b_var)print("c_var = ",c_var)print("d_var = ",d_var)

The output is:

 in a_func a_var =  15 in a_func b_var =  115 in a_func d_var =  30 in a_func c_var =  25 a_var =  10 b_var =  15 c_var =  125 d_var =   Traceback (most recent call last):  File "C:\Python24\def2", line 19, in -toplevel-     print "d_var = ", d_var  NameError: name 'd_var' is not defined

In this example the variablesa_var,b_var, andd_var are all local variables when they are inside the functiona_func. After the statementreturn b_var + 10 is run, they all cease to exist. The variablea_var is "automatically" a local variable since it is a parameter named by the function definition. The variablesb_var andd_var are local variables since they appear on the left of an equals sign within the function in the statements:b_var = 100 + a_var andd_var = 2 * a_var.

Inside of the functiona_var has no value assigned to it. When the function is called withc_var = a_func(b_var), 15 is assigned toa_var since at that point in timeb_var is 15, making the call to the functiona_func(15). This ends up setting the value ofa_var to 15 when it is inside ofa_func function.

As you can see, once the function finishes running, the local variablesa_var andb_var that had hidden the global variables of the same name are gone. Then the statementprint "a_var = ", a_var prints the value10 rather than the value15 since the local variable that hid the global variable is gone.

Another thing to notice is theNameError that happens at the end. This appears since the variabled_var no longer exists sincea_func finished. All the local variables are deleted when the functionexits. If you want to get something back from a function, then you will have to usereturn statement within the function.

One last thing to notice is that the value ofc_var remains unchanged insidea_func since it is not a parameter and it never appears on the left of an equals sign inside of the functiona_func. When a global variable is accessed inside a function, the function uses only value of the global variable but it cannot change the value assigned to the global variable outside the function.

Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.

Examples

[edit |edit source]

temperature2.py

# converts temperature to fahrenheit or celsiusdefprint_options():print"Options:"print" 'p' print options"print" 'c' convert from celsius"print" 'f' convert from fahrenheit"print" 'q' quit the program"defcelsius_to_fahrenheit(c_temp):return9.0/5.0*c_temp+32deffahrenheit_to_celsius(f_temp):return(f_temp-32.0)*5.0/9.0choice="p"whilechoice!="q":ifchoice=="c":temp=input("Celsius temperature: ")print"Fahrenheit:",celsius_to_fahrenheit(temp)elifchoice=="f":temp=input("Fahrenheit temperature: ")print"Celsius:",fahrenheit_to_celsius(temp)elifchoice=="p":print_options()choice=raw_input("option: ")

Sample Run:

Options: 'p' print options 'c' convert from celsius 'f' convert from fahrenheit 'q' quit the programoption:cCelsius temperature:30 Fahrenheit: 86.0option:fFahrenheit temperature:60Celsius: 15.5555555556option:q

area2.py

# By Amos Satterleeprintdefhello():print'Hello!'defarea(width,height):returnwidth*heightdefprint_welcome(name):print'Welcome,',namename=raw_input('Your Name: ')hello(),print_welcome(name)printprint'To find the area of a rectangle,'print'enter the width and height below.'printw=input('Width: ')whilew<=0:print'Must be a positive number'w=input('Width: ')h=input('Height: ')whileh<=0:print'Must be a positive number'h=input('Height: ')print'Width =',w,'Height =',h,'so Area =',area(w,h)

Sample Run:

Your Name:JoshHello!Welcome, JoshTo find the area of a rectangle,enter the width and height below.Width:-4Must be a positive numberWidth:4Height:3Width = 4 Height = 3 so Area = 12

Exercises

[edit |edit source]

Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius ** 2). This program should include a menu interface.

Solution

Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius ** 2). This program should include a menu interface.

defsquare(length):returnlength*lengthdefrectangle(width,height):returnwidth*heightdefcircle(radius):return3.14*radius**2defoptions():printprint"Options:"print"s = calculate the area of a square."print"c = calculate the area of a circle."print"r = calculate the area of a rectangle."print"q = quit"printprint"This program will calculate the area of a square, circle or rectangle."choice="x"options()whilechoice!="q":choice=raw_input("Please enter your choice: ")ifchoice=="s":length=input("Length of square: ")print"The area of this square is",square(length)options()elifchoice=="c":radius=input("Radius of the circle: ")print"The area of the circle is",circle(radius)options()elifchoice=="r":width=input("Width of the rectangle: ")height=input("Height of the rectangle: ")print"The area of the rectangle is",rectangle(width,height)options()elifchoice=="q":print"",else:print"Unrecognized option."options()


Previous: DebuggingFront PageNext: Advanced Functions Example
Retrieved from "https://en.wikibooks.org/w/index.php?title=Non-Programmer%27s_Tutorial_for_Python_2.6/Defining_Functions&oldid=3750671"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp