Python functions for getting started with Python

Keywords: Python Lambda IPython ascii

By: PyQuant
Blog: https://blog.csdn.net/qq_33499889
MOOC: https://mooc1-2.chaoxing.com/course/207443619.html

Like, pay attention to, and form good habits
Life is short, U need Python
Learning Python, Come on, let me


1. Basic structure of function

2. Definition of function

def hello():
    print('hello python!')

hello()
hello python!
def foo(a,b):
    c = a + b
    return c

r = foo(10,20)  
print(r)
30

3. Parameters of function

The parameter types of functions are generally divided into the following four forms:

  • Essential parameters

  • Key parameters

  • Default parameters

  • Indefinite length parameter

[1] Required parameter

  • The required parameters must be passed into the function in the correct order.

  • The number of calls must be the same as when they were declared, or there will be a syntax error.

  • Example:

def myprint(my_string):
    print(my_string)

myprint('hello python')
hello python

[2] Key parameters

  • Key parameters are closely related to function calls, which use key parameters to determine the passed parameter values.

  • Using key parameters allows the order of parameters when a function is called to be different from when it is declared, because the Python interpreter can match parameter values with parameter names.

  • Example:

def print_me(name, age):
    print ("Name: ", name)
    print ("Age: ", age)
    return

print_me("PyQuant", 30 )
Name: PyQuant
 Age: 30
print_me(age=30, name="PyQuant" )
Name: PyQuant
 Age: 30

[3] Default parameters

  • When a function is called, the default parameter is used if no parameter is passed. If the age parameter is not passed in in the following example, the default value is used.

  • Example:

def print_me(name, age=30):
    print ("Full name-->", name)
    print ("Age-->", age)
    return

print_me("PyQuant" )
Name -- > pyquant
 Age > 30
print_me("PyQuant" ,40)
Name -- > pyquant
 Age > 40

[4] Indefinite length parameter

  • You may need a function that can handle more arguments than you originally declared. These parameters are called indefinite length parameters. Unlike the above parameters, they will not be named when declared.
  • Example
def print_me(arg, *args):
    print('arg   -->', arg)
    print('*args -->', args)

print_me(30,2,3,4)
arg   --> 30
*args --> (2, 3, 4)
def print_me(arg, **args):
    print('arg    -->', arg)
    print('**args -->', args)

print_me(30,a=2,b=3,c=4)
arg    --> 30
**args --> {'a': 2, 'b': 3, 'c': 4}

4. Special functions

  • lambda function

  • map() function

  • filter() function

[1]lambda

Python uses lambda to create anonymous functions, instead of defining a function in the standard form of a def statement.

  • lambda is just an expression, and the function body is much simpler than def.

  • The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.

  • lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.

polynomial = lambda x,y: x**2 + y**2
polynomial(1,2)
5

[2]map()

The map() function maps the specified sequence based on the provided function.

Its syntax form is: map(function, iterable ):

  • Function ---- call the function function with each element in the parameter sequence.

  • iterable ---- one or more sequences (such as lists, tuples, dictionaries, etc.).

  • Return value: Python 3.x returns the iterator, which is displayed through the built-in functions of the sequence (such as list,tuple,set, etc.).

lst = [1,2,3]
m = map(lambda x: 10*x ,lst)
m
<map at 0x1c93abb7208>
list(m)
[10, 20, 30]
def f(x,y):
    return (x,y)

lst_1 = [0,1,2,3,4,5,6]
lst_2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

print(list(map(f,lst_1,lst_2)))
[(0, 'Sun'), (1, 'Mon'), (2, 'Tue'), (3, 'Wed'), (4, 'Thu'), (5, 'Fri'), (6, 'Sat')]

[3]filter()

The filter() function is used to filter the sequence, filter out the unqualified elements, and return a new list of qualified elements.

Its syntax is: filter(function, iterable)

  • Function ---- judgment function.

  • iterable ---- iteratable object.

  • Return value ---- Python 3.x returns the iterator.

numbers = range(-3,3)
f = filter(lambda x: x > 0, numbers)
f
<filter at 0x1c93ab05b70>
list(f)
[1, 2]

5. scope of action

  • Local scope

  • Global scope

  • Nesting scope

  • Built in scope (builtin)

[1] Local scope

a = 100

def func():
    a = 300             
    print('Local scope: ', a)
    
func()
Local scope: 300

[2] Global scope

a = 100   
def func():
    a = 300   
    print('Local scope: ', a)
    
func()
print('global scope: ', a)
Local scope: 300
 Global scope: 100
a = 100            
def func():
    a += 100       
    print('Local scope: ', a)
func()
print('global scope: ', a)
---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

<ipython-input-41-4c68dbc3afd0> in <module>()
      3     a += 100
      4     print('Local scope: ', a)
----> 5 func()
      6 print('global scope: ', a)


<ipython-input-41-4c68dbc3afd0> in func()
      1 a = 100
      2 def func():
----> 3     a += 100
      4     print('Local scope: ', a)
      5 func()


UnboundLocalError: local variable 'a' referenced before assignment
a = 100            
def func():
    global a
    a += 100       
    print('Local scope: ', a)
    
func()
print('global scope: ', a)
Local scope: 200
 Global scope: 200

[3] Nesting -- nested functions

x = 123

def f1():
    x = 100
    print('f1--->',x)
    def f2():
        x = 200
        print('f2--->',x)
    f2()
    
f1()
f1---> 100
f2---> 200

[4] Built in scope (builtin)

import builtins
print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
  • It's not easy to write, don't plagiarize
  • The praise and attention of bloggers is the biggest encouragement for bloggers to insist on writing
  • Keep updating, not finished to be continued

Last article: Loop statement of Python Beginner (4) - analytic
Next: introduction to python (6): Python "three tools"

16 original articles published, 38 praised, 6732 visited
Private letter follow

Posted by turdferguson on Mon, 09 Mar 2020 19:39:02 -0700