A complete guide to Python data types and variables
Introduction
Whether you are writing automation scripts, AI models, or web backends, the starting point of all logic is "packing data in appropriate containers"**. This container is Python's variable, and what is put in it is called data type. Although these two concepts are basic, they can lead to pitfalls if you are not careful - for example, the precision of floating point numbers is lost, and variable naming is not standardized, which leads to a long time to find bugs.
This article will use clear examples + pitfall avoidance guides to help you understand this part of the content at once.
1. Numeric type
Python's numerical types are used to process various quantitative data, the most commonly used are integers (int) and floating point numbers (float). Complex numbers are rarely used in daily development and will not be covered in this article.
1.1 Integer (int)
Python's integers have no size limit. Even if you write a prime number with tens of thousands of digits, it can be processed directly without overflow like some languages.
Multi-ary notation and readability of large numbers
In addition to the default decimal, Python also supports binary, octal, and hexadecimal:
- Binary:
0bbeginning - Octal:
0obeginning - hexadecimal:
0xbeginning
Starting in Python 3.6, you can insert underscores into numbers_To improve readability, no matter how large the number is, it is clear at a glance:
1.2 Floating point number (float)
Numbers with a decimal point are floating point numbers. Python also supports scientific notation, such as usingeRepresents a power of 10, which is very suitable for processing extremely large or extremely small values:
Avoid Pitfalls: Floating Point Precision Issues
This is not a Python bug, but a general limitation of IEEE 754 floating point numbers - the computer uses binary approximation to store decimals internally, so some decimal decimals cannot be accurately represented, such as0.1 + 0.2:
If you are doing amount calculation or any scenario that requires accurate results,** never use it directlyfloat**, please use insteaddecimalModule:
2. String (str)
Strings are the only built-in type in Python for handling text. Use a pair of single quotes'...'or double quotes"..."Just enclose them. The two quotation marks have exactly the same function. You can choose according to your needs, or use them to nest each other to avoid escaping.
2.1 Escape characters and original strings
backslash\Special characters can be escaped, such as'\n'Indicates line break. But when dealing with Windows paths and regular expressions, a bunch of backslashes can cause a lot of headaches. At this time, add arprefix, becomes raw string (raw string), all backslashes will remain intact:
2.2 Multi-line strings and docstrings
Use triple quotes'''...'''or"""..."""You can write multiple lines of text directly without manually adding line breaks. Python officially recommends using three double quotes"""To write the documentation string (docstring) of a function, class or module, which can be recognized by the editor and facilitate the generation of help information.
2.3 Highly recommended: f-string formatting
Python has three string formatting methods, but since Python 3.6, only f-string is recommended - the simplest way to write, the best performance, and also supports direct embedding of expressions and function calls:
3. Boolean value (bool) and null value (None)
Although these two types are simple, they are ubiquitous in conditional judgments and function return values.
3.1 Boolean value (bool)
Boolean values onlyTrueandFalseFor two values, useand、or、notPerform logical operations:
3.2 Null value (None)
NoneIt is the only special object in Python that means "no value". it and0, empty string"", empty list[]etc. are completely different. examineNoneMust be used whenis,The ____ does not work==:
4. Variables and naming conventions
Python is a dynamically typed language. Variables do not need to declare types, they can be directly assigned values, and the types can even be changed at any time:
4.1 Mandatory naming rules
Violation of the following rules will directly report a syntax error:
- Can only consist of letters, numbers, and underscores
- Cannot start with a number
- Case sensitive (
Nameandnameare two different variables) - You cannot use Python keywords (such as
if、class、for, availablekeyword.kwlistView all keywords)
4.2 PEP 8 naming convention (recommended)
Although not a mandatory rule, following PEP 8 can make your code more professional and easier to read:
- Common variable/function name:
snake_case(all lowercase, words separated by underscores), such asuser_name、calc_avg_score - Constant:
ALL_CAPS(all capital words underlined), this is just a convention, Python will not prevent modifications - Internal (private) variables/functions: Start with a single underscore (by convention, they should not be called directly from outside the module)
5. Type checking and conversion
5.1 Type checking
Two commonly used methods:
type(): Returns the exact type of the variableisinstance(): Check whether the variable belongs to a certain type** or its subclass** (more flexible, recommended for daily use)
5.2 Common type conversions
built-in functionsint()、float()、str()、bool()Type conversion is possible, but be aware of security risks:
6. Comprehensive exercise: simple score calculator
Connect the knowledge you learned earlier and give it a try:
7. Summary and best practices for avoiding pitfalls
- Floating point numbers must not be used directly for amount calculation, please use
decimal.Decimal - Do not use it directly
==To determine whether floating point numbers are equal, usemath.isclose(a, b) - Check
NoneMust useis, instead of== - Variable names must be descriptive to avoid
x、y、tempetc. Fuzzy naming (temporary loop variables can be relaxed appropriately) - String formatting uses f-string (Python 3.6+)
- Follow PEP 8 naming convention to make the code clear and easy to read
Related tutorials
Summarize
This article will help you master the five core basic data types of Python:
- int: an integer of any size
- float: Number with decimal point (note the precision trap)
- str: The only built-in type for handling text (f-string is strongly recommended)
- bool: only
True/False, used for logical judgment - None: a special object that means "no value"
At the same time, we also learned the naming rules, type checking and conversion methods of variables. This knowledge may seem simple, but it is a solid foundation for subsequent learning of advanced-features such as lists, dictionaries, functions, classes, etc. Write more code and read more errors, and you will really get started.

