Home Backend Development Python Tutorial Python basic learning code functions and functional programming

Python basic learning code functions and functional programming

Dec 29, 2016 pm 05:28 PM
python basics function functional programming

def func1():
    print 'hello world'
res = func1()
print type(res)
def func2():
    return ['xyz',10000,-98]
atuple = func2()
x,y,z = func2()
print x,y,z
def func3():
    return 'xyz',1000,-98
x,y,z = func3()
print x,y,z
def func4():
    return ['xyz',1000,-98,'xxx']
x,y,z,d = func4()
alist = x,y,z,d
print alist
true = lambda :True
print true()
sum = lambda x,y:x + y
summ = lambda x,y=4:x + y
atuplet = lambda *zaz:zaz
print atuplet('a',1)
adictt = lambda **z:z
print adictt(x=3,y=5)
from random import randint
def functest(arg):
    return arg % 2
allnums = []
for eachnum in range(9):
    allnums.append(eachnum)
print filter(functest,allnums)
allnums = []
for eachnum in range(9):
#    print eachnum
    ra = randint(1,99)
#    print ra
    allnums.append(ra)
#print filter(lambda x:x%2,allnums)
#print [i for i in allnums if i%2]
print [n for n in [randint(1,99) for i in range(9)] if n%2]
print map(lambda x:x+2,[i for i in range(9)])
print map(lambda x:x**2,[int(i) for i in range(9)])
print map(str,[i for i in range(9)])
print map(lambda x,y:x+y,[1,2,3],[1,2,3])
print map(lambda x,y:(x+y,x-y),[1,2,3],[1,2,3])
print map(None,[1,2,3],[1,2,3])
print reduce(lambda x,y:x+y,[i for i in range(3)])
from operator import  mul,add
from functools import partial
add1 = partial(add,1)
mul100 = partial(mul,100)
basetwo = partial(int,base=2)
basetwo.__doc__ = 'convert base 2 string to an int'
print basetwo('10010')
import Tkinter
root = Tkinter.Tk()
mybutton = partial(Tkinter.Button,root,fg='white',bg='blue')
b1 = mybutton(text='button1')
b2 = mybutton(text='button2')
qb = mybutton(text='quit',bg='red',command=root.quit)
b1.pack()
b2.pack()
qb.pack(fill=Tkinter.X,expand=True)
root.title('pfas!')
root.mainloop()
is_this_global = 'xyz'
def foo():
    global is_this_global
    this_is_local = 'abc'
    is_this_global = 'def'
    print this_is_local + is_this_global
def foor():
    m = 3
    def bar():
        n = 4
        print m + n
    print m
    bar()
def counter(start=0):
    count = [start]
    def incr():
        count[0] += 1
        return count[0]
    return incr
count = counter()
output = &#39;<int %r id=%#0x val=%d>&#39;
w = x = y = z = 1
def f1():
    x = y = z = 2
