What are variables in Python?
A variable in Python is a name that is associated with an object in computer memory. Variables are used to store data and access it during program execution. The main feature of Python is that variables do not need to be declared explicitly - they are created automatically the first time a value is assigned.
Naming rules for variables
When creating variables in Python, the following rules must be followed:
- The variable name must begin with a letter (a-z, A-Z) or an underscore (_)
- The first character can be followed by letters, numbers (0-9), or underscores
- The case of the characters matters: the variables
name,NameandNAMEwill be different - Python reserved words cannot be used (for example,
if,for,while) - It is recommended to use meaningful variable names
# Correct variable names
user_name = "Ivan"
age = 25
_private_var = "secret data"
counter1 = 0
# Incorrect variable names
# 1name = "error" # starts with a number
# class = "error" # reserved word
Basic data types in Python
Numeric data types
int (integer) integers are used to represent integers without a fractional part.
positive_number = 42
negative_number = -17
zero = 0
large_number = 1000000
float (floating-point) floating-point numbers represent real numbers with a fractional part.
pi = 3.14159
temperature = -0.5
scientific_notation = 1.23e-4 # 0.000123
complex (complex numbers) complex numbers consist of real and imaginary parts, written as a + bj.
complex_num1 = 3 + 4j
complex_num2 = 2 - 5j
only_imaginary = 7j
String data type (string)
Strings represent sequences of characters enclosed in quotation marks. Python supports single, double, and triple quotes.
single_quotes = 'Hello, world!'
double_quotes = "Python programming"
triple_quotes = """Multiline
string in Python"""
empty_string =""
Logical data type (bool)
The boolean type accepts only two values: True (true) or False (false). It is used to perform logical operations and conditional checks.
is_student = True
is_completed = False
has_permission = True
Data collections
Lists ordered mutable collections can contain elements of various data types.
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "text", True, 3.14]
empty_list = []
nested_list = [[1, 2], [3, 4], [5, 6]]
Tuples (tuple) ordered immutable collections cannot be changed after creation.
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_element = (42,) # a comma is required for one element
Dictionaries collections of key-value pairs Allow you to quickly find values by keys.
person = {"name": "Anna", "age": 28, "city": "Moscow"}
empty_dict = {}
nested_dict = {"user": {"name": "Ivan", "role": "administrator"}}
Sets (set) - unordered collections of unique elements Automatically remove duplicates.
unique_numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}
empty_set = set() # an empty set is created by the set() function
Practical examples of working with variables
Creating and assigning values
# Simple assignment
x = 5
name = "Alexey"
is_active = True
# Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0
# Exchange of values
a, b = b, a
Defining the data type
x = 42
name = "Python"
is_valid = True
print(type(x)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(is_valid)) # <class 'bool'>
# Type verification
print(isinstance(x, int)) # True
print(isinstance(name, str)) # True
Changing the values of variables
counter = 0
print(counter) # 0
counter = 10
print(counter) # 10
counter += 5 # Increase by 5
print(counter) # 15
Data Type Casting
Python allows you to convert data from one type to another using built-in functions.
Number conversion
# Number per line
x = 123
x_str = str(x) # "123"
# Integer in float
x_float = float(x) # 123.0
# Float to an integer
y = 3.14
y_int = int(y) # 3 (the fractional part is discarded)
String conversion
# String to a number (if possible)
num_str = "456"
num_int = int(num_str) # 456
num_float = float(num_str) # 456.0
# A string in the list of characters
text = "Python"
char_list = list(text) # ['P', 'y', 't', 'h', 'o', 'n']
Conversion error handling
try:
invalid_str = "abc123"
number = int(invalid_str) # Will cause ValueError
except ValueError:
print("It is impossible to convert a string to a number")
Useful tips and recommendations
Checking the contents of a variable
# Checking for an empty value
text = ""
if not text:
print("Line is empty")
# Check for None
value = None
if value is None:
print("Value undefined")
Working with global and local variables
global_var = "Global variable"
def example_function():
local_var = "Local variable"
global global_var
global_var = "Modified global variable"
print(local_var) # Is only available inside
the print(global_var) function # Is available everywhere
Constants in Python
# Constants are usually written in capital letters
PI = 3.14159
MAX_SIZE = 100
DATABASE_URL = "localhost:5432"
Conclusion
Variables and data types are fundamental Python concepts that need to be understood for effective programming. Using variables correctly and understanding different types of data will help you create more readable and efficient code. Keep in mind the rules for naming variables, master working with different data types, and always check the correctness of type conversions in your code.