杰瑞科技汇

Python primitives有哪些基础类型?

Of course! Let's break down the concept of "primitives" in Python.

Python primitives有哪些基础类型?-图1
(图片来源网络,侵删)

What are Primitives in Python?

In programming, primitive data types (also called built-in types or fundamental types) are the most basic, pre-defined data types that a language provides. They are the building blocks from which all other, more complex data structures are created.

In Python, these are the fundamental types that represent single values.

The main primitive data types in Python are:

  1. int (Integer)
  2. float (Floating-point number)
  3. str (String)
  4. bool (Boolean)
  5. NoneType (The None object)

Let's look at each one in detail.

Python primitives有哪些基础类型?-图2
(图片来源网络,侵删)

Integer (int)

Integers are whole numbers, without a fractional component. They can be positive, negative, or zero.

  • Description: Represents mathematical integers.
  • Examples: 10, -50, 0, 999999999
  • How to check type: type(10) returns <class 'int'>
# Examples of integers
age = 30
population = 8_000_000_000 # Using underscores for readability (Python 3.6+)
negative_temp = -15
print(age)          # Output: 30
print(population)   # Output: 8000000000
print(negative_temp)# Output: -15
print(type(age))    # Output: <class 'int'>

Float (float)

Floats (or floating-point numbers) are numbers that contain a decimal point. They are used to represent real numbers.

  • Description: Represents numbers with a fractional part.
  • Examples: 14, -0.001, 0, 5e2 (scientific notation for 250.0)
  • How to check type: type(3.14) returns <class 'float'>
# Examples of floats
pi = 3.14159
price = 19.99
scientific = 2.5e2 # 2.5 * 10^2 = 250.0
print(pi)           # Output: 3.14159
print(price)        # Output: 19.99
print(scientific)   # Output: 250.0
print(type(price))  # Output: <class 'float'>

Important Note on Precision: Due to how computers store floating-point numbers (binary floating-point), you can sometimes get tiny precision errors.

# This is a common floating-point precision quirk
result = 0.1 + 0.2
print(result) # Output might be 0.30000000000000004

String (str)

Strings are sequences of characters, used to represent text. In Python, strings are enclosed in either single (), double (), or triple ( or ) quotes.

Python primitives有哪些基础类型?-图3
(图片来源网络,侵删)
  • Description: Represents textual data.
  • Examples: "hello", 'Python', """This is a multi-line string"""
  • How to check type: type("hello") returns <class 'str'>
# Examples of strings
greeting = "Hello, World!"
name = 'Alice'
bio = """I am a
software developer."""
print(greeting) # Output: Hello, World!
print(name)     # Output: Alice
print(bio)
# Output:
# I am a
# software developer.
print(type(greeting)) # Output: <class 'str'>

Boolean (bool)

Booleans represent one of two values: True or False. They are fundamental for logic, conditional statements (if/else), and comparisons.

  • Description: Represents a truth value, either True or False.
  • Examples: True, False
  • How to check type: type(True) returns <class 'bool'>
# Examples of booleans
is_student = True
is_tired = False
print(is_student)   # Output: True
print(is_tired)     # Output: False
# Booleans are often the result of comparisons
age = 20
print(age > 18)     # Output: True
print(age == 15)    # Output: False
print(type(is_student)) # Output: <class 'bool'>

NoneType (The None Object)

None is a special primitive that represents the absence of a value. It is used to signify that a variable has no value assigned to it or that a function doesn't explicitly return anything.

  • Description: Represents "no value" or "null".
  • Example: None
  • How to check type: type(None) returns <class 'NoneType'>
# Example of None
middle_name = None # A person might not have a middle name
def do_nothing():
    # This function implicitly returns None
    pass
print(middle_name)      # Output: None
print(do_nothing())     # Output: None (because the function doesn't return a value)
print(type(middle_name)) # Output: <class 'NoneType'>

A Crucial Distinction: Primitives vs. Objects

A key feature of Python is that everything is an object. This means that even the primitive types we just discussed are actually full-fledged objects.

This has important implications:

  1. They have Methods: You can call methods on primitive types because they are objects.

    message = "hello world"
    # The .upper() method is called on the string object
    print(message.upper()) # Output: HELLO WORLD
    # The .is_integer() method is called on the float object
    num = 10.0
    print(num.is_integer()) # Output: True
  2. They have Attributes: Objects can have attributes (data stored within them).

    # You can check the length of a string (which is an attribute)
    text = "python"
    print(len(text)) # Output: 6
    # Note: len() is a built-in function that calls the __len__() method of the object.

Summary Table

Type Name Keyword Description Example
Integer int Whole numbers 42, -10, 0
Float float Numbers with a decimal 14, -0.5, 0e2
String str Textual data "hello", 'Python'
Boolean bool Truth values True, False
NoneType None Absence of a value None

Other Types (Not Primitives)

It's important to know what is not considered a primitive. Types that are built from primitives are called data structures or collections.

  • list: An ordered, mutable collection of items. e.g., [1, "a", True]
  • tuple: An ordered, immutable collection of items. e.g., (1, "a", True)
  • dict: A collection of key-value pairs (a map). e.g., {"name": "Alice", "age": 30}
  • set: An unordered collection of unique items. e.g., {1, 2, 3}

In short, the primitives are the simple, single-value building blocks, while the other types are more complex containers that hold these primitives.

分享:
扫描分享到社交APP
上一篇
下一篇