Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python functions and modules

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use Python functions and modules". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Overview of functions and modules (1) Overview of functions

A function can be seen as a collection of statements, and the statements it contains are executed through function calls. The function can return a calculation result, and different calculation results can be returned depending on the parameters of each function call. Python uses functions to improve code reuse and reduce code redundancy.

Execute dir (_ _ builtin__) to view all built-in objects in Python

['ArithmeticError',' AssertionError', 'AttributeError',' BaseException', 'BlockingIOError',' BrokenPipeError', 'BufferError',' BytesWarning', 'ChildProcessError',' ConnectionAbortedError', 'ConnectionError',' ConnectionRefusedError', 'ConnectionResetError',' 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', 'breakpoint',' bytearray', 'bytes',' callable', 'cell_count',' chr', 'classmethod',' compile', 'complex' 'copyright', 'credits',' debugcell', 'debugfile',' 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', 'runcell',' runfile', 'set' 'setattr', 'slice',' sorted', 'staticmethod',' str', 'sum',' super', 'tuple',' type', 'vars',' zip']

Demonstrate Python built-in functions

(2) Overview of modules

A module is the encapsulation of program code and data. Variables, functions, or classes defined in the module can be imported into other files for use. Python provides various functions through modules, for example, sys, os, math, random and so on are modules.

1. Sys module

View the objects (properties and methods) contained in the sys module

Path using the sys module

2. Os module

Import os Modul

Get the current working directory

3. Math module

4. Random module

Second, function

When writing programs, you often encounter similar code that is used in many places. At this point, the duplicate code can be extracted and defined as a function. As a result, the programming workload is simplified and the code structure is simplified.

A function has three elements: function name (function name), parameter list (parameter list), and return value (return value)

There are two types of parameters: position parameter (positional parameter) and key parameter (key parameter)

(1) define function 1. Syntax format

Def: define

Def function name (parameter table): function body (statement group) return return value

If we define a function without writing a return statement, the system will automatically add a return None to it.

2. Function type

No-parameter function

Single parameter function

Multi-parameter function

3. Case demonstration

Define no-parameter function

Define a single-parameter function (you can use position parameters or key parameters when calling)

Define multi-parameter function

Description: the parameter when defining the function is called formal parameter (formal paramter), which is referred to as formal parameter (virtual parameter); the parameter when calling function is called actual parameter (actual parameter), which is referred to as actual parameter. To call the function, you pass the argument to the parameter, and after processing, you get the return value.

Define a function with a return value

(2) call function 1. Brief description

The function is called by adding a set of parentheses to the function name, the arguments are placed in parentheses, and multiple arguments are separated by commas.

In Python, all statements are executed in real time, unlike the compilation process that exists in C _ blank +. Def is also an executable statement that defines a function. So the call to the function must be after the function definition.

In Python, the function name is also a variable that refers to the value returned by the return statement, and when there is no return value, the function value is None.

2. Case demonstration

Write and call the factorial function-factorial (n)

Run the program to view the results

(3) function parameters

When defining a function, the parameters in the parameter table are called formal parameters, or formal parameters for short. When a function is called, the parameters provided in the parameter table are called actual parameters, or arguments for short. In Python, a variable holds a reference to an object, similar to the pointer in C _ pointer +. To pass an argument to a formal parameter is to assign a reference to the object to the formal parameter.

1. Polymorphism of parameters.

Polymorphism is a feature of object-oriented, which means that one more behavior may get different results for different objects. Variables in Python have no type properties, and variables can refer to different types of objects. For the same function, different results can be obtained with different types of actual parameters, reflecting polymorphism.

2. Parameter assignment transfer

Typically, arguments are passed to formal parameters in the order in which the function is called. For example, when add (1,2.5) is called, 1 is passed to a Personality 2.5 to b. Python allows you to specify that arguments are passed to parameters in the form of parameter assignments.

Third, use the function to realize modularization. 1. Create a multi-level menu system.

Write programs-multi-level menu system .py

#-*-coding: utf-8-*-"" function: multi-level menu system author: Huawei date: January 4, 2021 "" def add_record (): print ('add record function to be developed') def query_record (): print ('query record function to be developed') def modify_record (): print ('modify record function to be developed') def delete_record () : print ('delete record function is yet to be developed') def login (): while True: print ('main menu') print ('=') print ('1. Add record') print ('2. Query record') print ('3. Modify record') print ('4. Delete record') print ('5. Return to the superior menu') print ('=') mc2 = int (input ('enter menu number:') if mc2 = = 1: add_record () elif mc2 = = 2: query_record () elif mc2 = = 3: modify_record () elif mc2 = = 4: delete_record () Else: breakwhile True: print ('=') print ('1. Log in') print ('2. Exit') print ('=') mc1 = int (input ('enter menu number:') if mc1 = = 1: login () elif mc1 = = 2: print ('Thank you for using!') Break2, start the program, view the effect

This is the end of the content of "how to use Python functions and modules". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report