SoFunction
Updated on 2025-03-01

A brief analysis of the usage of variables in Python

What are variables

In Python programming language, variables are identifiers used to store data values. They can be used to reference data values ​​instead of directly using the values ​​themselves. The equal sign (=) operator can be used to assign a value to a variable.

What are the variable data types?

There are several variable types:

1. Int: represents an integer, such as: `42`, `-3`, `1000`, etc.
2. Float: represents a floating point number (i.e., a number with a decimal point), such as: `3.14`, `-2.5`, `0.0`, etc.
3. Bool: means true or false, with only two values: `True` and `False`.
4. String type (str): represents a string, that is, a sequence composed of zero or more characters, such as: `"hello"`, `"world"`, `"123"`, etc.
5. List: represents an ordered set of elements, where the elements can be different types of data, such as: `[1, 2, "apple", True]`.
6. Tuple type: Similar to a list, it is also an ordered set of elements, but the elements in the tuple cannot be modified, such as: `(1, 2, "apple", True)`.
7. Set: represents an unordered set of elements, in which elements cannot be repeated, for example: `{1, 2, 3, 4}`.
8. dict: represents a set of key-value pairs, in which each key uniquely corresponds to a value, for example: `{"name": "Alice", "age": 30}`.

Here are a few small cases.

Practical cases

Here is the syntax for defining variables in Python:

variable_name = value

in,variable_nameIndicates the variable name,=is the assignment operator,valueis the value to be assigned to the variable. In Python, the types of variables are dynamic, meaning that they do not need to specify the type when declared, but automatically determine the type based on the value assigned to them.

Here are some examples:

# Define an integer variablex = 10
# Define a string variablename = "John"
# Define a Boolean variableis_valid = True
# Define a list variablenumbers = [1, 2, 3, 4, 5]
# Define a dictionary variableperson = {"name": "John", "age": 30}

In Python, you can refer to the value of a variable by using the variable name, for example:

print(x) print(name) print(is_valid) print(numbers) print(person)

How to use boolean variables

# Define boolean variablesis_sunny = True
is_raining = False

# Use boolean variables for conditional judgmentif is_sunny:
    print("It's a sunny day!")
else:
    print("It's not a sunny day.")

# Use boolean variables for loop controlwhile is_raining:
    print("It's still raining...")
  • Here are two Boolean variables is_sunny and is_raining, and then they are used for conditional judgment and loop control respectively.
  • In a conditional statement, if the value of the Boolean variable is True, the statement in the if code block is executed; otherwise, the statement in the else code block is executed.
  • In a loop, statements in the loop body are executed only if the value of the boolean variable is True. If the value of the variable becomes False during the execution of the loop, the loop will terminate.
  • It should be noted that in Python, the Boolean values ​​True and False are actually subclasses of integer types, where True is equal to integer 1 and False is equal to integer 0. Therefore, boolean values ​​can be used where integer types are required.

In Python 3, list variables are used to store an ordered set of elements, which can be the same type of data or different types of data. You can create a list in the following ways:

my_list = [1, 2, 3, 4, 5]  # List of integer elementsmy_list2 = ["apple", "banana", "orange"]  # List of string elementsmy_list3 = [1, "apple", True]  # A list of different types of elements
  • List indexes can be used to access elements in a list. List indexes in Python start at 0, so the first element has an index of 0, the second element has an index of 1, and so on. For example, to accessmy_listThe first element in  can use the following syntax:
first_element = my_list[3]
print(first_element)
  • You can also use slice syntax to access a portion of the list. Slice syntax uses colons between the start index and the end index:To specify a range, for example:
# Get the first three elements of my_listfirst_three_elements = my_list[0:3]
# Get the second and third elements of my_list2second_and_third_elements = my_list2[1:3]
print(second_and_third_elements)
  • In this example,first_three_elementsThe value of   will be[1, 2, 3],andsecond_and_third_elementsThe value of   will be["banana", "orange"]
  • The list also provides many useful methods, such asappend()Used to add elements at the end of the list,insert()Used to insert elements at a specified location,remove()Used to delete specified elements, etc.

In Python 3, dictionary variables are used to store a set of key-value pairs, where each key is unique, and the value can be any type of data. You can create a dictionary in the following ways:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}
  • In this example, we create a dictionary with three key-value pairs, where the keys are "name", "age" and "city", corresponding values ​​are "Alice", 30, and "New York".

You can use keys to access values ​​in a dictionary, for example:

name = my_dict["name"]
age = my_dict["age"]

#Print outprint(name)
print(age)

You can also use many methods provided by the dictionary to manipulate the dictionary, such as the keys() method is used to get all keys in the dictionary, the values() method is used to get all values ​​in the dictionary, the items() method is used to get all key-value pairs in the dictionary, and so on.

# Add a key-value pair to the dictionarymy_dict["gender"] = "female"

# Delete a key-value pair in the dictionarydel my_dict["city"]

# Get all keys in the dictionarykeys = my_dict.keys()

# Get all values ​​in the dictionaryvalues = my_dict.values()

# Get all key-value pairs in the dictionaryitems = my_dict.items()

In Python 3, the type of a variable is dynamic, that is, it does not need to specify its type when defining a variable, but determines its type based on the value of the variable at runtime. This dynamic typing feature makes Python3 programming more flexible and convenient.

The above is a detailed analysis of the usage of variables in Python. For more information about Python variables, please pay attention to my other related articles!