def f2():
    y = z = 3
    def f3():
        z = 4
        print output%(&#39;w&#39;,id(w),w)
        print output%(&#39;x&#39;,id(x),x)
        print output%(&#39;y&#39;,id(y),y)
        print output%(&#39;z&#39;,id(z),z)
    clo = f3.func_closure
    if clo:
        print &#39;f3 closure vars:&#39;,[str(c) for c in clo]
    else:
        print &#39;no f3 closure vars&#39;
    f3()
    clo = f2.func_closure
    if clo:
        print &#39;f2 closure vars:&#39;,[str(c) for c in clo]
    else:
        print &#39;no f2 closure vars&#39;
    f2()
    clo = f1.func_closure
    if clo:
        print &#39;f1 closure vars:&#39;,[str(c) for c in clo]
    else:
        print &#39;no f1 closure vars&#39;
from time import time
def logged(when):
    def log(f,*args,**kargs):
        print &#39;&#39;&#39;called:
function:%s
args:%s
kargs:%s&#39;&#39;&#39;%(f,args,kargs)
    def pre_logged(f):
        def wrapper(*args,**kargs):
            log(f,*args,**kargs)
            return f(*args,**kargs)
        return wrapper
    def post_logged(f):
        def wrapper(*args,**kargs):
            now = time()
            try:
                return f(*args,**kargs)
            finally:
                log(f,*args,**kargs)
                print &#39;time delta:%s&#39; % (time()-now)
        return wrapper
    try:
        return {&#39;pre&#39;:pre_logged,&#39;post&#39;:post_logged}[when]
    except KeyError,e:
        raise ValueError(e),"must be &#39;pre&#39; or &#39;post&#39;"
@logged(&#39;post&#39;)
def hello(name):
    print &#39;hello,&#39;,name
hello(&#39;world!&#39;)
x = 10
def ffoo():
    y = 5
    bar = lambda z:x+z
    print bar(y)
j,k = 1,2
def proc1():
    j,k = 3,4
    print &#39;j==%d and k==%d&#39;  % (j,k)
def proc2():
    j = 6
    proc1()
    print &#39;j==%d and k==%d&#39; % (j,k)
k = 7
proc1()
print &#39;j==%d and k==%d&#39; % (j,k)
j = 8
proc2()
print &#39;j==%d and k==%d&#39; % (j,k)
def max2(arg1,arg2):
    if arg1 > arg2:
        return arg1
    elif arg1 == arg2:
        return &#39;equal&#39;
    else:
        return arg2
max22 = lambda a,b:a if a > b else b
min22 = lambda a,b:a if a < b else b
def heji(a,b):
    return a+b,a*b
x,y = heji(3,4)
def mymin(a,b,*num):
    minnum = min22(a,b)
    for each in num:
        minnum = min22(minnum,each)
    return minnum
def mymax(a,b,*num):
    maxnum = max22(a,b)
    for each in num:
        maxnum = max22(maxnum,each)
    return maxnum
trantime = lambda m:(unicode(m / 60),unicode(m % 60))
print &#39;:&#39;.join(trantime(80))
a = [&#39;jia&#39;,&#39;wo&#39;,&#39;ma&#39;]
b = [&#39;get&#39;,&#39;hoa&#39;,&#39;?&#39;]
print map(None,a,b)
print zip(a,b)
def oddyear(y):
    if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
        return y
print filter(oddyear,range(1999,2030))
print [y for y in range(1999,2030) if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0]
print reduce(lambda x,y:x+y,range(6)) / float(6)
cl = lambda x:x.strip()
res = map(cl,open(&#39;e:\\thefile.txt&#39;))
import time
def timeit(arg):
    starttime = time.clock()
    result = arg
    endtime = time.clock()
    return (result,endtime-starttime)
def arg(a,b):
    return a * b
print timeit(arg(3,4))
mult = lambda x,y:x * y
print reduce(mult,range(9)[1:])
Copy after login

 以上就是Python基础学习代码之函数和函数式编程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

Common mistakes and pitfalls of golang functional programming Common mistakes and pitfalls of golang functional programming Apr 30, 2024 pm 12:36 PM

There are five common mistakes and pitfalls to be aware of when using functional programming in Go: Avoid accidental modification of references and ensure that newly created variables are returned. To resolve concurrency issues, use synchronization mechanisms or avoid capturing external mutable state. Use partial functionalization sparingly to improve code readability and maintainability. Always handle errors in functions to ensure the robustness of your application. Consider the performance impact and optimize your code using inline functions, flattened data structures, and batching of operations.

What are the advantages and disadvantages of Java functions compared to other functional programming languages? What are the advantages and disadvantages of Java functions compared to other functional programming languages? Apr 24, 2024 pm 02:51 PM

Java functional programming advantages include simplicity, composability, concurrency, test-friendliness, and performance. Disadvantages include learning curve, difficulty in debugging, limited flexibility, and performance overhead. Its key features include pure functions without side effects, data processing pipelines, stateless code, and efficient streaming APIs.

See all articles