python Lesson - Functions

Function returns

The master programmer Mr. Martin Fowler once said: "There are many bad taste codes, repetition is the worst kind!", To write high-quality code first problem to be solved is to repeat the code. For example, three times factorial:

m = int(input('m = '))
n = int(input('n = '))
fm = 1
for num in range(1, m + 1):
    fm *= num
fn = 1
for num in range(1, n + 1):
    fn *= num
fmn = 1
for num in range(1, m - n + 1 ): 
    fmn * = num 
print (fm // phone // fmn)

For the above codes, we can calculate the factorial function call encapsulated into a "function" function modules, where needed factorial calculation, we only need to "call" the "function" on it.

Defined Functions

Can be used in Python def keyword to define functions and variables as each function also has a famous name, but naming naming rules are rules and variables are the same. Can be passed in parentheses after the function name placed to function parameters, function and math on this is very similar in function parameters of the program is equivalent to saying the mathematical argument of a function, and the function execution is complete we can by return to return a key value, which is equivalent to saying that the dependent variable mathematical functions.

In the understanding of how to define a function, we can carry out the reconstruction of the above code, the so-called reconstruction is without effect on the structure of the code to adjust the premise of code execution result, the code after reconstruction is shown below.

DEF factorial (NUM):
     "" " 
    factorial 
    " "" 
    Result =. 1
     for n- in Range (. 1, NUM +. 1 ): 
        Result * = n-
     return Result 

m = int (INPUT ( ' m = ' )) 
n- = int (INPUT ( ' n-= ' ))
 # when it is necessary to calculate the factorial write cycle when not factorial but direct call function has been defined 
Print (factorial (m) // factorial (n-) // factorial (m - n- ))

Function parameters

Function is a code of the vast majority of programming languages are supported by the "building blocks", but the function of the Python language functions in the other there are still many not the same place, one significant difference is that Python for function parameters deal with. In Python, function parameters can have default values, but also supports the use of variable parameters, so Python does not need to support other languages like overloaded functions , we can make it because there are many different definitions of a function in time use, the following are examples of two small.

from Random Import the randint 


DEF roll_dice (= n-2 ):
     "" " 
    Shake dice 
    n: number of bosons 
    return: n boson particles and the number of dots 
    " "" 
    Total = 0
     for _ in Range (n-): 
        Total + the randint = (. 1,. 6 )
     return Total 

DEF the Add (A = 0, B = 0, C = 0):
     return A + B + C 

# argument not specified then use the default value of two dice roll 
Print (roll_dice () )
 # roll three dice 
Print (roll_dice (3 ))
 Print (the Add ())
 Print(the Add (. 1 ))
 Print (the Add (. 1, 2 ))
 Print (the Add (. 1, 2,. 3 ))
 # can not be transmitted in the order set when passing arguments 
Print (the Add (C = 50, A = 100 , b = 200))

We give two functions above parameters are set to default values, which means that if you use the default value for this parameter if the value of the corresponding parameter no incoming call functions, so we in the above code They can use a variety of different ways to call the addfunction, which like many other languages function overloading effect is the same.

In fact, the above add function as well as a better implementation, because we could have zero or more parameters adder, and specifically how many parameters are determined by the caller, we function as a designer this point We know nothing, so uncertain when the number of parameters, we can use a variable parameter, the code shown below.

# Before the parameter name indicates args * is a variable parameter 
# i.e. zero or more can be passed parameters when invoking the add function 
DEF add (* args): 
    Total = 0
     for Val in args: 
        Total + = Val
     return Total 
Print (the Add ()) Print (the Add (. 1 )) Print (the Add (. 1, 2 )) Print (the Add (. 1, 2,. 3 )) Print (the Add (. 1,. 3,. 5,. 7,. 9))

 Exercise

1, a simple function is defined

def H(user):
    vip = ['123','456','789']
    if user in vip:
        print("ok")
    else:
        print("error")
user = input()
H(user)

2, the purchase of goods

def Check_Goods(g):
    G = ['汽车','火车','飞机']
    if g in G:
        Address()
    else:
        return False

def Check_Info(name,phone,Addr):
    is_ok=True
    if name=="" or name ==" ":
        is_ok = False
    if len(phone) !=11:
        is_ok = False
    if Addr not in ['北京','山东']:
        is_ok = False
    return is_ok
def Address():
        Name = input("姓名:")
        Phone = input("电话:")
        Addr = input("地址:")
        res = Check_Info(Name,Phone,Addr)
        if (res):
            Note()
        returnFalse   
        
DEF Note ():
         Print ( " immediate shipment " ) 

DEF Start ():
     Print ( " Welcome " ) 
    G = the INPUT ( " Please enter the article: " ) 
    Check_Goods (G) 

    Start ()

3. User Registration

count = 0
def users():
    users_ = input('请输入用户名:')
    z = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    n = '1234567890'
    t = '!@!$#%^&*'
    is_z = False
    is_n = False
    is_t = True
    for i in users_:
        if i in z:
            is_z =True
         IF I in n-: 
            is_n = true
         IF I in T: 
            is_t = False
     IF is_n and is_t and is_z: 
        password () 
    the else :
         Print ( ' mistyped ' ) 


DEF password (): 
    the passwd = INPUT ( ' Enter password : ' )
     IF len (the passwd) <. 6 :
         Print ( ' password must be greater than six ')
     The else : 
        Phone () 

DEF Phone (): 
    P = INPUT ( ' Enter Telephone Number: ' )
     IF len (P) ==. 11 :
         Print ( ' verification code has been sent ' ) 
        VN () 
    the else :
         Print ( ' phone number 11 ' ) 


DEF VN ():
     Import Random
     Import Time
     Global COUNT 
    NUM = random.randrange (1000,9999 ) 
    COUNT + =. 1 
    START_TIME= The time.time ()
     Print ( ' East chi: D% ' % NUM) 
    num_ = int (INPUT ( ' Please enter this code: ' )) 
    END_TIME = the time.time () 
    
    SUB_TIME = END_TIME - START_TIME
     IF (SUB_TIME> 3 ):
         IF COUNT> 2 :
             Print ( " code acquiring too many times " ) 
            Exit () 
        Print ( " code timeout, retransmission ... " ) 
        the time.sleep ( 2 ) 
        VN ()
    the else :
         IF NUM == num_:
             Print ( " Registration Success " )
         the else :
             Print ( " Code Error " ) 

DEF Start (): 
    the Users () 
Start ()

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/gxnihao/p/11281885.html