tips for use:
In [1]: num1,oper,num2 = Raw_input (). Split ()
1 + 2
In [2]: Print num1,oper,num2
1 + 2
#表示将用户的输入, assign a value to the variable num1,oper,num2 by a space delimiter
Defining functions
def function name ():
The code block that the function needs to execute
Return function returns a value
Note: If no return is written in the function, the default return returns none
#!/usr/bin/env python# coding:utf-8def myadd (): Num1=input ("Enter first number:") num2=input ("Enter second number:") Print Num1+num2myad D ()
#!/usr/bin/env python# coding:utf-8def myadd (): Num1=input ("Enter first number:") num2=input ("Enter second number:") return Num1+num2pri NT Myadd ()
#这两种方式都是可以的, the second method assigns the result to the return value, and then outputs the return value when the function is called, the same as the first script function.
The second approach is more in line with Python's simplicity and elegance
Calling functions
First, call mode:
Function name ()
Second, transfer parameters:
- Required Parameters : Def myadd (x, y):
Myadd (x, y): #x, Y is a formal parameter, not a real argument, use any letter instead of x+ynum1= () num2= () Myadd (num1,num2) #调用函数, NUM1 and num2 are arguments, passing real NUM1 and num2 data to a function
- Default parameter : Def myadd (x=10,y=10):
#可以看到调用myadd函数结果是20, this is because the default parameter of the Myadd function is two 10, and the result of the addition is naturally 20
- variable parameters : def add (*num):
#!/usr/bin/env python
# Coding:utf-8
def add (*num): #*num can pass multiple values passed into a function as a whole, and finally num is a tuple that contains multiple values entered by the user
sum = 0
For i in Num:
sum + = i
Print sum
Add (1,2,3,4,5)
- keyword parameter : def info (name,password,gender,**other):
First output **other Look, find is the dictionary number type
**other This section can be any dictionary that you define:
Summary: When defining a function, several general parameters are mixed,
Order of mixed Use parameters: Required, default, variable, keyword
Functions in Python can return multiple values
Scope of variables in a function
Global variables: Unless the variable name is Del, it will remain in effect throughout the program.
Local variables: Only valid in the statement scope of the function
Note: In Python you want the local variable to take effect globally, you need the global keyword
#!/usr/bin/env python
# Coding:utf-8
num = Ten #全局变量
def fun ():
Global num
num = 3 #局部变量
Fun ()
Print num
#上面这个脚本的输出是3而不是10, because there is global, this local variable is not only working within the fun function.
#!/usr/bin/env python
# Coding:utf-8
num = 10
def fun ():
# Global Num
num = 3
Fun ()
Print num
#这个脚本的输出结果是10, because local variables work only within the fun function
Python (vii) function