Files
python_course/01_variables.ipynb
2025-10-20 19:53:27 +00:00

586 lines
18 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"id": "74336365-6e70-4b47-aeab-07c3a789693b",
"metadata": {},
"source": [
"# Переменные."
]
},
{
"cell_type": "markdown",
"id": "d93f7e89-b6c2-43fb-8b00-076a3cb05b78",
"metadata": {},
"source": [
"Переменные - это контейнеры для значений таких как строк, чисел, чисел с плавающей точкой, или булевых значений. Переменная ведет себя так же как и значение, которое хранит. Каждая переменная должна иметь уникальное имя. "
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "da325993-dcbf-45f8-8984-535e6071ddff",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Vlad\n"
]
}
],
"source": [
"first_name = \"Vlad\" # задали переменную first_name со значением Vlad\n",
"print(first_name) # аналогично print(\"Vlad\")"
]
},
{
"cell_type": "markdown",
"id": "71207199-4c93-4855-9e86-ec3015737991",
"metadata": {},
"source": [
"Допустим, мы хотим поприветствовать `first_name` и распечатать что-то типа \"Hello, Vlad\", для таких целей мы можем использовать форматируемые строки. В `python` если строка форматировуема, то перед ней ставят `f`. Посмотрим на примере"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "59a87db9-26be-4509-ac6f-f607322084ce",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Vlad\n"
]
}
],
"source": [
"first_name = \"Vlad\"\n",
"print(f\"Hello, {first_name}\") # в поле {first_name} подставится Vlad"
]
},
{
"cell_type": "markdown",
"id": "eb492fc6-d1a6-46e4-8f95-848bd684c7ee",
"metadata": {},
"source": [
"Заметим, что если не обозначить вид строки как форматируемой, то у нас напечатается \n",
"буквально что написано между кавычек, и ничего не подставится."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cf394481-6838-41a4-8647-f7e2c336d9ce",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, {first_name}\n"
]
}
],
"source": [
"first_name = \"Vlad\"\n",
"print(\"Hello, {first_name}\") # нет f перед строкой"
]
},
{
"cell_type": "markdown",
"id": "20e38d70-603d-446f-9fe4-274e6fc2b4ae",
"metadata": {},
"source": [
" Мы можем заводить сколько угодно различных переменных. Например"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "495c12a8-3caf-40cf-8935-068539188b29",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello Vlad\n",
"you like pizza\n"
]
}
],
"source": [
"first_name = \"Vlad\" # переменная 1\n",
"food = \"pizza\" # переменная 2\n",
"print(f\"hello {first_name}\")\n",
"print(f\"you like {food}\")"
]
},
{
"cell_type": "markdown",
"id": "28c4ba52-4bd0-4849-b909-53b70a96eab5",
"metadata": {},
"source": [
"Стоит отметить, что имя (`first_name`, `food`, и т.д.) переменной должно описывать ее содержимое. Это правило не является обязательным с точки зрения языка программирования, но для последующего понимания написанного стоит использовать описательные имена."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "baebcfa3-0b1b-4ccb-aba7-b60af075ff25",
"metadata": {},
"outputs": [],
"source": [
"kjhskdfhj = \"pizza\" # не описательное имя переменной\n",
"food = \"pizza\" # описательное имя переменной"
]
},
{
"cell_type": "markdown",
"id": "ab3d7fb5-658c-488e-8ae8-5b27eafe6ad4",
"metadata": {},
"source": [
"Добавим еще одно поле/переменную в нашу программу."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "33907261-c04d-499b-8bc8-e7e95a6804b8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello Vlad\n",
"you like pizza\n",
"your email is vlad@marmelad.com\n"
]
}
],
"source": [
"first_name = \"Vlad\" # переменная 1\n",
"food = \"pizza\" # переменная 2\n",
"email = \"vlad@marmelad.com\" # переменная 3\n",
"\n",
"print(f\"hello {first_name}\")\n",
"print(f\"you like {food}\")\n",
"print(f\"your email is {email}\")"
]
},
{
"cell_type": "markdown",
"id": "dc6d5342-5985-4841-81b3-0bdf717cfd94",
"metadata": {},
"source": [
"Пока что все введенные нами переменные (`first_name`, `food`, `email`) являлись переменными строкового типа."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "ecbc13b2-1b01-4877-903e-064ba8f4b54f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'str'>\n"
]
}
],
"source": [
"# при помощи функции type можно посмотреть тип переменной\n",
"print(type(first_name)) "
]
},
{
"cell_type": "markdown",
"id": "139999c5-7b17-4765-9665-33e109ebbe53",
"metadata": {},
"source": [
"Теперь добавим в программу целочисленные переменные (типа `int`),\n",
"которые будут хранить в себе целые числа."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "b15d0bba-7858-44ef-8d20-1733ecdf5b77",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello Vlad\n",
"you like pizza\n",
"your email is vlad@marmelad.com\n",
"you are 18 years old\n",
"you are buying 3 items\n",
"your class has 30 students\n"
]
}
],
"source": [
"first_name = \"Vlad\" # str\n",
"food = \"pizza\" # str\n",
"email = \"vlad@marmelad.com\" # str\n",
"\n",
"age = 18 # int\n",
"quantity = 3 # int\n",
"num_of_students = 30 # int\n",
"\n",
"print(f\"hello {first_name}\")\n",
"print(f\"you like {food}\")\n",
"print(f\"your email is {email}\")\n",
"print(f\"you are {age} years old\")\n",
"print(f\"you are buying {quantity} items\")\n",
"print(f\"your class has {num_of_students} students\")"
]
},
{
"cell_type": "markdown",
"id": "0daec73c-adfd-4e9b-a426-09628c241db4",
"metadata": {},
"source": [
"Названия типов данных - сокращения. Например: \n",
"* `int` - integer\n",
"* `str` - string\n",
"* `float` - floating point number\n",
"* `bool` - boolean"
]
},
{
"cell_type": "markdown",
"id": "72c38d28-fc0a-4065-9685-89408903c9c9",
"metadata": {},
"source": [
"Познакомимся еще с одним типом данных - `float` (числа с плавающей запятой)."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "165c57aa-505e-4991-a9a6-f6c5791c2407",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'float'>\n"
]
}
],
"source": [
"price = 10.99 # переменная типа float\n",
"print(type(price))"
]
},
{
"cell_type": "markdown",
"id": "c394be28-9977-4ee3-8727-f1e2b3281546",
"metadata": {},
"source": [
"Вместо привычной запятой для разделения целой и дробной частей ставится точка."
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "a3e1ac8a-1fdf-47d5-a54b-18a8f9af6fbd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The price is $10.99\n",
"your gpa is: 3.2\n",
"you ran 5.5km\n"
]
}
],
"source": [
"price = 10.99\n",
"gpa = 3.2\n",
"distance = 5.5\n",
"\n",
"print(f\"The price is ${price}\")\n",
"print(f\"your gpa is: {gpa}\")\n",
"print(f\"you ran {distance}km\")"
]
},
{
"cell_type": "markdown",
"id": "ed2f86dd-68ce-4d3e-a7f6-02b83cc2dafa",
"metadata": {},
"source": [
"Познакомимся с еще одним типом данных - `bool` (boolean), который может хранить только 2 значения `True` или `False`. Он часто используется в так называемых \"флагах\", чтобы обозначить состояние чего-либо. Но наиболее часто он неявно используется в ветвлениях, циклах и т.д."
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "0c804bb5-bbd6-497e-89e6-d9ae7343ff1e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"are you a student?: True\n"
]
}
],
"source": [
"is_student = True # создали переменную типа bool со значением True\n",
"\n",
"print(f\"are you a student?: {is_student}\")"
]
},
{
"cell_type": "markdown",
"id": "ce5e7881-ac15-4346-80eb-0edfa7e47069",
"metadata": {},
"source": [
"Переменную типа `bool` можно использовать в конструкции `if`-`elif`-`else`, то есть при проверке условия. Например "
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "3819a7b1-c506-4308-993c-4d23faafbc87",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"you are a student\n"
]
}
],
"source": [
"is_student = True\n",
"\n",
"if is_student: # если is_student это True\n",
" print(\"you are a student\") # то печатаем сообщение о том, что вы студент\n",
"else: # иначе (is_student это False)\n",
" print(\"you are NOT a student\") # то печатаем сообщение о том, что вы НЕ студент"
]
},
{
"cell_type": "markdown",
"id": "1ef25f0a-7ebd-4ed4-bd44-27396aa8ebaf",
"metadata": {},
"source": [
"В данном случае `is_student = True`, поэтому печатается \"you are a student\". Но если мы изменим `is_student` на `False`, то сработает блок `else`."
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "534d8de1-cd44-4577-9223-73f8e2e7b786",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"you are NOT a student\n"
]
}
],
"source": [
"is_student = False\n",
"\n",
"if is_student: # если is_student это True\n",
" print(\"you are a student\") # то печатаем сообщение о том, что вы студент\n",
"else: # иначе (is_student это False)\n",
" print(\"you are NOT a student\") # то печатаем сообщение о том, что вы НЕ студент"
]
},
{
"cell_type": "markdown",
"id": "457bc90f-b7e5-497d-980e-456b332165a8",
"metadata": {},
"source": [
"Приведем еще один пример."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "abc2b8ed-2d92-4289-a155-1172a98fe438",
"metadata": {},
"outputs": [],
"source": [
"for_sale = True\n",
"\n",
"if for_sale:\n",
" print(\"that item is for sale\")\n",
"else:\n",
" print(\"that item is not for sale\")"
]
},
{
"cell_type": "markdown",
"id": "be480bb2-8353-4e49-b2ca-7953f30f1e79",
"metadata": {},
"source": [
"В этом случае `for_sale = True`, поэтому срабатывает первый `print`. Если бы мы поменяли `for_sale` на `False`, то сработал бы блок `else`."
]
},
{
"cell_type": "markdown",
"id": "9513fa8f-3190-4479-a23f-e7efd2f895d2",
"metadata": {},
"source": [
"# Задания."
]
},
{
"cell_type": "markdown",
"id": "3bcafa63-5c4b-4f5d-8d8d-943ec9e64567",
"metadata": {},
"source": [
"1. Ниже, создайте программу, в которой задается переменная с именем `country` и ей присваивается страна, в которой вы живете. Добавьте `print` с соответствующей информацией как мы делали в примерах."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21f893ba-e0f1-4c72-a060-af8d6d2ab17f",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №1"
]
},
{
"cell_type": "markdown",
"id": "0a30e8d2-f078-4dce-a052-dc45bc77253d",
"metadata": {},
"source": [
"2. Добавьте к предыдущей программе целочисленную переменную, определяющее количество людей, живущее в стране `country`. Название переменной придумайте самостоятельно. Не забывайте, что по её названию должно быть понятно её содержимое. Также добавьте `print`, который будет печатать сообщение о количестве человек, живущей в стране `country`.\n",
"\n",
"P.S. А сможете ли вы объединить два разных типа в одном `print`? Напишите выражение типа \"в стране X живет Y человек\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "81a0ebf0-2148-4dfe-8e4f-8264452ee00b",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №2"
]
},
{
"cell_type": "markdown",
"id": "89705a7a-71ec-4498-82b5-03a2c06d2226",
"metadata": {},
"source": [
"3. Добавьте в вашу программу переменную типа `float` с именем `avg_age`, в которой будет хранится средний возраст человека в стране `country` с точностью до 2 знаков после запятой (точки). Обновите свое(и) `print` выражение(я), добавив туда новую информацию."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "00de321a-a023-4c37-bebb-bae790864a03",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №3"
]
},
{
"cell_type": "markdown",
"id": "be167590-41a0-48c0-9cfc-1e680268b47e",
"metadata": {},
"source": [
"4. Введите еще одну переменную типа `bool`. Придумайте самостоятельно для нее название, отражающее, что она будет обозначать. Добавьте `if`-`else` конструкцию, которая будет выводить разные сообщения в зависимости от значения вашей переменной."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5ecdfa67-14e8-470d-a925-93d200c0f9be",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №4"
]
},
{
"cell_type": "markdown",
"id": "d8c63a30-ab66-47b1-8029-a3e0773cfc7c",
"metadata": {},
"source": [
"5. Проверьте название типа своей созданной \"булевой переменной\" при помощи функции `type`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "754202e3-4cbc-44a4-a0dc-3563c7076bd0",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №5"
]
},
{
"cell_type": "markdown",
"id": "7b67b41b-552f-4ce3-ad5e-67f90b669441",
"metadata": {},
"source": [
"P.S. В новых версиях `python` можно удобно обозначать типы данных при создании переменных, например"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "fe9ed608-5f41-4b8f-8eed-682b805fd95b",
"metadata": {},
"outputs": [],
"source": [
"age: int = 18 # переменная типа int\n",
"gpa: float = 4.0 # переменная типа float\n",
"is_student: bool = True # переменная типа bool\n",
"name: str = \"Vlad\" # переменная типа str"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}