python-function Instance

Source: Internet
Author: User

1. Definition of Functions

Exercise: Judging if the input is not a number

#!/usr/bin/env pythondef isnum (): Sth = raw_input ("Please input something:") try:if type (int (sth)) = = Type (1):p rint '%s is A number "% sthexcept Exception:print"%s is not a number "% sthisnum ()



2. Parameters of the function

Exercise: Judging if the input is not a number

#!/usr/bin/env Pythonimport sysdef Isnum (s): For I in S:if i in "1234567890":p asselse:print "%s was not a number"% Sbreakel Se:print "%s is a number"% Sisnum (Sys.argv[1])


3. Default parameters for functions

Listdir () function

Exercise: Judging if the input is not a number

#!/usr/bin/env Pythonimport osdef Isnum (s): For I in S:if i in "1234567890":p asselse:breakelse:print SFOR I in (Os.listdir ( "/proc")): Isnum (i)


Note: Default parameters must be written in the back

In [3]: def fun (x=1,y): ...: Print X+yfile "<ipython-input-3-3b7bae6400b0>", line 1def Fun (x=1,y): Syntaxerror:no N-default argument follows default Argumentin [4]: def fun (X,y=1): ...: Print x+y...:in [5]: Fun (2)


4.1 Function variables

Exercise: Functions cannot be assigned to global variables within the function (local), or if they are declared as global variables.

#!/usr/bin/env Pythonx = 1def Fun (): Global Xx+=1print Xfun () print X


Results:

2

2


Exercise 2: Declare the internal variables of the function as global variables, and the external can also be called by the function

#!/usr/bin/env Pythonx = 1def Fun (): global xx + = 1global yy = 3print xprint yfun () print xprint y


Results:

2

3

2

3


Practice 3:locas (): Statistic variable, return dictionary

#!/usr/bin/env Pythonx = 1def Fun (): x = 1y = 1print locals () fun () print locals ()

Results:

{' Y ': 1, ' X ': 1} {' __builtins__ ': <module ' __builtin__ ' (built-in), ' __file__ ': ' 18.py ', ' __package__ ': None, ' x ': 1, ' fun ': <fu Nction fun at 0x7f53bc8938c0>, ' __name__ ': ' __main__ ', ' __doc__ ': None}


5. function return value

Exercise 1: Return none by default

#!/usr/bin/env pythondef Fun ():p rint ' Hello,world ' Print fun ()

Results:

Hello,world

None


Exercise 2: Customize return return value, the statement after return will no longer execute

#!/usr/bin/env pythondef Fun ():p rint "Hello,world" return "Heihei" print "haha" print fun ()

Results:

Hello,world

Heihei


Exercise 3: Determine if the input is a number

Print is seldom used in functions, and return is used to simplify

#!/usr/bin/env Pythonimport osdef Isnum (s): For i in s:if I not in ' 1234567890 ': return Falsereturn truefor i in (os.listdir ("/proc")): If Isnum (i):p rint i


Practice 4:isdigit () to determine if the input is a number

IsDigit (): Determines whether a string is a pure number (script more simplified)

#!/usr/bin/env Pythonimport osdef Isnum (s): If S.isdigit (): Return Truereturn falsefor I in (Os.listdir ("/proc")): If IsNum (i):p rint i


6. Multiple types of values (tuples or dictionaries) and redundant parameters

A tuple only represents one parameter, and a tuple with a *, you can pass the elements in the tuple as parameters to the script; tuples with parameters can only be placed behind, otherwise there is a syntax error

Exercise 1:

In [2]: def fun (x, Y, z): ...: print x + y +z...:in [3]: a = [1,2]in [4]: Fun (3,*a) 6


Error:

In [5]: Fun (*a,3)

File "<ipython-input-5-8a9ea4381ff5>", line 1

Fun (*a,3)

Syntaxerror:only named arguments may follow *expression


Exercise 2:

Dictionary arguments (parameter names and argument names are the same, location doesn't matter)

In [8]: def fun (x, Y, z): ...: print x + y +z...:in [9]: a = {"X": 1, "Y": 2, "z": 3}in [Ten]: Fun (**a) 6

Or:

In [All]: Fun (x=1,y=2,z=3)

6


Exercise 3:

In [1]: def fun (X,*ARGV,**KWARGV): ...: print x.: Print argv ...: print kwargv...:in [2]: Fun (1) 1 ( ){}

Exercise 4:

In the form of an equal sign or dictionary

In [6]: def fun (X,*ARGV,**KWARGV): ...: Print x ...: print argv ...: print kwargv...:in [7]: t = [ ]in [8]: Fun ("A", *t,y=1,**{"B": 1, "C": 2}) 1 (2, ' A ', 1, 2) {' Y ': 1, ' C ': 2, ' B ': 1}

7. Recursive invocation of functions (function call itself)

Conditions:

1) must have the final default result, i.e. if n = = 0

2) Recursive parameters must converge to the default result, i.e. factorial (n-1)

Exercise: factorial, n times f (n-1)

#!/usr/bin/env pythondef factorial (n): if n = = 0:return 1else:return n * factorial (n-1) print factorial (5)


Results:

120


Exercise 2: Accumulation, n plus f (n-1)

#!/usr/bin/env pythondef factorial (n): if n = = 0:return 0else:return n + factorial (n-1) print factorial (5)

Results:

15



python-function Instance

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.