1.1. What are Variables?
In Python, variables are names assigned to objects that are used for storing, changing, and accessing data within a program. Python is a dynamically typed language. This means that the type of a variable is determined at the moment a value is assigned to it, and this type can change during the program execution.
Main aspects of variables in Python:
1. Declaration and Assignment:
In Python, variables do not require declaration for reserving memory. Assigning values to variables automatically reserves memory and determines their type. For example, x = 10 creates a variable named x and assigns it the value 10.
2. Naming:
Variable names must be descriptive and follow the rules for Python identifiers, like not starting with numbers and not containing special characters, except for the underscore.
Examples:
| name1 = "Alex" | name1 — a good name. |
|---|---|
| user_age = 5 | user_age — a good name. |
| %city% = 7 | %city% — a bad name, it contains special characters. |
| 1234qwerty = 1234 | Bad name — starts with a number. |
3. Dynamic Typing:
As we mentioned, the type of a variable in Python is determined during program execution, which makes the language flexible and convenient for development. An example of changing the type during the program: code x = 10 assigns x a number value, and then code x = "hello" assigns x a string value.
Examples:
| age = "Alexander" | The variable age holds a value — a string with the text "Alexander" |
|---|---|
| age = 35 | The variable age holds a value — the number 35 |
| age = "London" | The variable age holds a value — a string with the text "London" |
| age = 3.14 | The variable age holds a value — the floating-point number 3.14 |
4. Referential Nature of Variables:
In Python, variables are references to objects. This means that when a value is assigned to a variable, a reference to an object with that value is actually created. If variables x and y point to the same object, any changes made using x will also affect y, since both variables refer to the same object in memory.
5. Scope:
The scope of a variable defines the part of the program where the variable is accessible. Python supports local, global, and non-local (in the context of nested functions) variables. We'll dive deeper into this and the previous topic a bit later. Not everything at once.
6. Memory Management:
Python automatically manages variable memory with a garbage collector that tracks and frees up unused memory.
7. Immutability of Objects:
Some data types in Python, like strings and tuples, are immutable. This means their content cannot be changed once created. Any attempts to modify such data will result in creating a new object.
8. Multiple Assignments:
In Python, you can perform several assignment operations in one line. Examples:
| x = 1 | |
|---|---|
| y = 2 | x, y, z = 1, 2, 3 |
| z = 3 |
1.2. Data Types
Python supports several basic data types that are used for storing and manipulating data in programs. These include int, str, float and bool.
int (integers)
The int data type is used to represent whole numbers without a fractional part. It can store both positive and negative values. For example, x = 5 assigns the integer 5 to the variable x.
str (strings)
The str type is used to store text information, or strings. Strings in Python are enclosed in single or double quotes. For example, name = "John" assigns the string "John" to the variable name. Strings in Python support many operations, such as concatenation and duplication, as well as a bunch of methods for text manipulation.
float (floating-point numbers)
The float type in Python is used to represent floating-point numbers, meaning numbers that contain a fractional part. These numbers are written using a decimal point. For example, pi = 3.14 assigns the variable pi the value of π, rounded to two decimal places.
bool (boolean values)
The boolean data type bool takes one of two values: True or False. It's often used to control the execution of conditions in scenarios like conditional statements and loops. For example, is_valid = True indicates that the variable is_valid holds the boolean value True.
These data types form the foundation for building more complex data structures and algorithms in Python, allowing programmers to effectively manage data and logic in their programs.
1.3. Variable Names
In Python, variable names are not just a way of referencing data, they are a key part of the code that makes it understandable and maintainable. Picking the right variable names can significantly simplify understanding the code and its subsequent debugging, while poor choices can lead to confusion and errors.
Main Rules for Naming Variables in Python:
Use clear names: A variable name should reflect the data it holds, making the code easily readable. For example, count is better than x if the variable is used for counting something.
Follow styling standards: In Python, the widely accepted standard is PEP 8, which recommends using lowercase with underscores for variable names (like my_variable).
Avoid conflicts with keywords: Don't use words that Python has reserved for its syntax, like if, else, class, return, and so on. This can lead to execution errors.
Use short names for small-scale variables: For local variables, used in small blocks of code, short names like i or j are often suitable and make the code more compact.
Use long and descriptive names for global variables: Global variables and constants that are used in many parts of the program should have longer and descriptive names to make their purpose clear.
Examples of Good Variable Names:
user_age instead of age (if there might be several ages in context)
total_price instead of total (clarifies that it's specifically about price)
max_height or min_height instead of max_h or min_h
Special Cases:
In many algorithms, especially mathematical and scientific ones, it's common to use single-letter variables (e.g., x, y, z for coordinates). This is acceptable when such a style is an industry standard and only enhances code understanding.
Variable names in Python play a significant role in creating efficient, sustainable, and easily maintainable code. So don't skimp on it and strive to come up with good names. This can greatly simplify the debugging and maintenance process of your code, as well as make it more accessible to other programmers.
GO TO FULL VERSION