Basic Python tutorial for. Net programmers-functions and exception handling [th Day], pythonfifth

Source: Internet
Author: User
Tags integer division

Basic Python tutorial for. Net programmers-functions and exception handling [th Day], pythonfifth

Today, the main record is the use of functions and Exception Handling in Python.

   I. functions:

1. Create and call functions.

def Add(val1,val2):    return  val1+val2;print Add(1,2)

2. defines a function that returns multiple parameters. The returned parameters are returned in the form of tuples. You can use the index in the following table to obtain a single value. The following is a function that obtains the sum of the two numbers and the difference between the two. in general, it is good. in C #, we generally use out to implement it. Multiple parameters are changed and returned, but it is not readable.

def GetSubAndSum(val1,val2):    return  val1-val2,val1+val2print GetSubAndSum(2,3)  #Answer:(2,3)print GetSubAndSum(2,3)[0] #Answer(2)

3. The function implements multiple parameters. The following example shows how to implement the parameters of any parameter and how to implement multiple parameters through. 1 x number is converted to a tuples, and 2 X numbers are converted to a dictionary. As for 3 X numbers, I have never tried it. I think no one will think about the complicated data.

def sumList(*param):    sumNumber=0    for val in param:        sumNumber+=val    return  sumNumberprint sumList(1,2,3) >>6def showList(*param):    print paramshowList(1,2,3)>>(1,2,3)showList()>>()def showDic(**param):    print(param)showDic(Name='Frank',Age=23)>>{'Age': 23, 'Name': 'Frank'}

5. recursion of the function. recursion means that the function calls itself internally. Let's take a look at how to obtain n through recursion!

Note: When N <1 does not return a value, it is None.

def Fun(N):    if(N==1):        return 1    elif(N>1):        return N*Fun(N-1)print Fun(3)>>6print Fun(-1)>>None

   Ii. Function exception handling: 

Since there are functions, some functions may fail, how can we catch exceptions? In Python, we use try... try t... finally to implement them.

1. exception type: [forgive me for being lazy. ]. In actual development, I personally think that Exception should be used more. In fact, we will not care about what is wrong, subsequent errors should be avoided by code in the program, or you can customize the Exception yourself.

 

2. Try... Try t.

def Div(val1,val2):    try:        return val1/val2    except ZeroDivisionError:        return 'Error'print Div(1,0)>>Error

3. capture multiple exceptions and print exceptions. All exceptions can be captured through exceptions.

def Div(val1,val2):    try:        return val1/val2    except (ZeroDivisionError,TypeError),E:        return Eprint Div(1,0)print Div(1,'2')>>integer division or modulo by zero>>unsupported operand type(s) for /: 'int' and 'str'

4. finally is useful in exception capture. It can be executed no matter whether there is any exception in finally code segments. The general purpose is to close the file stream in finally when reading the file, in this way, the file stream will not be closed and the file will crash.

def Div(val1,val2):    try:        return val1/val2    except (ZeroDivisionError,TypeError),E:        return E    finally:        print("No matter whether there have error,I will Excute")print Div(1,'2')print Div(1,1)>>No matter whether there have error,I will Excute>>unsupported operand type(s) for /: 'int' and 'str'>>No matter whether there have error,I will Excute>>1

5. the problem arises. Since finally must be executed, if the finally code block in a method contains the [return value] And try contains the [return value ], so what data will be obtained by calling this method. let's look at the following code.

Note: They all return finally. It is not clear why this design exists.

def Div(val1,val2):    try:        return val1/val2    except (ZeroDivisionError,TypeError),E:        return E    finally:        return  'I am finally'print Div(1,'2')print Div(1,1)>>I am finally>>I am finally

Iii. Summary:

This chapter records the creation and basic use of functions. And the usage of exceptions. There are still a lot to learn later, such:

1. [How to throw an exception in Python, not found? throw can be used in. Net. After all, an exception is encountered during development. Sometimes we need to further encapsulate the exception and throw the code above the layer]

2. [How do I customize exceptions? Is it similar to C #'s inherited Exception class? It will take several days to learn the Python abstraction knowledge]

3. [lamba learning, fitter, map, and reduce learning. A special blog will be used later to record learning notes .]

    

  

    

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.