Files
python_course/03_user_input.ipynb
2025-10-25 15:58:43 +00:00

258 lines
8.7 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": "3beaec4d-0974-495f-b538-61b74c461410",
"metadata": {},
"source": [
"# User Input"
]
},
{
"cell_type": "markdown",
"id": "108ea414-31fc-4cae-8951-e87742d0fc20",
"metadata": {},
"source": [
"`input()` - функция, которая просит пользователя ввести данные, а возвращает введенные данные в формате строки (`str`). Попробуем ее использовать."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "e43b4186-6a5f-4559-a619-bd55289ee62e",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" vlad\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"your name is vlad\n"
]
}
],
"source": [
"name = input()\n",
"print(f\"your name is {name}\")"
]
},
{
"cell_type": "markdown",
"id": "372a4b5f-d601-4dc2-801c-c31f2cd76cbe",
"metadata": {},
"source": [
"Как видно, в переменную `name` сохранилась введенная строка.\n",
"Ввод строки заканчивается нажатием на клавишу `enter`. Попробуйте запустить программу выше и ввести свое имя в соответствующее поле."
]
},
{
"cell_type": "markdown",
"id": "3c3de63f-d8b2-4322-9eab-33dda9a219f8",
"metadata": {},
"source": [
"В функцию `input()` можно передавать строковый параметр чтобы \"подсказать\" пользователю, какой ввод от него ожидается."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "70c2964a-afc9-4400-83a8-fd0c3ef5b641",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"enter your name: nik\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"your name is nik\n"
]
}
],
"source": [
"name = input(\"enter your name: \")\n",
"print(f\"your name is {name}\")"
]
},
{
"cell_type": "markdown",
"id": "28b6fdde-c224-41db-96db-5b49ae16324a",
"metadata": {},
"source": [
"Давайте напишем программу, которая будет спрашивать у пользователя имя и возраст, а затем поздравлять его с днем рождения."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "09059004-0c78-4374-863e-f29ee1f08cf6",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"what is your name?: vlad\n",
"How old are you?: 12\n"
]
},
{
"ename": "TypeError",
"evalue": "can only concatenate str (not \"int\") to str",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[6], line 4\u001b[0m\n\u001b[1;32m 1\u001b[0m name \u001b[38;5;241m=\u001b[39m \u001b[38;5;28minput\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mwhat is your name?: \u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;66;03m# запрашиваем имя\u001b[39;00m\n\u001b[1;32m 2\u001b[0m age \u001b[38;5;241m=\u001b[39m \u001b[38;5;28minput\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mHow old are you?: \u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;66;03m# запрашиваем возраст\u001b[39;00m\n\u001b[0;32m----> 4\u001b[0m age \u001b[38;5;241m=\u001b[39m \u001b[43mage\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m \u001b[38;5;66;03m# увеличиваем возраст на 1\u001b[39;00m\n\u001b[1;32m 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mHello \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m!\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 7\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mHappy Birthday\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
"\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"
]
}
],
"source": [
"name = input(\"what is your name?: \") # запрашиваем имя\n",
"age = input(\"How old are you?: \") # запрашиваем возраст\n",
"\n",
"age = age + 1 # увеличиваем возраст на 1\n",
"\n",
"print(f\"Hello {name}!\")\n",
"print(\"Happy Birthday\")\n",
"print(f\"you are {age} years old\")"
]
},
{
"cell_type": "markdown",
"id": "2bb86b8e-32b9-4a81-add5-aa6582110d7a",
"metadata": {},
"source": [
"Программа выше выдаст ошибку, так как мы получаем возраст в формате `str` и хотим его увеличить путем прибавления единицы. Но мы не можем складывать `int` и `str` поэтому `age` нужно привести к типу `int`, а потом уже выполнять сложение."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "c9290070-1446-4198-a315-6e07e255fdda",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"what is your name?: vlad\n",
"How old are you?: 12\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello vlad!\n",
"Happy Birthday\n",
"you are 13 years old\n"
]
}
],
"source": [
"name = input(\"what is your name?: \") # запрашиваем имя\n",
"age = input(\"How old are you?: \") # запрашиваем возраст\n",
"\n",
"age = int(age) # приводим age к типу int\n",
"\n",
"age = age + 1 # увеличиваем возраст на 1\n",
"\n",
"print(f\"Hello {name}!\")\n",
"print(\"Happy Birthday\")\n",
"print(f\"you are {age} years old\")"
]
},
{
"cell_type": "markdown",
"id": "ae37308f-3188-416e-9c6e-73bfdc7c1b84",
"metadata": {},
"source": [
"Чаще всего не пишут отдельно `age = int(age)`. Вместо этого можно использовать вот такую запись."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3e76933a-1826-4140-a477-8a7190f3ca52",
"metadata": {},
"outputs": [],
"source": [
"name = input(\"what is your name?: \") # запрашиваем имя\n",
"\n",
"# запрашиваем возраст и сразу приводим к типу int\n",
"age = int(input(\"How old are you?: \"))\n",
"\n",
"age = age + 1 # увеличиваем возраст на 1\n",
"\n",
"print(f\"Hello {name}!\")\n",
"print(\"Happy Birthday\")\n",
"print(f\"you are {age} years old\")"
]
},
{
"cell_type": "markdown",
"id": "184d3b4f-c355-4cc5-b8fe-52243ead0c6e",
"metadata": {},
"source": [
"# Задания"
]
},
{
"cell_type": "markdown",
"id": "fb0e7425-75e3-41db-b010-55638abefe3c",
"metadata": {},
"source": [
"1. Введите 2 переменные `length` (длина) и `width` (ширина). Запросите их значения у пользователя. И затем выведите площадь прямоугольника с такими сторонами. Программа должна оканчиваться строкой.\n",
"\n",
"```python\n",
"print(f\"the area of the rectangle with length = {length} and width = {width} equals {area}\")\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ead46f8a-2550-47b9-a07c-1d4a8efb5d23",
"metadata": {},
"outputs": [],
"source": [
"# решение задания №1"
]
}
],
"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
}