What is the function
Functions like Lego different shapes, can play our own imagination to be assembled using.
Defined functions need to achieve with the def keyword.
Let's look at an example:
DEF Demo (): Print ( " Hello everyone, I am a function " ) Print ( " I said he was excited " ) Demo ()
Note: At the time of writing after the function must be to pay attention to a small parenthesis, defined functions use def, finally, make the call.
Function parameters
Examples of parameters that make it possible to personalize the function, with this function parameter becomes a variable.
Look instance:
def Demo(num,num2): result = num + num2 print(result) Demo(1,2)
Note: If you want to use multiple parameters (at English) "," can be achieved.
Function's return value
The return value is to use the function to return some of the data or the result for us.
Example:
def Dome(num,num2): return num+num2 print(Dome(1,2))
Note: All functions have a default value returns under most cases, result in a return to return to function without using print Print
Local and global variables
Local variables
Defined in the function parameters are called local variables inside
Example:
DEF Demo (One, TOW): the Result = One * TOW return the Result NUM = float (the INPUT ( "Please enter a price:")) num2 = float (the INPUT ( "How many fold playing:")) A = Demo (NUM, num2 ) Print ( "discounted price:% S"% a) Print ( "Print where the value of the local variable result:% s"% result)
When performing code error line 8, because the result is a local variable, its scope is only effect this demo function inside,
A demo outside this range can not output the result, result can only take effect in the local inside.
Global Variables
In the beginning of the program defined variable called global variables
Example:
DEF Demo (One, TOW): the Result = One * TOW Print ( "NUM value print global variables:% S"% NUM) return the Result NUM = float (the INPUT ( "Please enter a price:")) num2 = float (the INPUT ( "how to play off:")) a = Demo (NUM, num2) Print ( "discounted price:% s"% a)
Note: python where you can go to access the global variables in the function but not to modify global variables,
Try to modify the global variable in a function, python will automatically create a new local variable to replace.
Example:
1 DEF Demo (One, TOW): 2 Result = One * TOW . 3 num = 50 . 4 Print ( " after a modified num value:% S " % num) . 5 return Result . 6 num = a float (INPUT ( " Please enter a price : " )) . 7 num2 = a float (INPUT ( " hit number off: " )) . 8 a = Demo (num, num2) . 9 Print ( " value of the num after 2 modifications:% S " % num) 10 Print ( " price after discount:% s" % a)