Переменные и типы данных (Variables and Basic Data Types)
Словарь урока (Lesson Vocabulary)
- variable — переменная
- data type — тип данных
- integer — целое число
- float — число с плавающей точкой
- string — строка
- boolean — булево значение
- assignment — присваивание
- convert — преобразовать
Введение (Introduction)
В этом уроке мы узнаем о переменных и основных типах данных в Python. Переменные — это один из фундаментальных концептов в программировании, позволяющий хранить и манипулировать данными в программе.
In this lesson, we will learn about variables and basic data types in Python. Variables are one of the fundamental concepts in programming, allowing us to store and manipulate data in a program.
Что такое переменная? (What is a Variable?)
Переменная — это именованная область памяти, в которой хранится значение. Можно представить переменную как коробку с этикеткой, где этикетка — это имя переменной, а содержимое коробки — её значение.
A variable is a named memory location that stores a value. You can think of a variable as a box with a label, where the label is the variable name, and the contents of the box are its value.
Создание переменных в Python (Creating Variables in Python)
В Python создание переменной очень просто — вам нужно лишь присвоить значение имени. Синтаксис такой:
Creating a variable in Python is very simple—you just need to assign a value to a name. The syntax is:
имя_переменной = значениеДавайте рассмотрим несколько примеров:
Let's look at a few examples:
age = 25 name = "Alex" is_student = True height = 1.75В этих примерах:
In these examples:
age— переменная, содержащая целое число 25.ageis a variable containing the integer 25.name— переменная, содержащая строку "Alex".nameis a variable containing the string "Alex".is_student— переменная, содержащая булево значение True (Правда).is_studentis a variable containing the boolean value True.height— переменная, содержащая число с плавающей точкой 1.75.heightis a variable containing the floating-point number 1.75.
Правила именования переменных (Variable Naming Rules)
В Python есть несколько правил, которым нужно следовать при именовании переменных:
In Python, there are several rules to follow when naming variables:
- Имя переменной может содержать буквы, цифры и символ подчеркивания (_).
Variable names can contain letters, numbers, and the underscore character (_). - Имя переменной не может начинаться с цифры.
Variable names cannot start with a number. - Имя переменной не может быть ключевым словом Python (например,
if,for,whileи т.д.).
Variable names cannot be a Python keyword (e.g.,if,for,while, etc.). - Имена переменных чувствительны к регистру (т.е.
name,NameиNAME— это три разные переменные).
Variable names are case-sensitive (i.e.,name,Name, andNAMEare three different variables).
Вот несколько примеров правильных имен переменных:
Here are some examples of valid variable names:
name age user_name userName _private name1 NAMEА вот примеры неправильных имен переменных:
And here are examples of invalid variable names:
1name # Начинается с цифры user-name # Содержит дефис if # Ключевое слово PythonСоглашения по именованию (Naming Conventions)
В Python принято следовать определенным соглашениям по именованию:
In Python, it is customary to follow certain naming conventions:
- Используйте
snake_caseдля имен переменных и функций (слова в нижнем регистре, разделенные подчеркиваниями).
Usesnake_casefor variable and function names (lowercase words separated by underscores). - Используйте
UPPER_CASEдля констант.
UseUPPER_CASEfor constants. - Используйте
CamelCaseдля имен классов.
UseCamelCasefor class names.
Основные типы данных (Basic Data Types)
Python имеет несколько встроенных типов данных. Рассмотрим основные из них:
Python has several built-in data types. Let's look at the main ones:
Объявление переменных (Variable Declaration)
name = "Alice"
age = 25
height = 1.75
is_student = TrueЧисловые типы (Numeric Types)
# Целые числа (Integers)
age = 25
year = 2024
# Числа с плавающей точкой (Floating-point numbers)
height = 1.75
weight = 68.5
pi = 3.14159Строки (Strings)
# Одинарные кавычки (Single quotes)
name = 'Alice'
# Двойные кавычки (Double quotes)
message = "Hello, World!"
# Многострочные строки (Multiline strings)
text = """Это многострочная
строка, которая может
содержать несколько
строк текста."""Булевы значения (Boolean Values)
is_student = True
is_working = False
has_car = TrueПреобразование типов (Type Conversion)
В Python можно преобразовывать один тип данных в другой с помощью встроенных функций.
In Python, you can convert one data type to another using built-in functions.
# Строка в число (String to integer)
num_str = "42"
num_int = int(num_str)
print(num_int) # Выведет: 42
print(type(num_int)) # Выведет: <class 'int'>
# Строка в число с плавающей точкой (String to float)
pi_str = "3.14159"
pi_float = float(pi_str)
print(pi_float) # Выведет: 3.14159
print(type(pi_float)) # Выведет: <class 'float'>
# Число в строку (Number to string)
age = 25
age_str = str(age)
print(age_str) # Выведет: 25
print(type(age_str)) # Выведет: <class 'str'>
# Между числовыми типами (Between numeric types)
height = 175.5
height_int = int(height)
print(height_int) # Выведет: 175 (дробная часть отбрасывается)
# В булев тип (To boolean)
print(bool(0)) # Выведет: False
print(bool(1)) # Выведет: True
print(bool("")) # Выведет: False
print(bool("Hello")) # Выведет: TrueВажно знать (Important to know)
При преобразовании строки в число строка должна содержать только числовые символы, иначе возникнет ошибка ValueError.
When converting a string to a number, the string must contain only numeric characters, otherwise a ValueError will occur.
Использование переменных (Using Variables)
После создания переменных их можно использовать в различных операциях:
After creating variables, you can use them in various operations:
# Арифметические операции
x = 10
y = 5
sum_result = x + y # 15
diff_result = x - y # 5
prod_result = x * y # 50
div_result = x / y # 2.0
print(sum_result, diff_result, prod_result, div_result)
# Операции со строками
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # Конкатенация строк
print(full_name) # "John Doe"
# Вывод значений переменных
age = 25
print("I am", age, "years old.") # "I am 25 years old."Изменение значений переменных (Changing Variable Values)
Вы можете изменить значение переменной, просто присвоив ей новое значение:
You can change the value of a variable by simply assigning it a new value:
# Изменение значения числовой переменной
count = 10
print(count) # 10
count = 20
print(count) # 20
# Изменение типа переменной (динамическая типизация)
var = 100
print(var, type(var)) # 100 <class 'int'>
var = "Hello"
print(var, type(var)) # Hello <class 'str'>
# Увеличение значения переменной
score = 0
print(score) # 0
score = score + 10 # Увеличиваем на 10
print(score) # 10
score += 5 # Сокращенная запись для score = score + 5
print(score) # 15Подведение итогов (Summary)
В этом уроке мы:
In this lesson, we:
- Узнали, что такое переменные и как их создавать
Learned what variables are and how to create them - Изучили правила именования переменных
Studied variable naming rules - Познакомились с основными типами данных в Python: целые числа (
int), числа с плавающей точкой (float), строки (str) и булевы значения (bool)
Got acquainted with the basic data types in Python: integers (int), floating-point numbers (float), strings (str), and boolean values (bool) - Научились определять тип данных с помощью функции
type()
Learned how to determine the data type using thetype()function - Узнали о преобразовании типов данных
Learned about data type conversion - Научились использовать переменные в операциях и изменять их значения
Learned how to use variables in operations and change their values
Понимание переменных и типов данных является фундаментальным навыком в программировании. В следующих уроках мы будем использовать эти знания для создания более сложных программ.
Understanding variables and data types is a fundamental skill in programming. In the following lessons, we will use this knowledge to create more complex programs.
Проверь себя (Check Yourself)
- Какие основные типы данных существуют в Python?
What are the basic data types in Python? - Какие правила нужно соблюдать при именовании переменных?
What rules should be followed when naming variables? - Как можно узнать тип данных переменной в Python?
How can you find out the data type of a variable in Python? - Как преобразовать строку "123" в целое число?
How do you convert the string "123" to an integer?
Практическое задание (Practice Task)
Создайте программу variables_practice.py, которая демонстрирует работу с переменными и типами данных:
Create a variables_practice.py program that demonstrates working with variables and data types:
- Создайте переменные различных типов данных: целое число, число с плавающей точкой, строку и булево значение.
Create variables of different data types: an integer, a floating-point number, a string, and a boolean value. - Выведите значение каждой переменной и её тип с помощью функций
print()иtype().
Display the value of each variable and its type using theprint()andtype()functions. - Выполните несколько операций с вашими переменными (например, сложение чисел, конкатенацию строк) и выведите результаты.
Perform several operations with your variables (e.g., adding numbers, concatenating strings) and display the results. - Преобразуйте некоторые переменные из одного типа в другой и выведите результаты.
Convert some variables from one type to another and display the results.