search
HomeBackend DevelopmentPython TutorialDetailed introduction to python built-in functions

To summarize the built-in functions, Build-in Function.

1. Mathematical operations

##oct(x)Convert a number to octalhex(x)Convert the integer x to a hexadecimal string chr(i)Return the ASCII corresponding to the integer i Charactersbin(x)Converts the integer x to a binary stringbool([x])Convert x to Boolean type
abs(x)

Find the absolute value

complex([real[, imag]]) Create a complex number
pmod(a, b) Get the quotient and remainder respectively
Note: Both integer and floating point types can
float([x]) Convert a string or number to Floating point number. If there are no parameters, it will return 0.0
int([x[, base]]) Convert a character to int type, base represents the base number
long([x[, base]]) Convert a character to long type
pow(x, y[, z]) Returns the y power of x
range([start], stop[, step]) Generates a sequence, default Starting from 0
round(x[, n]) Rounding
sum(iterable[, start]) Sum the set

2. Collection class operations

##basestring() cannot be called directly, but can be used as isinstance judgmentformat(value [, format_spec])The formatted parameter sequence starts from 0, such as "I am {0},I like {1}"unichr( i)enumerate(sequence [, start = 0])iter(o[, sentinel])##max(iterable[, args...][key]) Returns the maximum value in the setmin(iterable[, args...][key])Returns the minimum value in the setdict([arg])Create data dictionarylist([iterable]) Convert one collection class to another collection classset()set object instantiationfrozenset([iterable])Produces an immutable setstr([object]) Convert to string typesorted(iterable[, cmp[, key[, reverse]]]) Team collection sortingGenerate a tuple typeThe xrange() function is similar to range(), but xrnage() does not create a list, but returns an xrange object, which behaves like a list. But only calculate list values ​​when needed. This feature can save us memory when the list is large
Super class of str and unicode
Formatted output string
Returns unicode of the given int type
Returns an enumerable object , the next() method of the object will return a tuple
generates an iterator of the object, the second parameter represents Delimiter
##tuple([iterable])
xrange ([start], stop[, step])

3. Logical judgment

all(iterable) 1. When all the elements in the set are true, it is True
2. In particular, if it is an empty string, it returns True
any(iterable) 1. When one element in the set is true Is true
2. In particular, if it is an empty string, it returns False
cmp(x, y) If x y, returns a positive number

4. Reflection

##classmethod()1. Annotation is used to indicate that this method is a class methodcompile(source, filename, mode[, flags[, dont_inherit]])Compile source into code or AST object. Code objects can be executed via the exec statement or evaluated with eval(). dir([object])1. Without parameters, return the current List of variables, methods and defined types within the scope; delattr(object, name)Delete the object object Attribute named nameeval(expression [, globals [, locals]])Calculate the value of expression expressionexecfile(filename [, globals [, locals]])The usage is similar to exec(), except that the parameter filename of execfile is the file name, and the parameter of exec is a string. filter(function, iterable)Construct a sequence, which is equivalent to [item for item in iterable if function(item)]##len( s) Return the collection lengthlocals() Return the current variable listmap (function, iterable, ...) Traverse each element and perform the function operationmemoryview(obj) Return a memory image type The object of next(iterator[, default]) is similar to iterator.next()##object() property([fget[, fset[, fdel[, doc]]]]) reduce(function, iterable[, initializer]) reload(module) setattr(object, name, value)repr(object) slice()staticmethodsuper(type[, object-or-type]) type (object)vars([object]) bytearray([source [, encoding [, errors]]])1. If source is an integer, return An initialization array with a length of source; zip([iterable , ...])
callable(object) Check whether the object object is callable
1. The class can be called
2. The instance cannot be called Unless the __call__ method is declared in the class
2. Class Methods can be called by classes or instances
3. Class methods are similar to static methods in Java
4. There is no self parameter required in class methods
1. Parameter source: string or AST (Abstract Syntax Trees) object.
2. Parameter filename: the name of the code file. If the code is not read from the file, some identifiable values ​​will be passed.
3. Parameter model: Specify the type of compiled code. Can be specified as 'exec', 'eval', 'single'.
4. Parameters flag and dont_inherit: These two parameters will not be introduced for the time being.
2. When taking parameters, return the list of properties and methods of the parameters.
3. If the parameter contains the method __dir__(), this method will be called. When the parameter is an instance.
4. If the parameter does not contain __dir__(), this method will collect parameter information to the maximum extent
1. Parameter function : A function whose return value is True or False, which can be None
2. Parameter iterable: sequence or iterable object
getattr(object, name [, defalut]) Get the attributes of a class
globals() Returns a dictionary describing the current global symbol table
hasattr(object, name) Judge object object Whether to include the attribute named name
hash(object) If the object object is a hash table type, return the hash value of the object object
id(object) Returns the unique identifier of the object (memory identifier) ​​
isinstance(object, classinfo) Determine whether object is an instance of class
issubclass(class, classinfo) Determine whether it is a subclass
Base class
Wrapper class for property access, After setting, you can access the setter and getter through c.x=value, etc.
Merge operation, starting from the first The first two parameters, then the results of the first two are combined with the third one for processing, and so on
Reload module
Set attribute value
will An object is transformed into a printable format
 
Declare static Method is an annotation
references the parent class
Returns the type of the object
Returns the object's variables, if there are no parameters and dict() The method is similar to
Returns a byte array2. If source is a string, convert the string into a byte sequence according to the specified encoding;
3. If source is an iterable type, the element must be [ 0,255];
4. If the source is an object consistent with the buffer interface, this object can also be used to initialize bytearray.

is approximately equal to a zipper, which is to arrange the elements in the two lists one by one

5. IO operation

file(filename [, mode [, bufsize]])1. Parameter filename: file name. input([prompt]) It is recommended to use raw_input, because this function will not capture user input errorsopen(name[, mode[, buffering]]) What is the difference from file? It is recommended to use openprintraw_input([prompt])
Constructor of file type, which is used to open a file. If When the file does not exist and the mode is write or append, the file will be created. Adding 'b' to the mode parameter will operate on the file in binary form. Adding '+' to the mode parameter will allow simultaneous read and write operations on the file 2. Parameter mode: 'r' (read), 'w' (write), 'a' (append).
3. Parameter bufsize: If it is 0, it means no buffering. If it is 1, it means line buffering. If it is a number greater than 1, it means the size of the buffer.

Get user input
Open a file
Print function
Set input , the input is processed as a string

The above is the detailed content of Detailed introduction to python built-in functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software