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.

age = 25
account_balance = -300   # 负数直接写
default_count = 0

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:

# 多进制示例
binary_10 = 0b1010         # 二进制的10
oct_493   = 0o755          # 八进制的493
hex_255   = 0xff           # 十六进制的255

# 下划线分隔,像写英文那样写数字
one_million = 1_000_000
long_hex    = 0x12_34_56   # 十六进制同样支持

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:

pi_approx          = 3.14159
earth_circumference = 4.0075e7   # 4.0075乘以10的7次方,即40075000.0
atomic_size        = 1e-10       # 1乘以10的-10次方,即0.0000000001

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

print(0.1 + 0.2)   # 输出 0.30000000000000004,而不是0.3!

If you are doing amount calculation or any scenario that requires accurate results,** never use it directlyfloat**, please use insteaddecimalModule:

from decimal import Decimal

total = Decimal('0.1') + Decimal('0.2')
print(total)        # 完美输出 0.3

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:

# 普通字符串,需要转义单引号
i_am_ok = 'I\'m OK'

# 双引号里直接嵌套单引号,更清爽
he_said = "He said 'Hello'"

# 原始字符串:Windows路径、正则表达式首选
win_path    = r'C:\Users\道满\Documents'
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

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.

# 多行诗歌
tang_poem = """静夜思
唐·李白

床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。"""

# 函数文档字符串——生成API文档、IDE提示都靠它
def calc_rect_area(length: float, width: float) -> float:
    """
    计算矩形的面积

    Args:
        length: 矩形的长度
        width:  矩形的宽度

    Returns:
        计算得到的矩形面积
    """
    return length * width

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:

name  = "道满"
score = 92.375

# 直接嵌入变量
msg1 = f"我是{name},本次测试得分{score}"
print(msg1)

# 嵌入表达式和函数
msg2 = f"明年我要涨{score + 5}分!分数取整是{round(score)}"
print(msg2)

# 格式控制:保留小数、对齐、百分比
price = 1234.5
print(f"价格:{price:.2f}元")           # 保留两位小数 → 1234.50
print(f"右对齐价格:{price:>10.2f}元")  # 总宽度10,右对齐
print(f"得分率:{score/100:.1%}")       # 百分比格式 → 92.4%

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, useandornotPerform logical operations:

is_student    = True
has_graduated = False

# 基本运算
print(True and False)  # False (全True才True)
print(True or False)   # True  (有一个True就True)
print(not True)        # False (取反)

# 条件判断示例
can_vote = is_student and (not has_graduated) and (age >= 18)
if can_vote:
    print("可以参与学生会投票!")

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==

# 函数没有return时,默认返回None
def greet(name):
    print(f"你好,{name}!")

result = greet("道满")
if result is None:
    print("这个函数没有返回任何有效数据")

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:

x = 100
print(type(x))   # <class 'int'>
x = "道满"
print(type(x))   # <class 'str'>

4.1 Mandatory naming rules

Violation of the following rules will directly report a syntax error:

  1. Can only consist of letters, numbers, and underscores
  2. Cannot start with a number
  3. Case sensitive (Nameandnameare two different variables)
  4. You cannot use Python keywords (such asifclassfor, availablekeyword.kwlistView all keywords)

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_namecalc_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)
# 推荐写法
MAX_LOGIN_ATTEMPTS = 5          # 常量
def get_user_profile(_user_id): # 内部函数
    pass

# 从typing模块导入Final(Python 3.8+),明确标记“不可修改”
from typing import Final
API_KEY: Final = "your-secret-key-here"

5. Type checking and conversion

5.1 Type checking

Two commonly used methods:

  • type(): Returns the exact type of the variable
  • isinstance(): Check whether the variable belongs to a certain type** or its subclass** (more flexible, recommended for daily use)
num = 10
print(type(num))                  # <class 'int'>
print(isinstance(num, int))       # True
print(isinstance(num, (int, float)))   # True,可同时检查多个类型

5.2 Common type conversions

built-in functionsint()float()str()bool()Type conversion is possible, but be aware of security risks:

# 安全转换,基本不会报错
float_from_int  = float(42)   # 42.0
str_from_float  = str(3.14)   # "3.14"

# 有风险的转换(可能抛出异常或丢失信息)
try:
    int_from_str = int("abc")   # 触发 ValueError
except ValueError:
    print("无法将非数字字符串转成整数!")

# bool() 的“假值”规则:空、0、None 都是 False,其他均为 True
print(bool(0))      # False
print(bool(""))     # False
print(bool([]))     # False
print(bool("道满")) # True

6. Comprehensive exercise: simple score calculator

Connect the knowledge you learned earlier and give it a try:

# 准备数据
student_name  = "道满"
math_score    = 87
english_score = 91.5
python_score  = 95.8

# 数值运算
total_score = math_score + english_score + python_score
avg_score   = total_score / 3

# 布尔判断
is_all_passed = math_score >= 60 and english_score >= 60 and python_score >= 60

# 用 f-string 展示报告
print("--- 学生成绩报告 ---")
print(f"姓名:{student_name}")
print(f"总分:{total_score:.1f}")
print(f"平均分:{avg_score:.2f}")
print(f"是否全部及格:{'✅' if is_all_passed else '❌'}")

7. Summary and best practices for avoiding pitfalls

  1. Floating point numbers must not be used directly for amount calculation, please usedecimal.Decimal
  2. Do not use it directly==To determine whether floating point numbers are equal, usemath.isclose(a, b)
  3. CheckNoneMust useis, instead of==
  4. Variable names must be descriptive to avoidxytempetc. Fuzzy naming (temporary loop variables can be relaxed appropriately)
  5. String formatting uses f-string (Python 3.6+)
  6. Follow PEP 8 naming convention to make the code clear and easy to read

This part is the "foundation" of Python. It is recommended to write several small codes for type conversion, formatting and Boolean judgment, and write down the pitfalls you have stepped on!

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: onlyTrue / 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.