Скачать "Python Full Course for Beginners"

Скачайте это видео через UDL Client
Скачатьarrow down icon
  • Видео mp4 HD+ со звуком
  • Mp3 в максимальном качестве
  • Файлы любого размера
"videoThumbnail Python Full Course for Beginners
play-icon
Оглавление
|

Оглавление

0:00
Introduction
1:49
Installing Python 3
6:10
Your First Python Program
8:11
How Python Code Gets Executed
11:24
How Long It Takes To Learn Python
13:03
Variables
18:21
Receiving Input
22:16
Python Cheat Sheet
22:46
Type Conversion
29:31
Strings
37:36
Formatted Strings
40:50
String Methods
48:33
Arithmetic Operations
51:33
Operator Precedence
55:04
Math Functions
58:17
If Statements
1:06:32
Logical Operators
1:11:25
Comparison Operators
1:16:17
Weight Converter Program
1:20:43
While Loops
1:24:07
Building a Guessing Game
1:30:51
Building the Car Game
1:41:48
For Loops
1:47:46
Nested Loops
1:55:50
Lists
2:01:45
2D Lists
2:05:11
My Complete Python Course
2:06:00
List Methods
2:13:25
Tuples
2:15:34
Unpacking
2:18:21
Dictionaries
2:26:21
Emoji Converter
2:30:31
Functions
2:35:21
Parameters
2:39:24
Keyword Arguments
2:44:45
Return Statement
2:48:55
Creating a Reusable Function
2:53:42
Exceptions
2:59:14
Comments
3:01:46
Classes
3:07:46
Constructors
3:14:41
Inheritance
3:19:33
Modules
3:30:12
Packages
3:36:22
Generating Random Values
3:44:37
Working with Directories
3:50:47
Pypi and Pip
3:55:34
Project 1: Automation with Python
4:10:22
Project 2: Machine Learning with Python
4:58:37
Project 3: Building a Website with Django
Пожалуйста, подождите
|

Пожалуйста, подождите

Теги видео
|

Теги видео

python tutorial
python
python for beginners
python tutorial for beginners
learn python
python crash course
python 2019
python tutorial for beginners full
python (programming language)
python basics
python course
python from scratch
python full course
python language
python programming
python programming language
python programming tutorial
getting started with python
learn python programming
web development
mosh hamedani
machine learning
python 2020
ai
machinelearning
webdevelopment
Субтитры
|

Субтитры

subtitles menu arrow
  • enАнглийский
Скачать
00:00:04
В этом курсе вы узнаете все, что вам нужно, чтобы начать программирование на Python.
00:00:08
Python является одним из самых популярных языков программирования, и каждый день люди используют его для
00:00:12
классные вещи, такие как автоматизация, они используют его в искусственном интеллекте, а также
00:00:16
создание приложений и сайтов, таких как Instagram и Dropbox. Так что если вы ищете
00:00:20
для работы, Python для вас. В этом курсе я собираюсь научить вас всему
00:00:24
вам нужно начать с Python. Мы собираемся поговорить обо всех основных концепциях
00:00:28
в Python, а затем мы собираемся построить три проекта Python вместе.
00:00:32
Вот первый проект, который мы собираемся построить. Мы собираемся узнать, как создать этот красивый сайт
00:00:36
для воображаемого продуктового магазина. Здесь на главной странице мы можем увидеть все
00:00:40
продуктов в магазине, и у нас также есть область администратора для управления
00:00:44
склад. Мы собираемся построить это, используя популярный Python-фреймворк под названием Django.
00:00:48
Теперь, если вы никогда не создавали веб-сайт раньше, не волнуйтесь, я научу вас всему с нуля.
00:00:52
Вы также узнаете, как использовать Python в машинном обучении или искусственном интеллекте.
00:00:56
Таким образом, вы узнаете, как написать программирование на Python, которое будет предсказывать
00:01:00
музыка, которая нравится людям на основе их профиля. Так же, как YouTube
00:01:04
рекомендует видео на основе видео, которые вы смотрели ранее. Я также покажу вам
00:01:08
Python для автоматизации скучных повторяющихся задач, которые тратят ваше время.
00:01:12
Вы напишите программу на Python, которая будет обрабатывать тысячи электронных таблиц
00:01:16
менее чем за секунду. Я разработал этот курс Python для тех, кто хочет учиться
00:01:20
Python. Если вы новичок, не волнуйтесь, я буду держать вас за руку весь этот курс.
00:01:24
Вы не слишком стары или не слишком молоды, и Python очень прост в освоении. Вы можете написать свой первый
00:01:28
Программа Python буквально за секунды. Плюс я собираюсь дать вам много
00:01:32
упражнений, которые помогут вам создать уверенность в написании классных программ на Python.
00:01:36
Меня зовут Мош, я инженер-программист с двадцатилетним опытом работы
00:01:40
и я научил более 3 миллионов человек, как кодировать. Я очень рад учить тебя
00:01:44
Python в этом курсе. Поэтому я надеюсь, что вы остаетесь и изучаете эту прекрасную
00:01:48
мощный язык программирования.
00:01:52
В этом уроке я собираюсь показать вам, как скачать
00:01:56
и установите Python на свой компьютер. Итак, первое, что я хочу, чтобы ты сделал,
00:02:00
открыть браузер и перейти к Python
00:02:04
.org. На этой странице нажмите на загрузки,
00:02:08
здесь вы можете увидеть последнюю версию Python в настоящее время, на момент записи этого видео
00:02:12
последняя версия Python 3.7.2.
00:02:16
Скорее всего, в будущем, когда вы смотрите этот учебник, есть более новый
00:02:20
доступна версия Python, не волнуйтесь, все материалы, которые вы собираетесь изучать в этом курсе
00:02:24
будет применяться и к последней версии Python. Итак, давайте идти вперед
00:02:28
и загрузите Python 3, хорошо,
00:02:32
посмотрите на вашу папку загрузок, здесь у нас должен быть установщик Python 3
00:02:36
просто дважды щелкните по нему, если вы на Windows
00:02:40
Вы увидите этот флажок здесь, добавьте Python в
00:02:44
Python, это действительно важно, не забудьте поставить галочку в этом поле, иначе вы не сможете
00:02:48
следуйте этому уроку. Если вы на Mac,
00:02:52
вы увидите такой установщик, с помощью этого мастера установки мы собираемся установить Python 3
00:02:56
на нашем компьютере. Просто нажмите «Продолжить» и снова
00:03:00
и снова, и согласен с лицензионным соглашением, и
00:03:04
установить его, это займет несколько секунд, поэтому я собираюсь
00:03:08
приостановить запись.
00:03:12
Хорошо, мы успешно установили Python 3 на наш компьютер.
00:03:16
Давайте закроем это. Хорошо, теперь нам нужно установить
00:03:20
редактор кода, мы видим редактор кода, чтобы написать наш код, так же, как
00:03:24
как мы используем Microsoft Word для написания документов, мы используем редактор кода для написания
00:03:28
код. Сейчас существует так много редакторов кода, которые я собираюсь показать вам в этом
00:03:32
учебник PyCharm. Это один из самых популярных редакторов кода
00:03:36
для написания кода Python. Вы можете получить это от jetbrains.com
00:03:40
/ PyCharm. Теперь точнее пичарм
00:03:44
считается IDE, что сокращение от интегрированной разработки
00:03:48
среда. И это в основном редактор кода на стероидах,
00:03:52
у него есть некоторые дополнительные функции, которые упрощают написание кода. Так
00:03:56
давайте продолжим и загрузим PyCharm. Теперь здесь, на
00:04:00
Страница загрузки, вы можете увидеть две версии PyCharm, одна из которых является профессиональным дополнением
00:04:04
который имеет дополнительные функции, и вы должны платить за них. Другой является
00:04:08
Community Edition, это абсолютно бесплатно, и это то, что мы собираемся использовать в этом руководстве.
00:04:12
Итак, скачайте и это тоже.
00:04:16
Теперь, еще раз посмотрите на вашу папку загрузок, еще раз у вас должен быть pycharm
00:04:20
поэтому дважды щелкните по этому, теперь, если вы
00:04:24
в Windows вы увидите мастер установки, просто нажмите Далее, Далее, Далее
00:04:28
пока вы не установите pycharm. Если вы на Mac, вам нужно перетащить этот значок
00:04:32
в папку приложений, так что перетащите,
00:04:36
Хорошо, теперь давайте дважды щелкните по нему, чтобы запустить его,
00:04:40
при первом запуске pycharm мы получим это предупреждение, потому что это приложение
00:04:44
что мы скачиваем из интернета. Итак, давайте продолжим и откроем это,
00:04:48
Далее вы увидите это диалоговое окно для импорта некоторых настроек, оставьте это для
00:04:52
не импортируйте настройки, это не имеет значения. Хорошо,
00:04:56
На этой странице выберите Я никогда не использовал PyCharm, вы можете увидеть ключевое слово
00:05:00
ярлыки, которые могут быть полезны в будущем, просто примите это, и внизу,
00:05:04
нажмите следующую кнопку. А потом еще раз,
00:05:08
еще раз, а затем, наконец, начать использовать pycharm.
00:05:12
Итак, вот главная страница PyCharm каждый раз, когда вы открываете
00:05:16
это, нажмите на создать новый проект,
00:05:20
это место для нашего проекта, давайте назовем наш проект Hello
00:05:24
Мир. Теперь, прежде чем нажать и создать, разверните
00:05:28
этот пункт здесь, убедитесь, что базовый интерпретатор установлен на Python
00:05:32
3. Python интерпретатор в основном программа
00:05:36
который знает, как выполнить код Python, он будет знать, как интерпретировать
00:05:40
или переведите инструкции Python в инструкции, понятные компьютеру.
00:05:44
Теперь компьютеры Mac по умолчанию поставляются с более старыми
00:05:48
установка Python, это Python 2, считается устаревшим
00:05:52
Это означает, что он больше не поддерживается и не поддерживается. Так что раньше мы скачивали
00:05:56
Python 3, убедитесь, что он установлен на Python 3, если нет
00:06:00
из этого списка выберите Python 3.7.
00:06:04
Хорошо, теперь давайте продолжим и создадим этот проект,
00:06:12
Теперь здесь щелкните правой кнопкой мыши на
00:06:16
Папка Hello World и перейдите в новый
00:06:20
Файл Python, назовите этот файл app.py.
00:06:24
Таким образом, по соглашению, все файлы Python должны иметь это
00:06:28
Py расширение. Хорошо, давайте идти вперед,
00:06:32
Теперь давайте свернем эту панель проекта, нажав здесь, и напишем
00:06:36
первая программа на питоне. Просто наберите print, pr
00:06:40
int, все в нижнем регистре, открывать и закрывать скобки,
00:06:44
и внутри этих скобок добавьте цитаты, которые мы
00:06:48
теперь можно использовать одинарные или двойные кавычки
00:06:52
между кодами напишите свое имя. Я Мош Хамедани, так
00:06:56
здесь, так что это ваше первое программирование на Python. С этим куском кода
00:07:00
Вы можете напечатать свое имя на экране. Теперь, чтобы запустить это, иди
00:07:04
в верхней части, под меню Run, нажмите Run,
00:07:08
Также обратите внимание, что есть ярлык, связанный с этой командой, когда
00:07:12
Я программирую, я всегда использую ярлыки, потому что это увеличивает мою производительность.
00:07:16
Так что здесь, на компьютере Mac, ярлык управления, опция и
00:07:20
На винде это другое. Итак, давайте сделаем это сейчас
00:07:24
он спрашивает, где вы хотите запустить это, нажмите на приложение,
00:07:28
внизу, вы должны увидеть это маленькое окно терминала, это
00:07:32
небольшое окно в нашу программу, так что здесь вы можете увидеть наши результаты для
00:07:36
выход для нашей программы. В будущем, как вы узнаете больше Python, вы будете
00:07:40
возможность создавать приложения, которые имеют графический интерфейс пользователя или Gooey.
00:07:44
Это немного сложно, поэтому сейчас мы будем использовать этот маленький
00:07:48
Окно терминала, чтобы увидеть результаты нашей программы. Итак, как вы можете видеть, меня зовут
00:07:52
напечатано здесь, теперь, когда вы печатаете код, это окно может мешать так
00:07:56
всегда изменяйте его размер или уменьшайте его
00:08:00
значок здесь, так что это была наша первая программа на Python. Сейчас
00:08:04
если вы не видите результат, который я показал вам в этом видео, используйте поле для комментариев ниже и
00:08:08
скажите мне, с какой ошибкой вы столкнулись, я сделаю все возможное, чтобы помочь вам двигаться вперед.
00:08:16
В этом уроке по Python мы собираемся поднять эту программу на новый уровень и сделать ее более интересной.
00:08:20
Итак, я собираюсь показать вам, как рисовать собачью шерсть. Теперь как часть
00:08:24
Из этого урока вы узнаете, как выполняется код Python, а также узнаете
00:08:28
о нескольких условиях программирования. Так нажмите Enter, и
00:08:32
в строке 2 напишите еще одно заявление на печать, поэтому печатайте, открывайте и закрывайте
00:08:36
Скобка, добавьте цитату, теперь здесь вы хотите нарисовать собаку.
00:08:40
Итак, добавьте o, это голова нашей собаки, а затем
00:08:44
4 дефиса. Итак, это тело.
00:08:48
Хорошо, теперь еще один раз печатать заявление с
00:08:52
цитаты, теперь нам нужно нарисовать ноги. Так что добавьте пробел.
00:08:56
Следуйте за этим 4 вертикальными полосами. Ну вот так,
00:09:00
так вот маленькая воображаемая точка. Теперь давайте
00:09:04
запустить эту программу и посмотреть, что мы получаем. Так что в правом верхнем углу вы должны увидеть эту кнопку воспроизведения,
00:09:08
нажмите, что, так что у нас есть имя и
00:09:12
прямо под этим у нас есть воображаемая собака. Теперь, что вам нужно понять
00:09:16
здесь, это то, что наш код Python исполняется построчно
00:09:20
от верхней. Так что раньше я рассказывал вам про интерпретатор Python
00:09:24
это программа, которая знает, как переводить или интерпретировать
00:09:28
наш код Python в инструкции, которые компьютер может понять.
00:09:32
Поэтому, когда мы запускаем эту программу, нажав эту программу здесь,
00:09:36
интерпретатор python начинает выполнение или запуск нашей программы
00:09:40
построчно сверху. Итак, сначала он выполняет строку 1,
00:09:44
затем переходит на строку 2 и так далее. Так вот как питон
00:09:48
программы исполняются. Теперь позвольте мне показать вам что-нибудь классное. Давайте добавим
00:09:52
еще одно печатное заявление с цитатами
00:09:56
между цитатами добавьте звездочку или звездочку, например
00:10:00
этот. Теперь после цитаты и перед скобками,
00:10:04
добавьте пробел, еще раз, добавьте звездочку,
00:10:08
пространство, 10. Что здесь происходит? Что ж,
00:10:12
везде у нас есть цитаты, как здесь или здесь
00:10:16
мы определяем строку, строка это термин программирования, который означает
00:10:20
последовательность символов, поэтому здесь у нас есть строка, у нас также есть
00:10:24
строка в строке 3, а также строка 2 и строка 1.
00:10:28
Теперь здесь, мы умножаем строку на
00:10:32
число 10. Так что это оператор умножения, так же, как умножение
00:10:36
Оператор у нас в математике. Так что с этим куском кода мы можем
00:10:40
Нарисуйте 10 звездочек на терминале, позвольте мне показать вам. Итак, давайте запустим это
00:10:44
запрограммируйте еще раз, вот и все. Итак, у нас есть 10
00:10:48
звездочки. Теперь, что у нас здесь, этот кусок кода здесь,
00:10:52
называется выражением. Выражение это кусок
00:10:56
код, который производит значение. Так, когда интерпретатор Python
00:11:00
пытается выполнить строку 4, сначала он оценит
00:11:04
код, который мы помещаем между скобками, чтобы мы могли оценить наши выражения
00:11:08
Наше выражение даст 10 звездочек, а затем
00:11:12
эти звездочки будут напечатаны на терминале. Теперь как упражнение
00:11:16
Вы можете использовать эти операторы печати, чтобы нарисовать другую форму, вы можете нарисовать сердце,
00:11:20
мяч, как хочешь. Увидимся в следующем уроке.
00:11:24
Один из вопросов, которые я часто получаю на своем канале:
00:11:28
сколько времени займет изучение Python и подготовка к работе? Ну нет ни одного
00:11:32
ответ. Это действительно зависит от вас и от того, сколько усилий и усилий вы хотите приложить
00:11:36
в это. Но я бы сказал, если вы проводите 2 часа каждый день
00:11:40
примерно через 3 месяца вы сможете написать
00:11:44
базовые программы на Python, но, честно говоря, это не дает вам работу.
00:11:48
Чтобы получить работу, нужно специализироваться в одной области,
00:11:52
для чего вы хотите использовать python? Вы хотите создавать веб-приложения или
00:11:56
настольные приложения? Или вы хотите использовать его в машинном обучении и искусственном интеллекте?
00:12:00
Поэтому, чем бы вы ни занимались, вам нужно пройти дополнительные курсы.
00:12:04
Например, если вы хотите стать веб-разработчиком в дополнение к обучению
00:12:08
Python, вы также должны узнать о HTML, некоторые CSS, некоторые
00:12:12
JavaScript и Django, который является популярной платформой Python
00:12:16
для создания веб-приложений. Изучение всех этих вещей приведет вас к другому
00:12:20
6 месяцев, так что всего вам нужно 9-12 месяцев, чтобы стать
00:12:24
работа готова. На этом этапе вы можете получить работу младшего разработчика с
00:12:28
Зарплата около 50-60 тысяч долларов в год. Теперь, когда вы работаете больше
00:12:32
по мере того, как вы делаете больше проектов Python, ваше резюме начинает собираться и
00:12:36
Вы можете попросить 100 000 долларов в год или 120 000 долларов
00:12:40
год, в зависимости от того, где вы находитесь, какая компания, какой географический район,
00:12:44
это действительно зависит, нет однозначного ответа. Так вы рады
00:12:48
изучить Python и начать этот путь? Если да, я бы рекомендовал вам
00:12:52
взять на себя обязательство и проводить 2 часа каждый день, практикуя
00:12:56
питон. И используйте поле для комментариев ниже и дайте мне знать, почему вы учитесь
00:13:00
Python, что ты хочешь с этим делать? Какая твоя работа мечты? Я хотел бы услышать вашу историю.
00:13:08
В этом уроке по Python вы узнаете о переменных, которые являются одним из самых фундаментальных
00:13:12
понятия в программировании, они не специфичны для Python, они существуют
00:13:16
практически во всех языках программирования. Мы используем переменные
00:13:20
временно хранить данные в памяти компьютера. Вот пример,
00:13:24
давайте напечатаем цену = 10, когда Python
00:13:28
интерпретатор выполняет этот код, он выделит некоторую память, затем он сохранит
00:13:32
число 10 в этой памяти, и, наконец, он прикрепит это
00:13:36
ценник в этом месте памяти. Как метахор
00:13:40
представьте, у нас есть коробка. В этой коробке у нас есть номер 10
00:13:44
и цена - это этикетка, которую мы наносим на коробку. Теперь мы можем использовать этот ярлык
00:13:48
в любом месте нашей программы, чтобы получить доступ к значению, которое мы имеем в этом поле.
00:13:52
Это очень упрощенное объяснение. Итак, давайте
00:13:56
распечатать цену на терминале. Распечатать, сейчас мы не собираемся
00:14:00
добавить цитаты, потому что если мы поместим цитаты здесь, мы увидим текст
00:14:04
цена на терминал. Теперь значение переменной цены.
00:14:08
Итак, поместите его в цитаты и введите цену,
00:14:12
Теперь давайте запустим эту программу еще раз, вот и все. Итак, мы видим 10,
00:14:16
на терминале. Так вот, как мы определяем переменные, мы
00:14:20
начать с идентификатора, который является именем нашей переменной, затем,
00:14:24
знак равенства и, наконец, значение. Теперь точнее, когда
00:14:28
это число 10 будет сохранено в памяти, сначала оно будет
00:14:32
быть преобразованным в этот двоичный файл для представления. Итак, это число 10,
00:14:36
находится в десятичной системе, которая имеет все цифры от 0 до 9.
00:14:40
Компьютеры не понимают все эти цифры, они только понимают
00:14:44
0 и 1. Поэтому, когда мы храним номер 10 в памяти компьютера
00:14:48
Сначала он будет преобразован в его двоичное представление, которое будет
00:14:52
куча 0 и 1, как 001, 001, что угодно
00:14:56
Я не знаю. Затем он будет сохранен в памяти компьютера. Так,
00:15:00
давайте возьмем эту программу на следующий уровень. На второй линии мы можем
00:15:04
обновите значение этой переменной цены, чтобы мы могли ее сбросить
00:15:08
на новое значение, как 20, теперь, когда мы запускаем нашу программу,
00:15:12
мы должны увидеть 20, потому что, как я уже говорил, интерпретатор Python выполняет наши
00:15:16
код построчно сверху. Итак, сначала мы устанавливаем
00:15:20
цена до 10, затем мы сбрасываем ее до 20, и, наконец, мы
00:15:24
распечатайте его на терминале, давайте запустим терминал, так что,
00:15:28
мы видим здесь 20, хорошо? Теперь эти
00:15:32
числа, которые мы имеем здесь, являются целыми числами без десятичной точки.
00:15:36
В программировании мы называем эти числа целыми числами.
00:15:40
Но целое число - это число без десятичной точки. Мы также можем использовать
00:15:44
числа с десятичной точкой, например, в строке 2, мы можем определить
00:15:48
другая переменная называется рейтинг и установить его в число
00:15:52
4.9. Теперь в программировании мы называем этот вид числа
00:15:56
число с плавающей запятой для краткости. Итак, у нас есть целые числа
00:16:00
и плавает. Мы также можем определить переменную и установить
00:16:04
это строка, например, имя равно
00:16:08
Мош, у нас также есть другой вид значения, которое называется логическим,
00:16:12
который может быть правдой или ложью. Они строки да и нет на английском языке.
00:16:16
Вот пример, я собираюсь определить переменную, подчеркну
00:16:20
опубликовано, поэтому мы используем подчеркивание для разделения
00:16:24
несколько слов в названии нашей переменной. Мы установили это
00:16:28
правда или ложь. Это
00:16:32
булевы значения. Теперь обратите внимание, что Python это случай
00:16:36
чувствительный язык, что означает, что он чувствителен к строчным и прописным буквам.
00:16:40
Поэтому при определении переменных мы всегда должны использовать
00:16:44
строчные буквы, но здесь false и true являются специальными ключевыми словами в
00:16:48
язык, поэтому, если мы пишем его с маленькой буквы F, Python не
00:16:52
понимать это. Вы можете видеть, что у нас есть красное подчеркивание здесь, которое указывает на ошибку.
00:16:56
Обязательно пишите это с заглавной буквы F, или если вы хотите установить для этого значение true,
00:17:00
убедитесь, что Т является столицей, поэтому в этом
00:17:04
Программа, вы храните простые значения в памяти нашего компьютера. просто
00:17:08
значения могут быть числами, которые могут быть целыми числами или числами с плавающей запятой
00:17:12
или они могут быть строками или логическими значениями. Но в Python
00:17:16
мы также можем хранить сложные значения, такие как списки и значения. И вот что я собираюсь показать вам
00:17:20
в будущем. Поэтому, прежде чем идти дальше, я хочу, чтобы ты
00:17:24
сделать небольшое упражнение. Представьте, что мы собираемся написать программу для больницы.
00:17:28
Итак, мы проверим пациента по имени Джон Смит. Он
00:17:32
20 лет и новый пациент. Я хочу, чтобы вы определили 3 переменные здесь,
00:17:36
для его имени, его возраста и другой переменной
00:17:40
ибо, если это новый или существующий пациент. Так что пауза видео и потратить один
00:17:44
минута на это упражнение. Когда вы закончите, вернитесь, продолжайте и посмотрите мое решение.
00:17:48
Хорошо, так что здесь нам нужно
00:17:52
три переменные, первая - имя пациента,
00:17:56
мы установили это Джону Смиту. Мы также можем
00:18:00
назовите это полное имя, оба они являются допустимыми именами для наших переменных.
00:18:04
Вторая переменная для возраста нашего пациента. Так возраст
00:18:08
20, и, наконец, нам нужна переменная, чтобы сказать, если это новый
00:18:12
или существующий пациент. Вот где мы можем использовать логическое значение.
00:18:16
Итак, мы определяем переменную, является новым и
00:18:20
мы установили это на истину.
00:18:24
Итак, вы научились печатать
00:18:28
сообщения в окне терминала. В этом уроке я собираюсь показать вам, как
00:18:32
получать входные данные от пользователя. Итак, мы собираемся написать небольшую программу, которая спрашивает
00:18:36
имя пользователя, а затем мы напечатаем приветственное сообщение
00:18:40
для этого пользователя. Поэтому вместо печати мы будем использовать
00:18:44
вход. Теперь оба эти ввода и печати
00:18:48
являются функциями, которые встроены в Python. Как метафора думаю
00:18:52
пульта дистанционного управления телевизором. На этом пульте у нас есть куча
00:18:56
кнопки, это функции, встроенные в телевизор, вы можете включить его,
00:19:00
выключи, поменяй громкость и тд. В Python у нас также есть
00:19:04
функции для общих задач, таких как печать сообщений, получение ввода,
00:19:08
и так далее. Итак, мы собираемся использовать функцию ввода, теперь всякий раз, когда мы
00:19:12
есть эти скобки, мы будем говорить, что мы звоним или выполняем
00:19:16
эта функция, как нажатие кнопки на пульте дистанционного управления. Итак, мы
00:19:20
собираюсь вызвать функцию ввода и между скобками
00:19:24
мы хотим добавить строку для печати чего-либо на терминале,
00:19:28
как тебя зовут? С вопросительным знаком, за которым следует
00:19:32
пространство. Вы поймете, почему через секунду. Так что эта функция ввода
00:19:36
напечатает это сообщение на терминале, а затем будет ждать, пока пользователь
00:19:40
введите значение. Все, что пользователь вводит в эту функцию ввода, будет
00:19:44
вернуть. Так что теперь мы можем получить это значение и сохранить его в памяти, используя переменную.
00:19:48
Таким образом, мы получаем результат и помещаем его в переменную
00:19:52
название. Хорошо? Сейчас на второй строчке
00:19:56
мы хотим напечатать сообщение, как Привет Джон или Привет Мош или что-то еще, так что,
00:20:00
печать, цитаты привет с пробелом,
00:20:04
теперь после цитаты мы хотим динамически распечатать
00:20:08
что мы имеем в переменной имени. Итак, мы имели
00:20:12
знак плюс, а затем имя. Итак, у нас есть
00:20:16
Привет, который является строкой, мы объединяем или
00:20:20
объединяя строку с другой строкой, это то, что мы имеем
00:20:24
в переменной имени. Итак, вот еще один пример
00:20:28
выражение. Помните, что такое выражение? Это кусок кода, который
00:20:32
использует значение. Так что это выражение объединяет или объединяет
00:20:36
2 строки Давайте запустим эту программу и посмотрим, что произойдет. Так беги
00:20:40
хорошо, вот вопрос, как тебя зовут? Мош,
00:20:44
Теперь обратите внимание, что ранее мы добавили пробел после знака вопроса, мы
00:20:48
сделал это, поэтому здесь, в окне терминала курсор
00:20:52
отделен от знака вопроса, иначе это было бы так близко. Итак, давайте наберем
00:20:56
что бы здесь ни было, плюс введите, теперь мы получаем это сообщение, Привет, Мош.
00:21:00
Теперь вот небольшое упражнение для вас. Я хочу, чтобы вы продлили эту программу
00:21:04
и задать два вопроса. Сначала все имя человека, а затем
00:21:08
их любимый цвет. А затем распечатать сообщение, как Мош любит
00:21:12
синий. Поэтому сделайте паузу в видео, выполните это упражнение, а затем вернитесь и продолжайте смотреть.
00:21:20
Хорошо, вот первый вопрос сразу после этого,
00:21:24
все функции ввода еще раз, на этот раз мы зададим другой вопрос.
00:21:28
Какой твой любимый цвет?
00:21:32
Теперь мы получаем новое значение и сохраняем его в переменной
00:21:36
называется цвет, или вы могли бы назвать это любимым подчеркиванием.
00:21:40
цвет. Либо работает. И наконец мы собираемся изменить
00:21:44
что мы передаем в функцию печати, поэтому сначала мы печатаем имя
00:21:48
затем мы соединяем это со строкой, здесь мы собираемся
00:21:52
типа лайков, мы также ставим один пробел перед и
00:21:56
после лайков, и еще раз мы объединяем это.
00:22:00
С любимым цветом. Итак, любимый цвет,
00:22:04
теперь давайте запустим эту программу, так как вас зовут
00:22:08
Мошь входи, любимый цвет, синий, входи,
00:22:12
мы получаем это сообщение, Мош любит синий.
00:22:16
Эй, ребята, Мош, я просто хотел, чтобы вы знали, что
00:22:20
вам действительно не нужно ничего запоминать в этом курсе, потому что я собрал шпаргалку
00:22:24
с краткими примечаниями. Таким образом, вы можете быстро просмотреть материалы этого курса.
00:22:28
Ссылка ниже этого видео. Поэтому я сделал все возможное, чтобы создать
00:22:32
лучший возможный курс Python на Youtube. И я действительно ценю
00:22:36
это если вы поддерживаете мою тяжелую работу, любя это видео и делиться им с
00:22:40
другие, чтобы они могли учиться. И не забудьте подписаться на мой канал, для более
00:22:44
учебники, как это. Хорошо, теперь давайте перейдем к следующему уроку.
00:22:52
В этом уроке по Python мы напишем программу, в которой будет задан год, в котором мы родились
00:22:56
в, а затем он рассчитает наш возраст и распечатает его на терминале.
00:23:00
Итак, давайте начнем с нашей функции ввода, ввода
00:23:04
давайте напишем рождение здесь, а затем двоеточие,
00:23:08
и пробел. Теперь давайте получим возвращаемое значение и сохраним его в переменной,
00:23:12
называется Birth_year.
00:23:16
Итак, как я уже говорил ранее, мы используем подчеркивание для разделения нескольких слов
00:23:20
Далее нам нужно рассчитать возраст, поэтому мы определим еще один
00:23:24
переменная называется возраст, и здесь мы делаем некоторую базовую математику,
00:23:28
В настоящее время мы находимся в 2019 году, поэтому давайте напишем выражение
00:23:32
как это. 2019 - рождение
00:23:36
год. Теперь, наконец, давайте распечатать
00:23:40
возраст на терминале. Давайте запустим нашу программу и посмотрим, что произойдет.
00:23:44
Итак, мой год рождения 1982, введите,
00:23:48
К сожалению, мы получили ошибку, что здесь происходит? Так
00:23:52
всякий раз, когда вы видите это сообщение, это означает, что с вашей программой что-то не так. С информацией
00:23:56
Здесь мы можем точно определить, где произошла ошибка. Так,
00:24:00
рядом с файлом вы можете увидеть файл, сгенерировавший эту ошибку, в данном случае
00:24:04
это app.py. Так
00:24:08
В настоящее время наша программа имеет только один файл, но часто это сложные программы.
00:24:12
сотни или даже тысячи файлов. Итак, в этом файле
00:24:16
в строке 2, это где мы получили эту ошибку, и правильно
00:24:20
ниже мы видим фрагмент кода, который сгенерировал эту ошибку.
00:24:24
Так вот где мы рассчитываем возраст, и прямо под
00:24:28
что вы можете увидеть тип ошибки. В этом случае у нас есть ошибка типа, и вот
00:24:32
сообщение. Неподдерживаемые типы операндов для
00:24:36
вычитание. Инт и ул.
00:24:40
Таким образом, int это сокращение от целого числа, и это представляет собой целое число
00:24:44
а str это сокращение от string, поэтому здесь мы вычитаем
00:24:48
строка из целого числа, и Python не знает, что с ней делать.
00:24:52
Позволь мне объяснить. Поэтому я собираюсь закрыть окно терминала. Так после
00:24:56
первая строка, которую мы выполнили, у нас есть этот набор переменных год рождения
00:25:00
в строку, поэтому все, что мы печатаем в терминале, всегда
00:25:04
обрабатывается как строка, даже если вы введете число, другими словами,
00:25:08
когда мы запустим эту программу, эта переменная года рождения будет установлена
00:25:12
в строку, с четырьмя символами.
00:25:16
1982. Эта строка отличается от фактического числа
00:25:20
1982. Один - целое число, а другой - строка.
00:25:24
Правильно? Итак, вернемся к строке 2, где это
00:25:28
произошла ошибка. Во время выполнения, что означает, когда мы запускаем нашу программу
00:25:32
это выражение в правой части оператора присваивания
00:25:36
будет выглядеть так 2019 -
00:25:40
строка 1982. Python не знает как
00:25:44
интерпретировать или как оценить это выражение. Чтобы исправить эту проблему
00:25:48
нам нужно преобразовать этот 1982 в целое число
00:25:52
и тогда мы сможем вычесть его из 2019 года и что
00:25:56
это просто. Итак, вы узнали о двух встроенных функциях
00:26:00
один печатается, другой вводится. У нас есть несколько других функций
00:26:04
для преобразования значений в разные типы. Итак, мы имеем
00:26:08
int для преобразования строки в целое число, мы также имеем
00:26:12
float для преобразования строки в число с плавающей точкой или число
00:26:16
с десятичной точкой. И у нас также есть bool для преобразования строки
00:26:20
в логическое значение. Чтобы исправить эту проблему,
00:26:24
нам нужно вернуться на линию 2,
00:26:28
и передайте эту переменную года рождения функции int следующим образом.
00:26:32
в скобках, вот так
00:26:36
поэтому мы передаем эту строку в функцию int, int преобразует ее в itneger
00:26:40
и тогда интерпретатор Python сможет оценить это выражение.
00:26:44
Теперь давайте запустим эту программу еще раз, поэтому рождение
00:26:48
год 1982, введите, поэтому я
00:26:52
37 лет В Python у нас есть полезная функция
00:26:56
для получения типа переменных, например, давайте напечатаем тип
00:27:00
года рождения, поэтому сразу после строки 1,
00:27:04
давайте напишем, теперь здесь мы будем называть другую встроенную функцию,
00:27:08
называется типа, а теперь давайте пройдем рождение
00:27:12
год, ладно, теперь аналогично после строки
00:27:16
3, давайте также напечатаем тип возраста, так
00:27:20
тип печати возраст.
00:27:24
Хорошо? Итак, давайте запустим нашу программу, так что год рождения еще один
00:27:28
время, 1982, хорошо, вот результат
00:27:32
поэтому тип года рождения, как вы можете видеть, является классом
00:27:36
из строк или строк, мы смотрим на классы в будущем, так
00:27:40
пока не беспокойтесь о них, а также под ними вы можете увидеть тип
00:27:44
переменная возраста является целым или целым числом. Так
00:27:48
вот что тебе нужно отнять. Всякий раз, когда вы используете функцию ввода,
00:27:52
вы всегда получаете строку, поэтому, если вы ожидаете числовое значение
00:27:56
Вы всегда должны конвертировать эту строку в целое число или
00:28:00
поплавок. Итак, вот небольшое упражнение для вас. Я хочу, чтобы вы написали программу
00:28:04
спросите пользователя его вес, а затем преобразовать его в килограммы и распечатать
00:28:07
на терминале. Так что сделайте паузу в видео, сделайте упражнение и когда будете готовы, вернитесь
00:28:12
смотреть это.
00:28:16
Хорошо, так что давайте использовать нашу функцию ввода и спросить
00:28:20
для веса в фунтах
00:28:24
здесь мы получаем вес в фунтах или фунтах
00:28:28
теперь нам нужно перевести это в килограммы, это очень легко
00:28:32
мы определили другую переменную weight_kg
00:28:36
мы устанавливаем это в weight_lbs
00:28:40
времена 0,45.
00:28:44
И напоследок напишем вес подчеркивания
00:28:48
кг. Давайте запустим эту программу на Python и посмотрим, что произойдет. Так
00:28:52
мой вес 160, хорошо, еще раз мы получили ошибку,
00:28:56
не может умножить последовательность на не тип int
00:29:00
плавать. Как я уже говорил, эта функция ввода возвращает
00:29:04
строка, поэтому мы не можем умножить строку на число с плавающей запятой.
00:29:08
Python не знает, что с этим делать. Так что в этом случае мы должны преобразовать это число
00:29:12
на целое число или число с плавающей запятой, а затем умножить на 0,45.
00:29:16
Итак, давайте вызовем функцию int.
00:29:20
И передать вес подчеркивают кг.
00:29:24
И запустить нашу программу еще раз, 160
00:29:28
хорошо, так что я 72 кг.
00:29:36
В этом уроке вы узнаете больше о строках Python.
00:29:40
Итак, я определил эту переменную курса и установил ее на Python для начинающих
00:29:44
ранее я говорил вам, что вы можете использовать как одинарные, так и двойные кавычки
00:29:48
определить строку, но бывают случаи, когда вам приходится использовать конкретную форму,
00:29:52
в противном случае вы столкнетесь с проблемами. Вот пример. Представь, что ты хотел
00:29:56
измените эту строку в курс Pythons для начинающих.
00:30:00
Итак, мы хотим добавить апостроф, как это,
00:30:04
Курс для начинающих. Вы можете сразу сказать, что это происходит
00:30:08
сумасшедший, потому что наша строка начинается здесь, а затем заканчивается здесь,
00:30:12
все эти символы, которые мы имеем здесь после второго апострофа
00:30:16
Интерпретатор Python не знает, кто они. Таким образом, чтобы решить эту проблему
00:30:20
нам нужно использовать двойные кавычки, чтобы определить нашу строку, чтобы мы могли иметь
00:30:24
одиночная кавычка в середине строки. Итак, давайте изменим это
00:30:28
чтобы двойные кавычки, теперь вы можете видеть, что добавляет еще одну двойную кавычку, чтобы закрыть его,
00:30:32
Вы должны удалить это вручную, а также еще раз
00:30:36
в начале строки нам нужно добавить еще одну двойную кавычку. Сейчас
00:30:40
Вы можете увидеть, что ошибка исчезла, поэтому если вы печатаете курс
00:30:44
мы видим курс Python для начинающих.
00:30:48
Красивая. Теперь давайте скажем, что мы не хотим этого апостроф здесь, поэтому мы имеем
00:30:52
Python для начинающих, но мы хотим поместить начинающих в
00:30:56
двойные кавычки. Еще раз, если вы добавите здесь двойную кавычку, интерпретатор Python получит
00:31:00
путать, потому что предполагает, что вторая двойная кавычка указывает на то, что
00:31:04
конец строки, поэтому он не знает, что это за символы, поэтому для решения
00:31:08
нам нужно изменить наши двойные кавычки на одинарные кавычки
00:31:12
как это. И тогда мы можем добавить двойные кавычки в середине
00:31:16
строки. Теперь давайте запустим эту программу, вот и все.
00:31:20
Итак, мы получаем Python для начинающих. Так что это случаи
00:31:24
для использования одинарных или двойных кавычек. Теперь во всех примерах
00:31:28
Я уже показывал вам, что мы имеем дело только с короткими строками, но что если вы захотите определить
00:31:32
строка, которая имеет несколько длин? Например, что если вы хотите определить строку
00:31:36
для сообщения, которое мы отправляем по электронной почте. В этом случае нам нужно использовать
00:31:40
тройные кавычки. Так. Мы удаляем это.
00:31:44
Теперь мы добавляем три кавычки, так что 1, 2, 3, вот и все,
00:31:48
Итак, у нас есть три цитаты, чтобы начать нашу строку и три
00:31:52
прекратить это. Опять же, эти кавычки могут быть одинарными или двойными.
00:31:56
Хорошо? Теперь, с этим мы можем определить строку, которая охватывает
00:32:00
несколько строк. Например, мы можем сказать привет Джон
00:32:04
вот наше первое письмо к вам. Спасибо,
00:32:08
Служба поддержки. Как это.
00:32:12
Теперь давайте запустим эту программу и вот
00:32:16
результат. Итак, мы получаем эту красивую мульти-линию
00:32:20
строка. Теперь давайте изменим это обратно на что-то простое
00:32:24
Итак, мы можем посмотреть на другие характеристики строк и Python.
00:32:28
Поэтому я собираюсь использовать одинарные кавычки и установить название курса на Python
00:32:32
для начинающих. Теперь здесь мы будем использовать квадрат
00:32:36
скобки для получения символа и заданного индекса в этой строке.
00:32:40
Позволь мне показать тебе. Таким образом, чтобы получить первый символ, мы используем квадратные скобки
00:32:44
и введите 0. Таким образом, индекс первого символа
00:32:48
в строке равно 0. Другими словами, это как Python
00:32:52
строки проиндексированы. 0, 1, 2, 3, 4 и т. Д.
00:32:56
Таким образом, индекс первого символа равен 0, второй символ
00:33:00
1 и так далее. Итак, позвольте мне удалить это и запустить эту программу
00:33:04
мы получаем р. Мы также можем использовать отрицательный
00:33:08
Индекс здесь. И это одна из особенностей, которых у нас нет в других языках программирования
00:33:12
насколько я знаю. Таким образом, у нас есть отрицательный индекс, мы можем получить символы
00:33:16
началось с конца. Так что, если я передам отрицательный 1 здесь,
00:33:20
Предполагая, что 0 является индексом первого символа
00:33:24
минус 1 - индекс последнего символа. Поэтому, когда мы бежим
00:33:28
эту программу мы должны увидеть с. Давайте запустим это, вот и все,
00:33:32
мы получим s, если мы передадим отрицательный 2, это вернет
00:33:36
второй персонаж от конца. Давайте попробуем еще раз,
00:33:40
теперь мы получаем R, потому что это второй символ в конце.
00:33:44
Хорошо? Поэтому уделите пристальное внимание синтаксису в квадратных скобках
00:33:48
потому что довольно часто это тема для онлайн-тестов Python
00:33:52
или университетские экзамены, так что если вы готовитесь к тесту на питона,
00:33:56
не забудьте посмотреть этот урок еще раз и понять, как именно
00:34:00
этот синтаксис квадратных скобок работает, мы также можем использовать аналогичные
00:34:04
синтаксис для извлечения нескольких символов вместо 1 символа.
00:34:08
Например, если мы введем 0,
00:34:12
двоеточие 3, интерпретатор Python вернет все символы
00:34:16
начиная с этого индекса вплоть до этого
00:34:20
второй индекс, но он не возвращает символ в этом индексе.
00:34:24
Другими словами, вернемся к этим показателям
00:34:28
так что у вас есть 0, 1, 2, 3 и так далее. Когда вы запускаете эту программу.
00:34:32
Интерпретатор Python вернет символы, начиная с
00:34:36
индекс 0 вплоть до индекса 3,
00:34:40
но исключает символ и индекс 3,
00:34:44
поэтому, когда мы запустим эту программу на Python, мы увидим pint (?). Позвольте мне показать вам, поэтому мы собираемся
00:34:48
удали эту строку, запусти эту программу, вот и все.
00:34:52
Мы получаем пинту. Теперь здесь у нас также есть значения по умолчанию для
00:34:56
начальный и конечный индекс. Так что, если мы не поставляем
00:35:00
В конце индекса Python вернет все символы в конец строки.
00:35:04
Давайте взглянем. Итак, запустите эту программу, вот так
00:35:08
Python для начинающих. Но если вы измените начальный индекс на 1,
00:35:12
this will exclude the first character so when we
00:35:16
run this program, we see ython so p is removed.
00:35:20
Okay? Now similarly we have a default value for the
00:35:24
start index, so if we don't supply the start index
00:35:28
but add an end index like 5. Python interpreter will assume
00:35:32
0 as the start index, so, let's run
00:35:36
this program, there you go, we get pytho.
00:35:40
Now what if we leave both the start and end
00:35:44
index? Well, I told you? Now in this case 0 will be assumed
00:35:48
as the start index, and the length of the string will assume
00:35:52
as the end index. So with this syntax, you can basically copy
00:35:56
or clone a string. In other words, if I define
00:36:00
another variable here, let's call it another and set it to course
00:36:04
square brackets with just a colon, now this expression will
00:36:08
return all the characters in the course variable so
00:36:12
variable will be copy of our first variable. Let's take a look, so,
00:36:16
let's print another, and load our
00:36:20
program there you go, we get Python for beginners. So once again
00:36:24
the square bracket syntax is pretty important if you're preparing for online
00:36:28
python tests, or college exams, make sure to watch this tutorial again.
00:36:32
Now here's a little exercise for you. I'm going to delete all this code
00:36:36
define a variable, called name, and set it to Jennifer.
00:36:40
Now when we print name
00:36:44
of 1: negative 1
00:36:48
what do you think we're going to see on the terminal? I want you to use your knowledge
00:36:52
to tell what we're going to see on the terminal, we're now running this program. Так
00:36:56
pause the video, think about it for a few seconds, then come back and continue watching.
00:37:04
So this expression will return the characters starting from
00:37:08
index 1 which is the second character
00:37:12
all the way to the first character from the end, but excluding
00:37:16
the character at this index. In this case, the first character from the
00:37:20
in is r, so r will be excluded, in other words we're going to see
00:37:24
all the characters starting from e all the way
00:37:28
to the second e. Let's take a look. So I'm going to run this program
00:37:32
there you go. This is what we get,
00:37:36
I hope you guessed it right.
00:37:40
In this tutorial, we're going to look at
00:37:44
formatted strings in Python programming language. Formatted strings are
00:37:48
particularly useful in situations where you dynamically generate some
00:37:52
text with your variables. Let me show you. Let's say we have two variables
00:37:56
first name and last name. So first we set this to
00:38:00
John, and last we set this to Smith. Now it's better
00:38:04
to call these variables first name and last name, because they're more
00:38:08
descriptive. But here I'm using shorter names because I want you to see the entire code on display
00:38:12
screen. So let's say with these two variables, we want to generate
00:38:16
some text like this. Jon, in square brackets
00:38:20
Smith is a coder. Let's say we want to print this on
00:38:24
the terminal. How do we do this? Well, we define another variable
00:38:28
like message, now here we add the first name,
00:38:32
now we need to concatenate this, with a string that contains a space
00:38:36
and a square bracket next we need to add a last name,
00:38:40
then we need to add a string that contains
00:38:44
the closing square brackets followed by is a coder
00:38:48
okay? So, then,
00:38:52
if you print message and run this program
00:38:56
to see John Smith is a coder, right? Сейчас,
00:39:00
while this approach perfectly works, it's not ideal
00:39:04
because as our text gets more complicated it becomes harder to
00:39:08
visualize the output. So someone else reading this code, they have to
00:39:12
visualize all the string concatenations in their head. This is where we use
00:39:16
formatted strings, they make it easier for us to visualize the output. So,
00:39:20
I'm going to define another variable, let's say
00:39:24
msg short for message, and set this to a formatted string. A formatted
00:39:28
string is one that is prefixed with an f. So f,
00:39:32
quotes. Now in between the quotes, first we want to add
00:39:36
the value of the first name variable, so,
00:39:40
we add curly braces and here we type first.
00:39:44
Next we add a space, we add our square brackets, in between the square
00:39:48
brackets, we want to display the last name so once again we add curly
00:39:52
braces, and type last, and finally here we type
00:39:56
is a coder. So this is what we call the formatted
00:40:00
string. With these curly braces, we're defining place holders
00:40:04
or holes in our string, and when we run our program these holes
00:40:08
will be filled with the value of our variables. So here we have two place holders
00:40:12
or two holes in our string. One is for the value of our first name
00:40:16
variable and the other is for the value of the last name variable.
00:40:20
But compare this formatted string with string
00:40:24
concatenation. With this formatted string we can easily visualize
00:40:28
what the output looks like, right? Now let's print this other
00:40:32
terminal to make sure we get the same exact output. So, let's print message
00:40:36
there you go. So Jon
00:40:40
Smith is a coder. So to define formatted strings,
00:40:44
prefix your strings with an F and then use curly braces
00:40:48
to dynamically insert values into your strings.
00:40:56
In this Python tutorial, I'm going to show you some really cool things you can do with Python
00:41:00
strings. So let's start by defining a variable,
00:41:04
course and we set that to Python for
00:41:08
beginners. Now to calculate the number
00:41:12
of characters in this string, you can use a built in function called len.
00:41:16
So len we give it this course variable, and then,
00:41:20
we can print the result. Let's run this program,
00:41:24
so as you can see we have 20 characters in this string, this is
00:41:28
particularly useful when you receive input from the user. For example you have
00:41:32
noticed that when you fill out a form online, each input field
00:41:36
often has a limit. For example, you might have 50 characters for your name,
00:41:40
so using this len function we can enforce a limit on the number of characters
00:41:44
in an input field. If the user types in more characters than we allow,
00:41:48
we can display an error, now, this,
00:41:52
len function is another function built into Python, it's
00:41:56
a general purpose function, so it's not limited to counting the number of characters in a
00:42:00
string, in the future when we look at lists, I want to show you that we can use this
00:42:04
function to count the number of items in a list. So it's a general purpose
00:42:08
function. Now we also have functions specifically for strings
00:42:12
for example we have functions for converting all these characters to upper case
00:42:16
or lower case. To access these functions we use the dot operator.
00:42:20
let me show you. So first we type course,
00:42:24
then dot look these are all the functions
00:42:28
that are specific to strings. Now in more accurate terms,
00:42:32
you refer to these function as methods, this is a term
00:42:36
in object oriented programming that we want to look at in the future, but for now, what I want you to take away,
00:42:40
is that when a function belongs to something else, or is specific
00:42:44
to some kind of object, we refer to that function as a method.
00:42:48
For example, here we have this function, upper, for converting the string
00:42:52
into upper case, now more accurately because this function
00:42:56
is specific to a string, we refer to this as a method. In contrast
00:43:00
len and print are general purpose functions, they don't belong
00:43:04
to strings or numbers or other kinds of objects.
00:43:08
So this is the difference between functions and methods. Now let's take look at this
00:43:12
upper method. So, let's print the results
00:43:16
and we run our program, there you go,
00:43:20
you get all these characters displayed in uppercase. Now note this method
00:43:24
does not change or modify our original string, in fact
00:43:28
it creates a new string and returns it. So,
00:43:32
if we print our course variable right after we
00:43:36
call the upper method, we can see that our course variable still
00:43:40
has it's original form, so let's run this program one more time, there you
00:43:44
go. Look, here is our original course variable, it's not modified.
00:43:48
Now similar to the upper method we have another method
00:43:52
for converting a string into lower case. So let me show you.
00:43:56
Print, course.lower.
00:44:00
Now, let's run the program, so on the second line you can see,
00:44:04
all characters are in lower case. Now there are times
00:44:08
that you want to find a character or a sequence of characters in a string.
00:44:12
In those situations you can use the find method. So let me delete
00:44:16
these few lines. Call course.
00:44:20
find here we pass a character, let's say
00:44:24
p, and this will return the index of the first occurrence
00:44:28
of that character, let me show you. So let's print the result
00:44:32
we get 0, because the
00:44:36
index of the first capital p in the string is 0.
00:44:40
As another example, if we pass a lower case o here,
00:44:44
let's see what we get, we get 4 because
00:44:48
the index of this o here is 4. Now note that the
00:44:52
find method is case sensitive, so it's sensitive to
00:44:56
lower case and and upper case characters. As an example if you pass an upper case
00:45:00
here and run this program, we get negative 1 because
00:45:04
we don't have an upper case o anywhere in this string, okay?
00:45:08
We can also pass a sequence of characters, for example, we can pass
00:45:12
beginners with a capital B
00:45:16
let's run this program, we get 11 because
00:45:20
beginners starts with index 11, now we
00:45:24
also have method for replacing a character or a sequence of characters
00:45:28
and that is called replace. So let's change find
00:45:32
to replace let's say we want to replace beginners with
00:45:36
absolute beginners, so we add a comma to pass a second value
00:45:40
to this function, or more accurately this method. We add a string,
00:45:44
here I'm going to pass absolute beginners.
00:45:48
Okay, now let's run this program,
00:45:52
so, we get python for absolute beginners.
00:45:56
Again, this method like the find method is case sensitive so
00:46:00
if you pass beginners all in lowercase, this method is
00:46:04
not going to find this exact word in our string, so it's not going to
00:46:08
place it with absolute beginners. Let's take a look. So I'm going to run the program
00:46:12
One more time, look, we still get python for beginners.
00:46:16
We can also replace a single character, for example we can replace
00:46:20
capital p with let's say capital
00:46:24
j. Now when we run this program we get
00:46:28
jython for beginners. So these are the find and replace methods
00:46:32
and one last things I want to show you in this tutorial. There are
00:46:36
times that you want to check the existence of a character or sequence of characters in your
00:46:40
string. In those situations you use the in operator,
00:46:44
so let's say you want to know if this string contains the word python.
00:46:48
We can write an expression like this. String
00:46:52
python space in space course.
00:46:56
So we're checking to see if python is in
00:47:00
course variable. And this is an expression that produces a boolean
00:47:04
value, and I get true or false, so we refer to this expression
00:47:08
as a boolean expression, now if we print this on the terminal,
00:47:12
we should get true, and by the way
00:47:16
I'm going to delete the second line, we don't need it anymore, so run the program
00:47:20
we get true, but if I change this capitol p to a lower case
00:47:24
p and run the program we get false because we don't have
00:47:28
is exact sequence of characters in our strings.
00:47:32
Now note that the difference between the in operator and the find method
00:47:36
is that our find method returns the index of
00:47:40
character or sequence of characters but the in operator
00:47:44
produces a boolean value. Do we have this or not?
00:47:48
So that's the difference. Now let's recap all the cool things you learned
00:47:52
to do with strings in this tutorial. We can use the len function
00:47:56
to count the number of characters in a string, this is the general
00:48:00
purpose function built into python, we also have specific functions
00:48:04
for strings which we refer to as methods, these include
00:48:08
upper for converting a string into uppercase
00:48:12
you also have lower and title methods,
00:48:16
you learn about the find method which returns the index
00:48:20
of a character or sequence of characters, we have
00:48:24
the replace method for replacing characters and words in a string and finally
00:48:28
you learned about the in operator. So some characters
00:48:32
in a string.
00:48:40
So, you have learned that in Python programming language you have 2
00:48:44
types of numbers, integers which are whole numbers like 10, they don't have
00:48:48
a decimal point, and floating point numbers or floats.
00:48:52
Which are numbers with a decimal point. Now in this tutorial you're going to look
00:48:56
at the arithmetic operations supported in python language these are the
00:49:00
same arithmetic operations that we have in math, we can add numbers,
00:49:04
multiply them and so on. So let's look at a few examples,
00:49:08
we can print, 10 plus 3, so
00:49:12
this is the addition operator, we also have subtraction, we
00:49:16
have multiplication, we have two kinds of division,
00:49:20
here's one with a forward slash, let's run this program and see what we get.
00:49:24
we get a floating point number. But we also have
00:49:28
another division operator for getting an integer. Так
00:49:32
if we add another slash here and run this program
00:49:36
we get an integer. У нас есть
00:49:40
another operator called modulis (?) which is a percent sign.
00:49:44
And this returns the remainder of the division. So when we run this program
00:49:48
we should get 1, there you go. And
00:49:52
one last operator we have here is exponent which is the power.
00:49:56
So, that is indicated with 2 asterisks and this will return
00:50:00
10 to the power of 3. So let's run this program
00:50:04
we get 1000 so these are the arithmetic operators
00:50:08
in python programming language. Now for all these operators that you learned
00:50:12
we have an augmented assignment operator. That is
00:50:16
very useful, let me show you. So let's say we have a variable
00:50:20
called x we set it to 10, now we want to increment this by
00:50:24
3, we'll have to write code like this. X we set this to
00:50:28
x plus 3. So Python interpreter will add
00:50:32
10 to 3, the result is 13, and then it gets stored
00:50:36
into x again. So when we print x we should see
00:50:40
13, there you go. So this is how you can increment
00:50:44
a number, right? Now augmented assignment operator is
00:50:48
a way to write the same code but in a shorter form. это
00:50:52
is how it works. We type x plus
00:50:56
equals 3. What we have on line 3 is exactly
00:51:00
like what we have on line 2. So this is what we call
00:51:04
the augmented assignment operator we have augmented or
00:51:08
enhanced the assignment operator. Now in this particular
00:51:12
case we are incremented a number using the augmented assignment operator,
00:51:16
but we can also subtract or multiply a number by a given value
00:51:20
for example, let's delete what we have on line 2,
00:51:24
we can type subtract equals 3. So here we
00:51:28
subtracted 3 from x. When we run this program we should see 7,
00:51:32
there you go.
00:51:40
Now let me ask you a question, I'm going to clear all this code here to
00:51:44
define x and set it to 10 plus 3
00:51:48
times 2. What do you think is the result of this expression?
00:51:52
this is a very basic math question that unfortunately a lot of people fail to answer.
00:51:56
The answer is 16. Because in math we have this
00:52:00
concept called operator precedence which means the order of
00:52:04
operations. So the multiplication operator has
00:52:08
a higher precendence which means it's applied first which means 3 x
00:52:12
2 is executed first, the result is 6 and then
00:52:16
its added to 10, that's why x showed up as 16 after
00:52:20
we run this code, let's verify that. So, print x
00:52:24
run the program, x is 16. So this is what we call
00:52:28
operator precedence, it's just a basic math concept.
00:52:32
It's not about python programming language. So all the other programming languages
00:52:36
behave the same way, so here's the order, first we have
00:52:40
the exponentiation which is the power, like 2 to the power of 3,
00:52:44
then we have multiplication or division
00:52:48
and finally we have addition or subtraction.
00:52:52
This is the order of operations. Let me show you another example.
00:52:56
Here I'm going to add the exponentiation operator, so,
00:53:00
2 to the power of 2. Once again, what do you
00:53:04
think is the result of this expression? Pause the video and think about it for a few seconds.
00:53:08
The answer is 22.
00:53:12
Because the exponentiation operator takes precedence, so first
00:53:16
2 to the power of 2 is executed, the result is 4,
00:53:20
then 4 is multiplied by 3, that is 12,
00:53:24
and finally 12 is added to 10. So x should be 22.
00:53:28
So let's run this program and verify this. So I'm going to
00:53:32
delete these lines here. Run the program, there you go. X
00:53:36
is 22. Now let me bring back these rules here.
00:53:40
We can also use parenthesis to change the order of operations
00:53:44
so if we have parenthesis we always
00:53:48
takes priority. In this case we can add parenthesis
00:53:52
around 10 + 3, so this piece of 3 will be
00:53:56
executed first, the result is 13, then the exponentiation
00:54:00
operator will be executed, so 2 to the power of 2 is 4,
00:54:04
and finally 4 is multiplied by 13.
00:54:08
Now here is a little exercise for you. I'm going to set x to
00:54:12
parenthesis 2 + 3 x 10 minus
00:54:16
3. What is the result of this? Pause the video and think about it for a few seconds.
00:54:24
So you learned that parenthesis always
00:54:28
overrides the order, so this piece of code is executed first. The result
00:54:32
of these 5. Then, between the multiplication and
00:54:36
subtraction, you know that multiplication takes precedence.
00:54:40
So next, 5 will be multiplied by 10, the result is
00:54:44
50 and finally we have subtraction. So 50 minus
00:54:48
3 will be 47. Let's verify this, print
00:54:52
x, run the program there you go, I hope you guessed it right.
00:54:56
So this is all bout operator precedence, it's a very important topic
00:55:00
and I see it quite often in Python tests. So if you're preparing for a Python test
00:55:04
make sure to watch his tutorial one more time.
00:55:12
In this tutorial, we're going to look at a few useful functions for working with numbers
00:55:16
let's start by defining a variable like x and set it to 2
00:55:20
.9. Now to round this number we can use the built in
00:55:24
round function, so we call the round function, give it x,
00:55:28
and then print the result. Let's run this program
00:55:32
so, we get 3, we have another useful built in function called
00:55:36
abs which is short for absolute, and this is the absolute function
00:55:40
we have in math, we give it a value and it always returns
00:55:44
the positive representation of this value, even if the value is negative.
00:55:48
Here's an example. Let's call the abs function
00:55:52
and give it negative 2.9 When we run this program
00:55:56
we're gong to see 2.9 on the terminal. So let's go ahead
00:56:00
there you go. So absolute always returns a positive number.
00:56:04
But technically in Python we have a handful of built in functions for performing
00:56:08
mathematical operations, if you want to write a program that involves complex
00:56:12
mathematical calculations, you need to import the math module.
00:56:16
A module in Python is a separate file with some reusable
00:56:20
code. We use these modules to organize our code into different
00:56:24
files. As a metaphor think of a super market. When you go to a super market
00:56:28
you see different sections for fruits and vegetables, cleaning products,
00:56:32
junk food and so on. Each section in the super market is like a module
00:56:36
in Python. So in Python we have this math module which contains a bunch
00:56:40
of rustable functions for performing mathematical calculations.
00:56:44
So, let me show you how to use this module. On the top
00:56:48
we type import, math, all in lowercase
00:56:52
with this we can import the math module. now math is
00:56:56
an object like a string, so we can access it's functions or more accurately
00:57:00
it's methods using the dot operator. So if you type
00:57:04
math. look these are all the mathematical
00:57:08
functions available in this module. For example you can call the
00:57:12
seal method to get the sealing of a number. So if you pass 2.9 here
00:57:16
and then print the result we should see 3.
00:57:20
Let me delete all this other code here. Alright, let's run this program
00:57:24
there you go. So we get 3. Another useful method is the
00:57:28
floor method, so let's give that a try, floor of 2.
00:57:32
9. What do you think we're going to get? We get
00:57:36
2. Now there are so many functions built in this module and we don't really have time
00:57:40
to go through all of them. But let me show you how we can learn about them on your own.
00:57:44
Open up your browser and search for Python 3
00:57:48
math module. Make sure to add the version python 3.
00:57:52
Because the math module in python 2 is slightly different from the math module in
00:57:56
python 3. So python 3 math module,
00:58:00
now here you can see the documentation of this kind of module
00:58:04
let's go let's have a look, if you scroll down,
00:58:08
we can see the list of all the functions and their explanation.
00:58:12
So as an exercise I encourage you to have a quick look at this
00:58:16
documentation. See what functions are there for you in case you need them.
00:58:24
In this tutorial, I'm going to talk to you about if statements in Python
00:58:28
if statements are extremely important in programming and they
00:58:32
allow us to build programs that can make decisions based on some condition.
00:58:36
So if some conditions are true we're going to do certain things, otherwise we're going to do other
00:58:40
things. Here's an example. Over here I've got this text file with
00:58:44
a bunch of rules for our program. If it's a hot day, perhaps we want to
00:58:48
tell the user it's a hot day, so make sure to drink plenty of water.
00:58:52
Otherwise, if it's cold, so here's another condition
00:58:56
if this condition is true we're going to tell the user it's a cold day
00:59:00
so where warm clothes. And otherwise if it's
00:59:04
either hot or cold, we want to tell the user it's a lovely day.
00:59:08
So let me show you how to write a program that simulates these rules. So,
00:59:12
back to our program here, we start by defining a boolean variable
00:59:16
is underline hot. We set this to true.
00:59:20
Next, we add an if statement, so if, here
00:59:24
we need to add a condition, in this case we're going to use our boolean variable. So,
00:59:28
is underline hot. So if this values to true.
00:59:32
Then we're going to do certain things. In this case, we want to tell the user
00:59:36
hey it's a hot day, drink plenty of water. So, back to our program
00:59:40
after our condition we add a colon, now,
00:59:44
note that when I press enter pycharm automatically indents
00:59:48
our cursor. Now any code that we write here will be executed
00:59:52
if this condition is true, otherwise it will be ignored. Here
00:59:56
is an example. Let's write a print statement, here I'm going to use
01:00:00
double quotes because I want to use an apostrophe in our string. So,
01:00:04
it's a hot day. Now let's press enter
01:00:08
you can see the cursor is still indented, that means we can write more code
01:00:12
that we executed if this condition is true, in this case let's say we don't want to
01:00:16
write any extra code, so to terminate this block
01:00:20
we need to press shift and tab, now the cursor is at the beginning of the line
01:00:24
so lets write a print statement with a message like
01:00:28
enjoy your day. Now when we run this program, because
01:00:32
this condition is true, you're doing to say this message followed by
01:00:36
this second message, take a look, so run, there you go, it's a hot day
01:00:40
enjoy your day. But if I go over here and
01:00:44
change this boolean value to false and run the program again, our
01:00:48
first message disappears and we only see the second message, enjoy
01:00:52
your day. So this is how if statements work. Now back
01:00:56
here we can add another print statement let's say
01:01:00
drink plenty of water.
01:01:04
Now because this spirant statement is also indented it will be
01:01:08
executed if this condition is true. So I'm going to revert is hot to true
01:01:12
and run the program one more time. There you go, so
01:01:16
it's a hot day, drink plenty of water, and enjoy your
01:01:20
day. Alright now let's add a second rule here, if
01:01:24
it's hot we're going to execute these two lines, otherwise if it's not hot
01:01:28
we want to print a different message. So here
01:01:32
we are moving an indentation and typing els
01:01:36
colon. Now when we press enter once again our cursor
01:01:40
indented so the code that we write here will be executed if this
01:01:44
condition is not true. So here we can print
01:01:48
it's a cold day, print,
01:01:52
where warm clothes.
01:01:56
Now let's run our program one more time. So we get the message
01:02:00
about a hot day followed by enjoy your day. You don't see any message
01:02:04
about a cold day. Now if we go back here on the top.
01:02:08
And change this boolean value to false and run our program
01:02:12
we see different set of messages. It's a cold day
01:02:16
wear warm clothes and enjoy your day. But there's a problem with
01:02:20
our program. If it's not hot it doesn't necessarily mean that it's cold, it means
01:02:24
it's a lovely day. So the absence of heat doesn't mean its cold.
01:02:28
Back to our conditions, here on line 4 we have this rule that says
01:02:32
if it's a cold day, then print these messages
01:02:36
otherwise if it's neither hot or cold say it's a lovely day.
01:02:40
So, to implement this rule we need to go back and put
01:02:44
py and define another variable. So let' say
01:02:48
is underline cold we set this to
01:02:52
true. Now here we need to add a second condition. So after
01:02:56
our first if statement, we can use an el if statement
01:03:00
to define a second condition. So here's how it works. So,
01:03:04
el if which is short for els if or
01:03:08
otherwise if, now here we add another condition, so,
01:03:12
is cold So if t's cold you want to
01:03:16
execute these few lines. So let's cut these
01:03:20
from here, and move them under our second condition
01:03:24
and finally if none of these conditions are true,
01:03:28
you want to print a different message. It's a lovely
01:03:32
day. So, right now,
01:03:36
is hot is false, is cold is true,
01:03:40
so when we run this program, python interpreter is going to execute the first
01:03:44
if statement, in this case because our condition is false, these two
01:03:48
lines will be ignored, then Python interpreter will look at
01:03:52
line 7, it will evaluate this condition, in this case is
01:03:56
cold is true so we're going to see these two messages on the terminal.
01:04:00
Now, in this case, because one of these conditions was true, this els statement
01:04:04
will be ignored, so we are not going to see this message, and finally
01:04:08
as before, we are always going too see this message. So let's run our
01:04:12
program, there you go. it's a cold day,
01:04:16
where warm clothes and and enjoy your day. Сейчас,
01:04:20
back to the top, if we change is cold
01:04:24
to false it's neither hot nor cold so it's going to be a lovely day.
01:04:28
Let's run the program, and here you go, it's a lovely day
01:04:32
enjoy your day. So these are the basics of using if
01:04:36
statements. As you can see they are very useful in programming and with these
01:04:40
we can build all kinds of rules into our programs. Okay here's an
01:04:44
exercise or you. Imagine the price of a house is 1 million dollars.
01:04:48
Now if the buyer has good credit, they will need to put down 10 percent
01:04:52
of the price of this property otherwise they need to put down 20 percent
01:04:56
write a program with these rules an display the down payment
01:05:00
card for a buyer with good credit. You will see my solution
01:05:04
next.
01:05:08
Alright let's define a variable for the price of this house so price
01:05:12
we set this to 1 million so 1 with 6 0s.
01:05:16
Next we need a variable to tell if this buyer has good credit
01:05:20
so has good credit,
01:05:24
and we set this to true, now we need an if statement
01:05:28
so if has good credit has true
01:05:32
colon, here we need to calculate a down payment so
01:05:36
the down_payment should be equal to
01:05:40
0.1 x the price. That is 10 percent of the price of this
01:05:44
property. Otherwise colon
01:05:48
the down payment should be 0.2
01:05:52
times price. Now finally we remove the
01:05:56
indentation and print here we can use a form
01:06:00
of valid string, first we add a label, down payment
01:06:04
colon and right after that we add a placeholder
01:06:08
or a hole for our down payment variable. So curly braces
01:06:12
down payment. Let's run this
01:06:16
program, so down payment for a buyer with good credit
01:06:20
is 100,000 dollars. Now let's improve this by adding a
01:06:24
dollar sign before this number. So back to our formatted string,
01:06:28
just before the curly brace I'm going to add a dollar sign let's
01:06:32
run this one more time, that is better.
01:06:40
In this tutorial I'm going to talk to you about the logical operators within Python.
01:06:44
We use these operators in situations where we have multiple
01:06:48
conditions. Here is an example. Let' say we're building an application for
01:06:52
processing loans. If an applicant has high income
01:06:56
and good credit, then they're eligible
01:07:00
for a loan. So in this example we have two conditions, one is having
01:07:04
high income and the other is having good credit. So if both
01:07:08
these conditions are true, then the applicant is eligible for a loan.
01:07:12
So this is where we use the logical and operator.
01:07:16
We use this operator to combine two conditions, and by the way
01:07:20
this is not specific to python programming language, pretty much any programming language
01:07:24
that supports if statements also supports the logical operators.
01:07:28
So, back to our program, let's define two variables,
01:07:32
has high income, we set this to true.
01:07:36
And another one has good
01:07:40
credit, we also set this to true, now our if statement
01:07:44
if has high income has true,
01:07:48
and has good credit is also true,
01:07:52
then we're going to print eligible
01:07:56
for null. So this is where
01:08:00
we're using the and operator. So if both these conditions are true
01:08:04
then this message will be printed. If one of them is false, we're not going to see
01:08:08
this message. Let's try this out. So I'm going to run this program
01:08:12
so we see it eligible for loan, but if we change
01:08:16
either of these conditions to false, and run the program again
01:08:20
look, the message disappears.
01:08:24
So this is the logical and operator. We also have the
01:08:28
logical or, and we want to use that in situations where we want to do certain things
01:08:32
at least one of the conditions is true, for example let's change
01:08:36
the rule for this program, such that if the applicant has high income,
01:08:40
or good credit, then they're eligible for a loan,
01:08:44
so if either or both these conditions are true then the candidate is
01:08:48
eligible. Now back to our program we can
01:08:52
implement this rule by using the logical or operator. So we simply replace
01:08:56
and with or, now when we run this program we're going to
01:09:00
see this message because at least one of our conditions is true,
01:09:04
let's take a look. So the applicant is eligible for a loan
01:09:08
for a loan because they have good credit. If you change this to false
01:09:12
but set the other condition to true, we still
01:09:16
see the same result, but if both these conditions are false
01:09:20
then we're not going to see this message anymore. So this is the difference
01:09:24
between these operators. With the logical and operator
01:09:28
both conditions should be true, with the logical
01:09:32
or operator at least one condition should be true
01:09:36
we also have another logical operator called not
01:09:40
and that basically inverses any boolean value we give it, if we give it,
01:09:44
we give it a true boolean value it converts it to false. For example
01:09:48
let's make up a new room, if applicant
01:09:52
has good credit and doesn't have
01:09:56
a criminal record then
01:10:00
they're eligible for a loan. Let me show you how to implement this. So,
01:10:04
we go back to our program, in this example we don't need a
01:10:08
first variable for let's delete that. Let's set this variable to true
01:10:12
we also define another variable like has criminal
01:10:16
record. We set this to false.
01:10:20
Now, we want to check to see if this applicant has good credit and not
01:10:24
a criminal record. This is where we use the not operator.
01:10:28
So, if they have good credit
01:10:32
and not criminal
01:10:36
record. So, in this example, has criminal
01:10:40
record is set to false, when we use the not operator this
01:10:44
basically gets changed to true, so we have two conditions that are true.
01:10:48
Here's ones and here's another one. So our applicant is
01:10:52
eligible for a loan. And when we run this program we see
01:10:56
this familiar message. However
01:11:00
if an applicant has a criminal record, so let's change this to
01:11:04
true, now when we run this program we can see our applicant is
01:11:08
not eligible because when we apply then operator on this
01:11:12
variable, we'll get false. So true changes to false.
01:11:16
And we'll end up with two conditions, one that's true
01:11:20
and the other is false. And that's why this message is
01:11:24
not printed. So this is all about the logical operators in
01:11:28
python.
01:11:32
In this tutorial I'm going to talk to you guys about
01:11:36
comparison operators in Python. We use comparison operators
01:11:40
in situations where we want to compare a variable with a value,
01:11:44
for example, if temperature is greater than 30, then
01:11:48
we want to print it's a hot day. Otherwise, if it's less
01:11:52
then 10, it's a cold day, otherwise it it's neither hot
01:11:56
nor cold. And by the way I'm taking about celsius, not farenheit.
01:12:00
So, to build these rules into our program, we need to use comparison
01:12:04
operators. Back to app.py, I define this
01:12:08
temperature value, let's write an if statement, if temperature
01:12:12
now we want to check to see if this is greater than 30, so we use
01:12:16
the greater than operator. If this is greater than 30,
01:12:20
we want to print it's a hot day
01:12:24
otherwise, let's just print
01:12:28
it's not a hot day. Сейчас,
01:12:32
when we run this program, we're going to see this second message because 30
01:12:36
is not greater than 30. So our first condition a value
01:12:40
is to false. let's verify that. So run,
01:12:44
it's not a hot day. Now if you change
01:12:48
the temperature to 35 and run this again,
01:12:52
we're going to see a different message, it's a hot day, so this is where we use
01:12:56
comparison operators. Now what we have here as you know is an expression
01:13:00
because it's a piece of code that produces a value. So more accurately this is
01:13:04
a boolean expression. So this is the greater than operator,
01:13:08
we also have greater than or equal to, we have
01:13:12
less then, less then or equal to,
01:13:16
here's the equality operator, so if the temperature equals to 30,
01:13:20
then you can say it's a hot day. Note that this is different from the assignment operator
01:13:24
that has only one equals sign. You can see that if we use only one equal sign
01:13:28
here we immediately get this red underline because this is simply
01:13:32
an assignment statement. We're changing the value of the temperature.
01:13:36
you are setting the value of
01:13:40
something else. So we don't have a boolean expression, you are not producing a
01:13:44
boolean value. Okay? So, our equality operator
01:13:48
has two equal signs and finally we have not
01:13:52
equal which is an exclamation followed by an equal sign.
01:13:56
Now here's an exercise for you. You have probably seen that when you fill out a
01:14:00
form online, sometimes the input fields have validation messages,
01:14:04
for example, let's say we have an input field for the user to enter their name.
01:14:08
Now if the name is less then 3 characters wrong we want to display a validation
01:14:12
error, like name must be at least three characters,
01:14:16
otherwise, if the name is more then 50 characters long then we want
01:14:20
to display a different validation error like name can be a maximum
01:14:24
of 50 characters. Otherwise if the name is between 3 and 50 characters
01:14:28
then we just want to tell the user that name looks good.
01:14:32
So go ahead, and write a plan to implement these rules.
01:14:40
Alright let's define a variable called name and set it to
01:14:44
let's say j. So we're assuming this is what the user types into an input field.
01:14:48
Now, we want to get the number of characters in this string.
01:14:52
So we use the len function, right? Len of name.
01:14:56
When we print this we get 1, right
01:15:00
you have seen this before. Now here we want to use an if statement so
01:15:04
if len of name is less then
01:15:08
3, then we want to print
01:15:12
name must be at least 3 characters
01:15:16
now here we need a second condition
01:15:20
to check the upper limit. So el if
01:15:24
len of name is greater than 50,
01:15:28
then we want to print a different message, name,
01:15:32
must be a maximum
01:15:36
of 50 characters.
01:15:40
Okay? And otherwise if else
01:15:44
none of these conditions are true that means the name looks good. So,
01:15:48
print, name looks good. Let's
01:15:52
run our program. So in this case we get this message
01:15:56
because our name is too short. Now if you go back here and
01:16:00
type something really really long. And then
01:16:04
we run our program we're going to see a different message name must be a
01:16:08
maximum of 50 characters and finally if
01:16:12
we type a proper name here like John Smith
01:16:16
and run our program we get name
01:16:20
looks good.
01:16:24
Here's another good exercise that combines
01:16:28
many of the materials you have learned so far, so earlier you built a program to
01:16:32
convert someone's weight from pounds to kilograms. Now we want to extend this program
01:16:36
and allow the user to enter their weight in either kilograms or
01:16:40
pounds and then we will convert it to the other unit. Here's how our program
01:16:44
is going to work. So I enter my weight in pounds so
01:16:48
100 and 60 now it's telling me if it's in pounds or
01:16:52
kilograms. So here I'm adding l to lbs or k for kilograms.
01:16:56
And by the way, this program is not case sensitive so
01:17:00
when I enter a capital l or lowercase l it takes
01:17:04
it as pounds. Now it tells me ur set it to
01:17:08
kilos. Let's run this program one more time,
01:17:12
this time I'm going to enter my weight in kilo's, so send it to
01:17:16
is the weight and the unit is kilograms so k,
01:17:20
and it says you are 160 pounds.
01:17:24
So go ahead and spend a few minutes on this exercise, you will see my solution next.
01:17:32
Alright first let's ask the user their weight. So we use the input
01:17:36
function, weight colon we get the return value
01:17:40
and store it in the variable called weight.
01:17:44
Now the second question, so one more time we use the input function
01:17:48
el for pounds.
01:17:52
Or k for kilograms. So,
01:17:56
let's get that too and store it in a variable called unit
01:18:00
now we need an if statement. So if unit
01:18:04
equals l then we need to convert this weight
01:18:08
into kilograms. However, with this implementation we are only allowing
01:18:12
the user to enter a capitol l, if they enter a lowercase l
01:18:16
this code is not going to work. So this is where we use the upper
01:18:20
method of string objects so this unit is a string because as I told you
01:18:24
before, the input function always returns a string.
01:18:28
So, we can use the dot operator to access all it's methods or
01:18:32
functions, here we call the upper method, this
01:18:36
will convert whatever the user enters to upper case and then we'll convert it
01:18:40
to a capital l. Now, if this condition is true,
01:18:44
then we need to get the weight and multiply it by 0,
01:18:48
.45 However, as you know this
01:18:52
weight is a string object, and we cannot multiply a string
01:18:56
by a floating point number, we talked about this earlier in this course.
01:19:00
So first we need to convert this weight to a numerical value. Так
01:19:04
right here, when we call the input function, we can get the return
01:19:08
value and pass it to the int function. So,
01:19:12
we call the int function and give it
01:19:16
the return value of the input function. Now, the
01:19:20
in function will return an integer so we can store it in this weight
01:19:24
variable. So here's the converted weight, let's store it in
01:19:28
a variable called converted,
01:19:32
then we print here we can use a formatted string, so
01:19:36
we prefix this string with f ur
01:19:40
we add curly braces to dynamically insert the value of
01:19:44
converted variable. And finally we add kilo.
01:19:48
Otherwise, if the unit is kilograms.
01:19:52
We need to divide the weight by 0.45. q
01:20:00
So, weight divided by 0.45 and
01:20:04
just to refresh your memory, this division operator returns a floating point number
01:20:08
but if we use double slashes we'll get an integer.
01:20:12
In this case, we want to get a floating point number,
01:20:16
finally let's print a formatted string, ur
01:20:20
curly braces, converted
01:20:24
pounds. Okay? Now
01:20:28
let's run this program and see what happens. So weight is
01:20:32
160 and lbs in
01:20:36
and that equals to 72 kilos, perfect, if we run it one more time,
01:20:40
and enter 72 kilos
01:20:44
we get 160 pounds.
01:20:52
In this tutorial I'm going to show you how to use y loops in python. Мы
01:20:56
use y loops to execute a block of code multiple times and there are often
01:21:00
useful in building interactive programs and games. In a future tutorial
01:21:04
I'm going to show you how to build a simple game using ay loop.
01:21:08
So, let's get started with the basics, we write ay statement
01:21:12
and right after that, we type a condition followed by a colon
01:21:16
as long as this condition is true the quote that we write
01:21:20
in this block will be repeatedly executed. Here is an example.
01:21:24
We can define a variable like i, as in short for
01:21:28
index and set it to 1. Now we set our condition to
01:21:32
i less than or equal to 5, so as long as I
01:21:36
is less then or equal to 5, we can print i,
01:21:40
on the terminal. And then we need to increment i,
01:21:44
by 1. So we set i to i plus 1. The reason
01:21:48
we do this is that if we don't do this I will be 1 forever
01:21:52
so we'll end up with an infinite loop. Because this condition will
01:21:56
always be true. One is always less then 5, so in every iteration of this
01:22:00
loop, we increment i by 1, so at some point, i is gonna be
01:22:04
six and then that is when this condition will be false and then
01:22:08
we'll jump out of this loop, okay? Now to demonstrate how everything works
01:22:12
after this loop I'm going to add a print statement
01:22:16
say done. So note that these two lines
01:22:20
are indented so they are part of the y block.
01:22:24
Okay, now let's go ahead and run this program and see what happens. So,
01:22:28
take a look, we get the numbers 1-5 followed by
01:22:32
done. So heres how this program gets executed
01:22:36
first we set i to 1 now python interpreter executes line
01:22:40
2, this condition is true because i is less then 5,
01:22:44
so i is printed on the terminal and then incremented by
01:22:48
1. Then the control moves back to the beginning of the y loop.
01:22:52
So it doesn't go to the next statement. So,
01:22:56
we come back here and now we are in the second iteration. In the second iteration
01:23:00
i is 2, and because 2 is less then 5, our condition is still
01:23:04
true, so i will be printed on the terminal, and once again it will be
01:23:08
incremented by 1, so at some point i is going to be 6,
01:23:12
and that's when this condition will be false so our look will
01:23:16
be terminated and this done message will be printed on the terminal.
01:23:20
So this is the basics of y loops. Now let's make this program a little
01:23:24
bit more interesting. Here we can write an expression like this. Мы
01:23:28
add a string, and in this string we add an asterisk
01:23:32
and then we multiply this string by i. Так
01:23:36
with this expression, we can repeat a string, when we multiply a string
01:23:40
by a number, that string will be repeated. For example, if
01:23:44
i is two, this expression will produce a
01:23:48
string with two asterisks. Now let's run the program
01:23:52
and see what we get. So we see this little triangle
01:23:56
shape here. Because in the first iteration i is 1, so,
01:24:00
1 times an asterisk produces 1 asterisk.
01:24:04
In the second iteration i is 2, so when we multiply 2
01:24:08
by 1 asterisks, we'll get 2 asterisks.
01:24:16
In this tutorial I'm going to show you how to use ay loop to build
01:24:20
a guessing game like this. So we have this secret number which is currently set to
01:24:24
9. Now the computer is asking me to make a guess. So,
01:24:28
let's say 1 is not right because the secret number is 9, okay,
01:24:32
try again, 2, no it's not right, let's try again, so I
01:24:36
only have three chances to make a guess. If I can't guess the number the program
01:24:40
tells me that I failed. let's run the program one more time, this time
01:24:44
I'm going to guess the number, it's 9, there you go, it says you in.
01:24:48
So let's go ahead and build this program using ay loop.
01:24:52
Alright, let's start by defining a variable to store our secret number
01:24:56
so, we call the secret underline number and set it to 9.
01:25:00
Now we need a while loop to repeatedly ask a user to
01:25:04
make a guess. So while condition colon
01:25:08
What is our condition here? Well we want to give our user a
01:25:12
maximum of three guesses. So similar to the last tutorial, we can define
01:25:16
a variable like I, set it to 0, and assume this represents
01:25:20
the number of guesses the user has made. And then we write our condition
01:25:24
as i less then 3. Note that here I'm not
01:25:28
using less then or equal to operator, because with this condition
01:25:32
our loop will be executed 4 times, while i is 0,
01:25:36
one, two, and three, so here we should use
01:25:40
the less then operator. Now if we give this code to someone else it's unclear
01:25:44
what does i represent here, it's only in our head that
01:25:48
i represents the number of guesses the user has made. So as
01:25:52
a best practice, always use meaningful and descriptive names for your variables.
01:25:56
So it's better to rename this variable to guess, count.
01:26:00
Let me show you how to rename. So right click on i variable,
01:26:04
and then go to refactor and
01:26:08
rename it. Look at the shortcut. On a Mac computer it's shift and
01:26:12
f 6. Now in this dialogue box we can easily
01:26:16
rename your variable and pycharm will update all the references to that
01:26:20
variable so we don't have to manually update each instance, okay? Let's
01:26:24
change this to guess_count
01:26:28
enter, there you go, now that is better,
01:26:32
also it's better to store 3 in a separate variable to make our code
01:26:36
more readable, because it's not quite clear what does 3 represent here.
01:26:40
So, let's define a variable called guess limit
01:26:44
say to 3, and then we can change 3 to guess
01:26:48
underline limit, now our code is more readable
01:26:52
while guess count is less then guess limit, see it reads like a story
01:26:56
this is how you should write code. Okay, so
01:27:00
while this condition is true, we want toast the user to make a guess. So here
01:27:04
we use our input function, guess
01:27:08
Now whatever the user enters comes out as a string so we need to convert it to an integer.
01:27:12
So right here, we pass the result to the end function
01:27:16
and then get it and store it in a separate variable called guess.
01:27:20
So at this point the user made a guess, now we need to
01:27:24
increment guess count so guess count
01:27:28
we set it to plus equal 1 or
01:27:32
okay, now we need to check to see if the user will make the right guess.
01:27:36
So here we need an if statement. If what the user guessed
01:27:40
equals our secret number,
01:27:44
again see our code is so readable. It's like a story you can read it like plain
01:27:48
English. So if this condition is true we want to
01:27:52
tell the user they won. So print you won
01:27:56
now lets go ahead and run our program up to this point.
01:28:00
So okay it's asking me to make a guess, I'm going to make
01:28:04
the wrong guess so one it asked me again, 2 one more time,
01:28:08
3, okay, what is missing in this implementation is the
01:28:12
message that tells me that I failed. We're going to take care of it momentarily, but
01:28:16
let's run the program one more time and make the right guess. So, 9
01:28:20
okay it says you won, but it's still asking me to make
01:28:24
a guess, because our while loop is going to get executed 3 times. Look
01:28:28
1 and 2. So we need to change our program
01:28:32
such that if the user makes the right guess, we need to terminate our
01:28:36
while loop, we need to jump out of it. How do we do that?
01:28:40
So, over here if the user makes the right guess, after
01:28:44
we print this message we can use the brick statement to terminate
01:28:48
terminate a loop, when python interpreter sees this, it's going to
01:28:52
immediately terminate our loop, it's not going to evaluate this condition again.
01:28:56
Now let's run our program and see what happens. So, I'm going to
01:29:00
guess the right number, you won and look, you are
01:29:04
now asked to make two more guesses, beautiful. Now the last thing we need
01:29:08
to add here is the message that tells the user that they failed if they could not guess
01:29:12
the right number. How do we do that? Well in Python
01:29:16
our while loops can optionally have an else part.
01:29:20
similar to the if statements. So earlier you learned that our if statements
01:29:24
can optionally happen else part. Here, so
01:29:28
if this condition is true, do this,
01:29:32
otherwise do something else. In this case our if statement doesn't have
01:29:36
an else part. Now, similar to the if statements
01:29:40
Our while loops, our while statements can also have an else part.
01:29:44
So, right at this level we can add
01:29:48
an else block, so else colon.
01:29:52
And the code that we write here will get executed if this while loop
01:29:56
completes successfully without an immediate
01:30:00
break. In other words. If the user guesses the
01:30:04
right number, you break this loop, you jump out of it so the code that
01:30:08
we write in the else block will not get executed.
01:30:12
But if the user cannot guess this number, you're never going to break out of
01:30:16
this loop, so this loop will be executed to completion untill
01:30:20
this condition become false. In that case, the code that we write
01:30:24
in the else block will get executed, and this is the perfect opportunity for us
01:30:28
to tell the user hey, you made three guesses but none of them were right.
01:30:32
So, print, sorry you
01:30:36
failed. Now, let's test the program one more time.
01:30:40
So, guess 1, 2, 3,
01:30:44
sorry you failed, let's run it one more time. This time I'm going to make
01:30:48
a wrong guess, and then the right guess,
01:30:52
we won and our loop terminated immediately.
01:31:00
Alright, now it's time for you to practice what you have learned so far.
01:31:04
So once again we're going to build a game this game is a simulation
01:31:08
card game. Now our game doesn't have a graphical user interface or gooey
01:31:12
and it doesn't really matter for now, our focus is entirely on building the
01:31:16
engine for this game. So let's see how this works.
01:31:20
When we run this, we get this little symbol here, and our program
01:31:24
is waiting for us to enter a command. If you type help
01:31:28
either a lower case or upper case we get the list of commands
01:31:32
that our program or our game currently supports. So we can type the
01:31:36
start command to start our car, we can type
01:31:40
stop command to stop our car, and quit to terminate the game.
01:31:44
Any other commands that we type our program is going to tell us hey I don't understand that.
01:31:48
For example, if I type asd here, it's going to say I don't understand
01:31:52
that.If you type start, we get this message,
01:31:56
car started, ready to go, if you type stop it
01:32:00
says car stopped, and finally if we hit quit
01:32:04
our program terminates, this is a fantastic exercise for you to practice
01:32:08
wha you have learned, so pause the video and spend 5-10 minutes
01:32:12
to build this program.
01:32:16
Alright, we're going to start with a while loop with a condition
01:32:20
What is our condition here? We want to run this loop
01:32:24
until the user types quit. So we can define a variable
01:32:28
or a story to command what the user enters, and then we can run this
01:32:32
loop as long as the command does not equal to quit. So right before
01:32:36
the loop, we define a variable, command, and initially we set it
01:32:40
to an empty string. An empty string is a string that has no characters
01:32:44
in it. We only have the quotes. So then
01:32:48
we type out our condition as while command
01:32:52
does not equal to quit then do something.
01:32:56
Now immediately we have a problem here because we're assuming that the user
01:33:00
types the command in lower case, so if they type this in upper case they
01:33:04
our program is not going to behave properly, so to fix this problem, you need to
01:33:08
call the lower method of the string object and then compare the results.
01:33:12
With this quit. You could also call this upper
01:33:16
and then type quit in upper case. It's about our personal preference
01:33:20
in this demo I'm going to use lower case characters.
01:33:24
So, okay, now in this loop we need to ask the user to enter
01:33:28
a command. So once again we're going to use our input function, we're going to add
01:33:32
a greater then symbol followed by a space,
01:33:36
whatever the user enters, we get it and store it in our
01:33:40
command variable. Now apart from
01:33:44
quit command, there are three other commands that we need to support. Start,
01:33:48
stop, and help. So here we need an if statement to compare
01:33:52
what the user enters with one of the supported commands.
01:33:56
So, if command.lower
01:34:00
equals start then you want to print the message
01:34:04
like the car started. So print the car started.
01:34:08
Ready to go, it doesn't matter,
01:34:12
now the second condition. What if its not start, maybe it's stop? So,
01:34:16
el if command.lower
01:34:20
equals stop, there you go, then we print a
01:34:24
different message car stopped. Now look at our code.
01:34:28
We have repeated this lower lower lower multiple times.
01:34:32
This is bad, in programming we have a term called dry, which is short for
01:34:36
don't repeat yourself. So whenever you have duplicate
01:34:40
your code that means you're doing something wrong. So how can we solve this problem.
01:34:44
Well, instead of calling the lower method in each condition,
01:34:48
we can call it right here when we get the input from the user, so
01:34:52
this input function as you know returns a string, we can
01:34:56
immediately call the lower method on this string, and with this command
01:35:00
will always be in lowercase, so we don't need to
01:35:04
call this method in every condition. Look,
01:35:08
we remove the duplication and also our conditions
01:35:12
are shorter and easier to read. There is also one more place
01:35:16
we need to modify so, it's right here. That is better.
01:35:20
Now, the third command. We need one more el if.
01:35:24
If the command equals help, then,
01:35:28
we want to show the commands that we support. So,
01:35:32
here we're going to print a multi line string. So we
01:35:36
use triple quotes like this, and
01:35:40
give the user a guideline like this. So start
01:35:44
to start the car stop
01:35:48
to stop the car, and
01:35:52
quit to quit. Now finally we need
01:35:56
an else part, so if what the user enters is none of these commands,
01:36:00
we're going to tell them, hey we don't understand these,
01:36:04
else, colon print
01:36:08
sorry I don't understand that.
01:36:12
And by the way note that here becomes I'm using double
01:36:16
quotes, I can easily use a single quote as an apostrophe, okay?
01:36:20
So let's run our program up to this point and see what happens.
01:36:24
Alright, let's type start car is
01:36:28
started, beautiful, stop, car is stopped, help,
01:36:32
we get this guideline, but there's so much indentation
01:36:36
before our commands, we'll fix that in a second. And finally
01:36:40
let's test the quit command, oops, our program
01:36:44
didn't work properly. Here is the reason. With these if statements,
01:36:48
we're comparing the command with start stop, and
01:36:52
Помогите. Anything else will end up here, so that's why our
01:36:56
program says it doesn't understand that. So that's why our program
01:37:00
says it doesn't understand that command. However, after this el statement
01:37:04
the control will be moved to the beginning of the loop.
01:37:08
At this point our command is quit, so our loop will complete and the
01:37:12
program terminates. In other words when we run this program
01:37:16
and type quit, our program actually quits but
01:37:20
we still see this message which shouldn't appear here. How can we solve this problem?
01:37:24
Well, we can come back here and just before
01:37:28
the else block, add another el if, something like
01:37:32
this. el if command equals
01:37:36
quit then you can immediately break.
01:37:40
This will solve our problem, but note that we have kind of repeated
01:37:44
this expression in two places. The reality is that
01:37:48
we don't really need this condition on the top, because with these if statements
01:37:52
well more accurately with this el if we can jump out of this loop and terminate
01:37:56
our program. So, we can simplify our condition
01:38:00
to something like this. True. So while true means
01:38:04
this block of code is going to get executed repeatedly,
01:38:08
until we explicitly break out of it,
01:38:12
okay? Now let's test our program one more time. So,
01:38:16
quit now our program terminates and we don't see that message
01:38:20
beautiful. So let's fix the last problem. You saw that when we
01:38:24
typed help, these guidelines appeared with so much in
01:38:28
indentation, and here's the reason, look, right here in our code,
01:38:32
they are already indented. So when we use triple quotes, what we type here
01:38:36
will be printed exactly as is. So, because we
01:38:40
have an indentation here, this indentation will also be printed on the terminal.
01:38:44
So, let's delete these
01:38:48
okay, run the program one more time, type help,
01:38:52
the indentation is gone. Красивая. Now here's a challenge for you. I want you to
01:38:56
take this program to the next level. So right now if we type
01:39:00
start we get this message car started. And if we type start again
01:39:04
we get the same message. It would be better if
01:39:08
we got a message like car is already started so it doesn't make sense to
01:39:12
start a car twice. Similarly, if we type stop
01:39:16
it says car stopped, if we type it again we get the exact same
01:39:20
message, it doesn't make sense to stop the car twice. So here's what I need you to do
01:39:24
if the car is stopped and the user tries to stop it again,
01:39:28
the program should say hey, the car is already stopped, what are you doing? And similarly
01:39:32
if the car is already started and the user tries to start it again,
01:39:36
the program should yell at the user. So go ahead and make the necessary changes to
01:39:40
implement this scenario.
01:39:44
Alright to add this to our program, we need
01:39:48
to know if the car is started or not. So there is one more piece of information
01:39:52
we need to store in the memory. What is the kind of data we need to store here?
01:39:56
A boolean. Is the car started or not, it's a matter of yes
01:40:00
or no. True or false. So on the top, here
01:40:04
we can define another variable like started and initially we set it
01:40:08
to false. So the car is not started, right? Now
01:40:12
when the user types the start command, here we need to check
01:40:16
to see if the car is already started. If not the we'll start it
01:40:20
or otherwise we'll yell at the user. So in this block we'll write
01:40:24
another if statement, if it's already started
01:40:28
and we print car is already
01:40:32
started. Otherwise, so if you add an
01:40:36
el statement here. And at this point,
01:40:40
you set started to true. So we start
01:40:44
the car and we print this message, okay? Now we need to make a similar
01:40:48
change for the stop command. So if the car is
01:40:52
already stopped we need to print a different message. Если
01:40:56
not started, so here we're using the not operator to see
01:41:00
if the car is stopped. So if it's not started that means
01:41:04
it's stopped, okay? So if it stopped we print
01:41:08
car is already stopped with
01:41:12
double p's, otherwise so else
01:41:16
we need to stop the car, how do we do that? Мы
01:41:20
set started to false. And then we'll print this message.
01:41:24
As easy as that. Let's go ahead and run our program.
01:41:28
So, initially our car is stopped. So I'm going to type
01:41:32
stop, it says the car is already stopped, so lets
01:41:36
start it, okay, now our car is started, let's
01:41:40
start it one more time. The program is yelling at us. So we can
01:41:44
not start the car twice. Красивая. Now let's stop it
01:41:48
it says the car is stopped, let's stop it one more time, we get this message
01:41:52
again.
01:41:56
In this tutorial, I'm going to talk to you guys about
01:42:00
for loops in python. In the last tutorial, you learned about while loops
01:42:04
you learned that we use while loops to execute a block of code multiple times.
01:42:08
In python we have another kind of loop, that is a for loop, and we use that
01:42:12
and we use that to iterate over items of a collection, such as a string.
01:42:16
Because a string is a sequence of characters, so it looks like a collection
01:42:20
so we can use a for loop to iterate over each character in a
01:42:24
string and then do something with it. Here's an example. We type out
01:42:28
for then we define a variable, this is what we call a loop
01:42:32
variable. In each iteration, this variable will hold
01:42:36
one item. So, let's call it item, in
01:42:40
here we type out a string like Python, and then
01:42:44
colon. So with this for loop we can iterate over a string and in each
01:42:48
iteration this item variable will hold one character at a time
01:42:52
in the first iteration it will be set to p then
01:42:56
in the second iteration it will be set to y, and in the third iteration it will be set to
01:43:00
t and so on. So here we are inside our for block,
01:43:04
because of the indentation here, so whatever we type here will be executed in
01:43:08
each iteration, for now we can simply print this item
01:43:12
now let's run this program and see what happens.
01:43:16
So you can see each character in this string is printed on
01:43:20
a new line. Let's look at another example. In Python we can
01:43:24
define lists using square brackets, so let me remove this string from
01:43:28
here, and define a list using square brackets,
01:43:32
a list is simply a list of items, a list of numbers, a list of
01:43:36
customers, a list of emails, products, blog posts, whatever.
01:43:40
So here we can define a list of names like Mosh,
01:43:44
Jon, Sarah, and then go ahead
01:43:48
and run our program so we can see in each iteration we get one name
01:43:52
and print it on a new line. We can also
01:43:56
loop over a list of numbers, for example,
01:44:00
1, 2, 3, 4, let's run it, again
01:44:04
we see each number on a new line, but what if we want
01:44:08
a list of numbers? We don't to explicitly type out a list
01:44:12
with let's say 100 or 1000 numbers, we don't want to type, 5, 6
01:44:16
7 all the way to 100. That is when we use the range function.
01:44:20
So, let me delete this,
01:44:24
In Python we have a built in function called range, for creating
01:44:28
range of numbers. So, we give it a number, let's say 10,
01:44:32
let's run this program, now we can see
01:44:36
here on the terminal we have 0 all the way
01:44:40
to 9. So 10 is not included.
01:44:44
So basically when we call the range function, this range creates
01:44:48
an object, it's not a list, it's a special kind of object we can
01:44:52
iterate over, in each iteration this object will spit out a new number.
01:44:56
We can also work with a range of numbers here, let's say you want to start
01:45:00
from 5, and go all the way to 10.
01:45:04
So, let's run our program, now we have the numbers
01:45:08
5, 6, 7, and 9. Also, this range
01:45:12
function can optionally take a step, so we can pass
01:45:16
two asa step to this function,
01:45:20
and when we run our program, we can see our first number
01:45:24
is 5, now we go two steps forward to get 7,
01:45:28
once again we go to two steps forward we get 9 and that is
01:45:32
the end of our range. So this is the basics of using for loops in python.
01:45:36
Now here's an exercise for you. I want you to write a program
01:45:40
to calculate the total cost of all the items in a shopping cart.
01:45:44
So let's say we have a list of prices like 10,
01:45:48
20, and 30, I want you to use a for loop,
01:45:52
to calculate the total cost of all the items in our imaginary shopping cart,
01:45:56
so calculate that, and then print it on the terminal. That's pretty
01:46:00
easy. And you should do it in a couple minutes.
01:46:04
So as you learned we use for
01:46:08
loops to iterate over all the items in a collection,
01:46:12
a collection can be a string, it can be a list, it can be a range object that is
01:46:16
returned from the range function. Anything, any kind of object that has multiple
01:46:20
items. So in this example we're going to use a for loop to iterate over
01:46:24
the list of prices. So for item in
01:46:28
prices, colon, and by the way this loop variable
01:46:32
we don't have to call this item, can call this anything. For example, in this case
01:46:36
we can rename it to price. So for price,
01:46:40
in prices. Now in each iteration this
01:46:44
price will hold one value. In the first iteration it's going to hold 10, then it's
01:46:48
gooing to be 20, and then it's going to be 30. So we need to define
01:46:52
another variable to calculate the total so
01:46:56
we define that outside of our for loop, let's call it total
01:47:00
and initially we set it to 0. Now in each
01:47:04
iteration we get the current price and add it to the total so
01:47:08
we write total equals total plus price
01:47:12
or as you learned earlier we can use the augmented
01:47:16
assignment operator to simplify this code.
01:47:20
So, after our for loop. This total variable has
01:47:24
a total of all the prices we can simply print it here,
01:47:28
or we can use a formatted string, so a string
01:47:32
prefix with f, the other label, like total,
01:47:36
curly braces to dynamically include some value in our string,
01:47:40
in this case our total variable. So let's go ahead
01:47:44
and run this program, there you go, so the total cost of
01:47:48
all the items in our imaginary shopping cart is 60.
01:47:56
In this tutorial I'm going to talk to you guys about nested loops
01:48:00
in python. Using a nested loop basically means adding one loop
01:48:04
inside of another loop, and with this technique we can do some amazing things
01:48:08
for example we can easily generate a list of coordinates. So, a
01:48:12
acquired (?) as you know is a combination of x and y
01:48:16
value. Let's say 0 and 0. Now let's say you wan to generate
01:48:20
a list of coordinates like this. So we have 0 and 0,
01:48:24
then we'll have 0 and 1, then 0 and 2, next
01:48:28
we're going to change x, so we're going to use 1 for x,
01:48:32
and once again we're going to use these 3 values for the y coordinates
01:48:36
so 1 and 0 then 1 and 1
01:48:40
and 1 and 2, you got the point. We can
01:48:44
easily generate these coordinates using nested loops. Let me show you.
01:48:48
So, we start with one loop, let's say for x in
01:48:52
range 4. With this loop, we can generate value
01:48:56
for the x coordinate. Let's print this on the terminal,
01:49:00
Okay, so, we get the values, 0
01:49:04
to 3. Now for each x, like 0, we
01:49:08
should generate a few y values. So that is where we use
01:49:12
a nested loop. So inside of this loop we're going to add
01:49:16
another loop, so instead of just printing x first we want to add
01:49:20
another loop, for y in range
01:49:24
let's say 3, now we can print x and y together
01:49:28
so, print, here, we use a formatted string.
01:49:32
to display coordinates like this. So we add parenthesis
01:49:36
inside of this parenthesis first we need to add x so curly braces
01:49:40
x then a comma followed by
01:49:44
another set of curly braces, and y,
01:49:48
let's run this program and see what we get.
01:49:52
There you go. So, we have these coordinates
01:49:56
0 and 0, 0 and 1, 0 and 2, then you have
01:50:00
1 and 0 1 and 1 1 and 2 and so on. So let me explain exactly
01:50:04
how this program gets executed. So in the first iteration,
01:50:08
of our outer loop, x is 0. Now we are
01:50:12
on line 2, here we have a new loop which we call an
01:50:16
inner loop. In this inner loop, in the first iteration y
01:50:20
is going to be 0, so we print 0 and 0 on the
01:50:24
terminal. Now the control goes back to line 2 or our
01:50:28
inner loop. In this second iteration y will be set to 1, but
01:50:32
we are still in the first iteration of our outer loop. Так
01:50:36
x is still 0, but now y is incremented to 1.
01:50:40
So that is why we see 0 and 1 on the terminal.
01:50:44
Once again, the control goes back to line 2, we are in the third
01:50:48
iteration of our inner loop, so this will continue until our inner loop
01:50:52
completes. That is when y reaches 2 because
01:50:56
this range function generates number 0 to 3 but not including
01:51:00
3. So we'll have 0 1 and 2. After this inner loop completes,
01:51:04
then the control goes back to line 1, and at this point we're going to
01:51:08
be in the second iteration of our outer loop. So x will be
01:51:12
1, then the control will be moved to line 2, or our inner
01:51:16
loop, at this point, this range function is going to generate the numbers 0
01:51:20
to 3 one more time. So this inner loop will be executed 3 times.
01:51:24
And then we'll go back to our outer loop. So this is how
01:51:28
nested loops get executed.
01:51:32
Okay, here's an exercise for you, but this one is a little bit
01:51:36
more challenging then the exercises you have done so far. So I really don't
01:51:40
expect you to do it, but if you do it, wow, I will be so proud of you,
01:51:44
so see what I've done here? Using nested loops,
01:51:48
I've written some code to draw this f shape, can you see that? So I
01:51:52
let me give you a hint, first of all we have this
01:51:56
list, called numbers, in this list we have these values,
01:52:00
5, 2, 5, 2, 5, 2. These values determine
01:52:04
the number of x's we have in each line. So,
01:52:08
for example, the first item in this list, this tells us that we should have
01:52:12
5 x's on the first line. There you go, so 1, 2, 3,
01:52:16
4, 5, on the second line we're going to have 2 x's,
01:52:20
on the third line we're going to have 5 x's like this.
01:52:24
So I've written code to convert a simple list of numbers
01:52:28
into a shape like this. Now here's a tip for you.
01:52:32
Using your for loop you need to iterate over this list. В
01:52:36
each iteration you get one number, this determines the number of x's
01:52:40
to be displayed on that particular line. So if you want to cheat,
01:52:44
you can get this number and multiply by a string that contains x,
01:52:48
so if you multiply x by 5, we'll get 5 x's, that's not what
01:52:52
I want you to do. I want you to use an inner loop here to
01:52:56
generate a string that contains 5 x's. So imagine
01:53:00
in Python we cannot multiply a string by a number
01:53:04
so to solve this problem we need a nested loop. So go ahead and spend
01:53:08
five minutes on this exercise. And by the way, do your best to solve this. It is
01:53:12
a little bit challenging, but it's not extremely difficult. It just requires
01:53:16
a little bit of focus. You'll see my solution next.
01:53:20
Alright so first we need to iterate over
01:53:24
all the items in this list. So for item
01:53:28
in numbers, or, you could rename this variable
01:53:32
to x_count. That is the number of x's
01:53:36
on each line. Okay? Now I told you that if you want to cheat you can write code
01:53:40
like this. Print x times
01:53:44
x underline count. If you run this program we get the same
01:53:48
output. So this is the beauty of Python, with Python
01:53:52
we can write expressions like this, we can multiply a string by a number to
01:53:56
repeat it. A lot of other programming languages don't support this feature. But
01:54:00
for this exercise, I wanted you to imagine that we don't have this feature in Python
01:54:04
so you will have to use an inner loop to solve this problem. Here's how
01:54:08
it works. In the first iteration, x count is going to be 5.
01:54:12
So we need to generate 5 x's. How can we do that?
01:54:16
Well, let's say we define a variable called output and initially set it to
01:54:20
an empty string. Now we need to add 5 x's to this string. So,
01:54:24
we can use another loop for count in range,
01:54:28
of x underline count. So we're using the range function
01:54:32
to generate a sequence of numbers from 0 up to
01:54:36
x count. So in our first iteration x count is going to be 5, so
01:54:40
range of 5 would generate the numbers 1, 2, 3, 4.
01:54:44
So this inner loop will be executed 5 times.
01:54:48
That is exactly what this count represents.
01:54:52
So now in each iteration we simply need to
01:54:56
append an x to our output variable. So we set
01:55:00
output, plus, equals x,
01:55:04
and then after this inner loop we simply print
01:55:08
the output. With his we'll print 5 x's on
01:55:12
the first row. Then we go to the second iteration of our outer loop.
01:55:16
At this point x count is going to be 2, now
01:55:20
on line 3, we're going to reset our output variable to an
01:55:24
empty string. So we start over. Then we go to our inner loop,
01:55:28
this loop will be executed 2 times, so we'll append to x's
01:55:32
to the output variable and then print it, as simple as that.
01:55:36
So see, it wasn't really that difficult, but it was slightly more difficult then the
01:55:40
previous exercises. So let's run this program, there you go.
01:55:44
Now if you're adventurous, I want you to modify the values that we have
01:55:48
in our numbers list,
01:55:52
to print and l here.
01:56:00
Now in this tutorial we're going to take a closer look at lists.
01:56:04
So, I'm going to define a list of names, let's send them
01:56:08
to John Bob Mosh
01:56:12
Sarah and Mary. So,
01:56:16
if you print this list here, what we see on
01:56:20
the terminal look exactly like how we define our lists we have
01:56:24
square brackets, and in between these square brackets we have our item
01:56:28
our items, so we have 5 strings in this list.
01:56:32
So we can also access an individual element using an index just like
01:56:36
how we can access an individual character in a string using an index.
01:56:40
So, here we type out square brackets,
01:56:44
and specify an index. The index of the first item in this list
01:56:48
is 0. So, let's run this program, there you go,
01:56:52
we get Jon now if you want to print out the third element in this list
01:56:56
it's index is 2, so names of 2,
01:57:00
returns Mosh, now we can also pass
01:57:04
a negative index here, so negative 1, refers to the last item
01:57:08
in this list, that is Mary, let's run the program,
01:57:12
there you go, we see Mary, if you pass negative 2, this
01:57:16
returns the second item from the end of the list. So let's run the program,
01:57:20
there you go, we get sarah, so this is exactly like accessing
01:57:24
individual characters in a string. We can also
01:57:28
use a colon to select a range of items, for example if
01:57:32
you pass 2 colon. This will get all items
01:57:36
starting from the index of 2, that is Mosh here all the
01:57:40
way to the end of the string. So let's run this program
01:57:44
there you go. We get this list with 3
01:57:48
items, Mosh, Sarah, and Mary. We can also specify
01:57:52
an end index, let's say 4, so this will return all
01:57:56
the items up to this index, but it doesn't include the item at this index.
01:58:00
So when we run this program we only see Mosh and
01:58:04
Sarah, the item I've indexed 4which is the 5th element or
01:58:08
5th item in this list is not returned. So Mary
01:58:12
is not returned. And also here we have default values, so if you
01:58:16
leave out the end index this expression is going to return
01:58:20
all the items starting from the index of 2, to the end of the list
01:58:24
or if you leave out the start index, this expression asumes
01:58:28
0 as the default index, so it will return all the items from the
01:58:32
beginning to the end of the list. And by the way,
01:58:36
just like strings, these square brackets here, don't modify our
01:58:40
original list, they simply return a new list. For example, if we pass
01:58:44
2 here, you can see this returns a new list with 3 items.
01:58:48
So if you go back here and print our original
01:58:52
list of names right after you can see it's not affected.
01:58:56
So here we want to use square brackets with a colon to select a
01:59:00
range of items, we get a new list, and by the way we can also
01:59:04
modify any of the elements in this list. For example let's say we made a mistake and
01:59:08
the first item shouldn't be john with an h,
01:59:12
so we want to remove the h, that is very easy, so we access it,
01:59:16
using an index that is names of 0, and we set it to a new value
01:59:20
like this. Now, let's print our list
01:59:24
so, you can see the first item in this list
01:59:28
is now data. So this is the basics of lists. And here's a
01:59:32
exercise for you. I want you to write a program to find the largest number
01:59:36
in your list. This is a fantastic exercise for beginners, so go ahead and
01:59:40
spend a few minutes on this, then come back and continue watching.
01:59:44
Alright, let's
01:59:48
define a list of numbers, numbers, with a bunch of random numbers
01:59:52
3, 6, 2, 8, 4 and 10.
01:59:56
Now to find the largest number in this list. We need to define another
02:00:00
variable let's call it max, this variable will hold
02:00:04
the largest number, now initially you want to assume
02:00:08
the first item in this list is the largest number. So we set max to
02:00:12
numbers of 0. We're only assuming that the first item
02:00:16
is the largest number. Chances are our assumption is wrong. So we need
02:00:20
to iterate over this list, we need to loop through it, get
02:00:24
each item and compare it with max. If it's greater than Max, then
02:00:28
we need to reset max to that number. So in the first iteration we get
02:00:32
3, and max is also 3. Is 3 greater than
02:00:36
3. No, so we move on, we get the second number, is
02:00:40
6, greater than 3? It is, so we need to reset max
02:00:44
to 6. Once again, we continue, we get 2, these two greater
02:00:48
than 6, no it's not, so we move on, then we get 8,
02:00:52
is 8 greater than 6? It is, so we should reset max to 8.
02:00:56
That is pretty easy. So here we need a for loop, for
02:01:00
number in numbers colon
02:01:04
now we need too heck to see if this number is greater than max,
02:01:08
so, if number is greater than max,
02:01:12
max colon then we need to reset max, so max
02:01:16
to this new number, that's all we had to do.
02:01:20
So, let's print max, and run our
02:01:24
program we can see the largest number in this list is 10.
02:01:28
It doesn't matter whether this number is at the end of the list or the beginning.
02:01:32
So if I move 10 and put it right at the beginning
02:01:36
we should still see the same result. Let's run our program,
02:01:40
we still see 10, if I put this somewhere in the middle, our
02:01:44
program should still work. Let's put it right after 2.
02:01:48
Run the program, we still get 10.
02:01:56
In this tutorial I'm going to talk to you guys about two dimensional
02:02:00
lists in python. Two dimensional lists are extremely powerfully and they have a lot
02:02:04
if applications in data science and machine learning. Here's
02:02:08
an example, In math we have a concept called matrix, which is like
02:02:12
a rectangular array of numbers, let me show you. Так
02:02:16
we have 1, 2, 3, 4, 5, 6, 7, 8, 9.
02:02:20
So we have a rectangular array of numbers. You have rows,
02:02:24
and columns. So this is a 3 x 3 matrix
02:02:28
in math. Now we can model this in python using
02:02:32
a 2 dimensional list. A 2 dimensional list is a list where
02:02:36
each item in that list is another list. So,
02:02:40
you want to define a matrix. We set it to a list, each
02:02:44
item in this list, is going to be another list, and that list represents
02:02:48
the items in each row. So, the first
02:02:52
item in our list is going to be another list, and in this other list we're going to have
02:02:56
the values 1, 2, and 3. Now the second
02:03:00
item in our matrix list, once again, we have a list,
02:03:04
this list represents the items in the second row. So,
02:03:08
4, 5, and 6, and finally 7, 8
02:03:12
9. So as you can see we have a 2 dimensional list
02:03:16
Each item in our outer list is another list.
02:03:20
Okay? So, this is how we can implement a matrix in
02:03:24
python, now to access an individual item in our matrix,
02:03:28
once again we use square brackets, let me delete this stuff,
02:03:32
alright, so how do we access 1 here,
02:03:36
well, you start with our list then we add square
02:03:40
brackets first we need to go and get the first item in this list.
02:03:44
Правильно? So we pass 0, now this expression
02:03:48
returns another list. That is the inner list. In this list,
02:03:52
let's say you want to access the second item, so,
02:03:56
once again we add square brackets, and we pass 1, that
02:04:00
is the index of 2 in this list, alright.
02:04:04
So if we print this on the terminal
02:04:08
we get 2. Okay? So using 2 square brackets
02:04:12
we can access individual items in our matrix, and
02:04:16
also we can modify these values using this syntax, so,
02:04:20
before printing this, let's change this to 20, so matrix
02:04:24
of 0, and 1, let's change it to 20,
02:04:28
and then print it, there you go, it's modified, now here you
02:04:32
can also use nested loops to iterate over all the items
02:04:36
in this matrix. Let me show you. So,
02:04:40
we start with a rows for the rows in matrix,
02:04:44
so with this loop, we are iterating over our Matrix
02:04:48
list, in each iteration row will contain 1
02:04:52
list, 1 item, okay? Now, here we need to
02:04:56
use an inner loop. So we need to loop over this row
02:05:00
which is a list of items. We can type out 4
02:05:04
item in row colon and print
02:05:08
item. Okay? So, let's run this program,
02:05:12
there you go, we get all the item
02:05:16
in our list. Hey, I just
02:05:20
wanted to make a quick announcement. In case you haven't seen my website yet, head over to codewithmosh.com
02:05:24
this is my coding school, where you can find plenty of courses
02:05:28
on web and mobile application development. In fact recently I published a
02:05:32
comprehensive python course that goes way beyond this beginners
02:05:36
youtube. And if you're serious about learning python and getting a job, I highly encourage
02:05:40
you to enroll in this course. Just like this tutorial you can watch it anytime,
02:05:44
anywhere as many times as you want, and you will also receive a certificate
02:05:48
of completion that you can add to your resume, and the course comes with a 30 day
02:05:52
money back guarantee, so if you're not happy we'll give all your money back,
02:05:56
no questions ask. The price for this course is 149 dollars, but
02:06:00
the first 200 students can get it for only 15 dollars. So if you're interested,
02:06:04
the link is below this video, click the link, and get started.
02:06:08
In this tutorial, I'm
02:06:12
going to talk to you guys about the list methods, or list functions. These are the
02:06:16
operations that we can perform in a list. So let's define
02:06:20
a list of numbers, here we pass a bunch of random numbers, like
02:06:24
5, 2, 1, 7, and
02:06:28
4. Now there are a number of things we can do with this list, we can
02:06:32
add new items to it, we can remove existing items, we can check for the existence of an item
02:06:36
these are the operations that we can perform on a list. So,
02:06:40
the we type numbers, we can see all these functions or more accurately
02:06:44
the methods that are available in our list objects.
02:06:48
So we can call the append method to add a new item to this list. Let's say
02:06:52
13. Actually, no it's not a good number.
02:06:56
I'm joking I'm not superstitious, so let's add 20, it
02:07:00
doesn't really matter and then print our list
02:07:04
when we run the program we can see 20 is added at the end of this list
02:07:08
but what if you want to add a number somewhere in the middle, or at the beginning
02:07:12
of our list? For that we use a different method, that is called
02:07:16
insert. So, insert, now this method
02:07:20
takes 2 values, let me show you. So when we open parenthesis
02:07:24
look at this little tool tip above the insert method.
02:07:28
You see the first value that we need to pass here is an index, so
02:07:32
this is the index at which we want to insert this new item. Let's
02:07:36
say we want to add an item at the beginning of our list, so we passed our index position
02:07:40
of 0, and then the second value is the actual
02:07:44
object we want to add to this list. Let's say we want to add the number 10,
02:07:48
now when we print this list you can see that the
02:07:52
number 10 is placed at the beginning of the list and
02:07:56
all the other items are pushed to the right. We can also remove an item so
02:08:00
we call remove and pass the item that
02:08:04
we want to remove 5. Now we
02:08:08
print our list so we see 5 is gone, and we have
02:08:12
2, 1, 7, 4. If you want to remove all the items in the list, you can call
02:08:16
the clear method, so, clear
02:08:20
this method doesn't take any values, so, we simply
02:08:24
call it and it empties our list, all the items are removed.
02:08:28
We also have another useful method called hop,
02:08:32
and with this we can remove the last item in a list.
02:08:36
Let me show you. So, we run our program, you can see the number 4
02:08:40
is removed from the end of our list. Now if you want to
02:08:44
check for the existence of an item in our list, you can call the index method.
02:08:48
So, we call index and pass a value here, like 5
02:08:52
and this returns the index of the first
02:08:56
occurrence of this item. So let's print this on the terminal.
02:09:00
We don't need this line anymore. So the
02:09:04
index of 5 is 0. What if we pass a number that doesn't exist
02:09:08
in this list? Let's say 50? Run the program,
02:09:12
we get an error. We get a value error. 50 is not
02:09:16
in the list. There is also another way to check for the existence of an item,
02:09:20
we can use the in operator. So, let me show you
02:09:24
we type our 15 in numbers,
02:09:28
earlier we used the in operator with a string, we
02:09:32
check for the existence of a character or a sequence of a character in a string,
02:09:36
now here we're checking for the existence of 50 in the list of numbers, so
02:09:40
let's print this, we get a boolean value,
02:09:44
false, so unlike the index method, this expression,
02:09:48
doesn't generate an error, so it's safer to use this. We also have another
02:09:52
method for counting the occurances of an item, let's say we have
02:09:56
another 5 over here.
02:10:00
Now we can call numbers.count and pass 5
02:10:04
and this should return 2 because we have 2 5s in this list.
02:10:08
Take a look. There you go. That is pretty useful
02:10:12
now if you want to sort your lists you can call sort method. So,
02:10:16
we call the sort method here, this method doesn't take any values so,
02:10:20
look at he return value, that is none, none
02:10:24
is an object in python that represents the absence of a value.
02:10:28
So this sort method doesn't really return any values it simply sorts this
02:10:32
list, in place, so instead of printing the return value
02:10:36
oft his method, we simply call it to sort our list
02:10:40
and then print our list. Take a look.
02:10:44
Now, all the items are assorted in ascending order. We can also
02:10:48
sort the items in descending order, so after we sort the list
02:10:52
we can call the reverse method. We can simply reverse
02:10:56
our list. Now let's go ahead and run our program, take a look.
02:11:00
Our numbers are sorted in descending order.
02:11:04
And one last method I want to show you here that is pretty useful is the copy
02:11:08
method. So copy, with this method you can get a copy
02:11:12
of our list. So let's define another variable called numbers 2,
02:11:16
now numbers 2, is a copy of our original list. So if
02:11:20
you make any changes to our original list, if you add new items to it, if you remove
02:11:24
existing items, these operations are not going to impact our second list.
02:11:28
Let me show you. So after we show you a copy of our numbers list
02:11:32
let's add a new item to this list, so numbers.apphend
02:11:36
ten. So the first list is updated, so now we have a
02:11:40
new item in our first list, then lets print the second list.
02:11:44
Take a look, we don't have the number 10 here, because these are
02:11:48
2 independent lists. So these are all the operations
02:11:52
that we can perform on lists. We can add new items to a list, we can
02:11:56
remove exxisitn items, we can check for the existence of an item, we can sort
02:12:00
our list, and copy them. Now here's an exercise for this tutorial,
02:12:04
I want you to write a program, to remove the duplicates on our list.
02:12:08
Again, this is a fantastic exercise. So spend a few minutes on this and then
02:12:12
come back and continue watching.
02:12:16
Alright let's say we have a list of numbers with
02:12:20
a bunch of duplicates. So 2, 2, 4, 6,
02:12:24
6, 3, 4, 6, 1. We want to remove
02:12:28
the duplicates. So we need to define another list
02:12:32
let's call that new list. Initially we
02:12:36
set it to an empty list. Then we need to iterate over
02:12:40
our first list, get each item, and if we don't have that number
02:12:44
in this unix list, then we'll add it to this second list.
02:12:48
As simple as that. So, for number
02:12:52
in numbers, now we need to check to see if we
02:12:56
have this number in the second list. So we use the in
02:13:00
operator. If number not
02:13:04
in units
02:13:08
so if we don't have an operator in this units list,
02:13:12
then we'll need to add it, so units.
02:13:16
apphend number, that's all we have to do.
02:13:20
So, let's go ahead and print the units list
02:13:24
there you go. So you have 2, 4,
02:13:28
6, 3,and 1. The duplicates are removed.
02:13:36
In this tutorial I'm going to talk to you guys about another important structure.
02:13:40
in Python called tuple. Tuples are similar to lists
02:13:44
so we can use them to store a list of items. But unlike lists we can
02:13:48
not modify them, we cannot add new items, we cannot remove existing items, we
02:13:52
tuples are immutable. We cannot mutate or change them. Так
02:13:56
let me show you. So I'm going to start by defining a list of numbers,
02:14:00
1, 2, 3, 4, so we use square brackets to define lists and
02:14:04
parenthesis to define tuples, so if we change this to
02:14:08
parenthesis, 1, 2, 3. Now we have a
02:14:12
tuple. So if we type numbers.
02:14:16
look here we don't have the append or insert methods, so we cannot add new items to this tuple.
02:14:20
We also don't have remove clear and pop, we cannot
02:14:24
remove any of these items here. We only have two methods, count,
02:14:28
and index. We use count to count the number of occurrences in an item,
02:14:32
and index, to find the index of the first occurrence,
02:14:36
of an item. So we can only get information about a tuple, we can't change it.
02:14:40
And by the way, these other methods that you see here, they start
02:14:44
with two underscores, we refer to these as magic methods, they're more of an advanced
02:14:48
topic, so they go beyond the scope of this tutorial. If you're interested
02:14:52
to learn bout them. You can get my python course, I've covered them in detail.
02:14:56
So similar to lists you can address individual items using
02:15:00
squre bracketts,so we can get the first item like this and then
02:15:04
print another terminal, there you go, the first item is 1,
02:15:08
but if you try to change the first item we'll get an error, so,
02:15:12
numbers of 0, we set it to 10 and run our program
02:15:16
there you go. We get this type error, because the tuple object
02:15:20
does not support item assignment. So we cannot
02:15:24
mutate or change tuples, they are immutable. Now practically
02:15:28
speaking, most of the time you'll be using lists, but tuples are also
02:15:32
useful. If you want to create a list of items and make sure
02:15:36
no where in your program you accidentally modify that list, then it's better to
02:15:40
use a tuple,
02:15:44
In this tutorial I'm going to show you a powerful
02:15:48
feature we have in python called unpacking.
02:15:52
So lets find a tuple called coordinates
02:15:56
and here we pass 3 values, 1, 2, 3. So you imagine these are
02:16:00
the coordinates for xy and z. Now let's say
02:16:04
we want to get these values and use them in a few expressions, a few complex
02:16:08
expressions in our program. Maybe we want to include them as part of a large
02:16:12
complex formula. So together we'll have to write code like this,
02:16:16
coordinates of 0, then let's say we want to multiply this
02:16:20
by coordinates of 1, and then multiply it by coordinates
02:16:24
of 2, our code is getting a little bit too long, this is just
02:16:28
a very simple example. But let's say we want to use these values in quite a few places
02:16:32
in our program, a better approach is to get these values
02:16:36
and store them in separate variables like we can get
02:16:40
coordinates of 0, and store it in x, then you can
02:16:44
get coordinates of 1 and store it in y.
02:16:48
And similarly we get coordinates of 2,
02:16:52
and then store it in z. Now we started repeating coordinates of
02:16:56
2 or coordinates of 0 multiple times, we can simply work with these
02:17:00
variables, x times y times z, that is better.
02:17:04
Правильно? So nothing new so far. But in Python we have a powerful
02:17:08
feature called unpacking and with that we can achieve
02:17:12
the same result with far less code. So we can define our variables
02:17:16
x, y, and z. And set them to our
02:17:20
tuple. What we have on line 6 is exactly
02:17:24
identical to what we have on lines 2-4.
02:17:28
So this is a shorthand to achieve the same result.
02:17:32
So let me delete this and explain how this code works.
02:17:36
When Python interpreter sees this statement, it will get the
02:17:40
first item in this tuple and assign it to the
02:17:44
variable. Then it will get the second item in this tuple, then
02:17:48
similarly we get the third item in this tuple and assign it to
02:17:52
the third variable we have here, so we are unpacking
02:17:56
this tuple into 3 variables. Now if we
02:18:00
print x you can see x
02:18:04
is 1, similarly y is 2, there you go.
02:18:08
So this is unpacking. And by the way this is not
02:18:12
limited to tuples, we can use this feature for lists as well. So,
02:18:16
if I change parenthesis to square brackets, now
02:18:20
coordinates is a list, so we can unpack our list into 3 variables
02:18:24
now we run our program we can see y is 2.
02:18:32
In this tutorial I'm going to talk to you about dictionary
02:18:36
in python. We use dictionaries in situations where we want to
02:18:40
store information that comes as key value pairs. Here's
02:18:44
an example. Think of a customer. A customer has a bunch of attributes
02:18:48
like name, email, phone number, address
02:18:52
and so on. Now each of these attributes has a value.
02:18:56
For example the name can be jon smith the email can be
02:19:00
jon@ gmail.com the phone can be whatevr
02:19:04
so what we have ere is a bunch of key value pairs. So in this
02:19:08
example, our keys are name, email, and phone,
02:19:12
and each key is associated with a value. So this is where we use
02:19:16
a dictionary. With a dictionary, we can store a bunch of key value pairs.
02:19:20
So let me show you how to define a dictionary in python.
02:19:24
Back to our program, I'm going to define a variable, customer,
02:19:28
and here we set it to curly braces. With these curly braces we can
02:19:32
define dictionary. In this example we have an empty dictionary that doesn't have
02:19:36
any key value pairs. Now we can add one or more key
02:19:40
value pairs in between the braces. So let's
02:19:44
add a key value pair here, I'm going to set the key to a name, and
02:19:48
the value to John Smith, then we add a comma,
02:19:52
to add another key value pair. So let's set age to
02:19:56
30 let's add another key value pair is
02:20:00
underline verified and we set this to a boolean.
02:20:04
Now what matters here is that these keys should be
02:20:08
unique. So if I add another key value pair here,
02:20:12
set age to 40, now look pycharm
02:20:16
has highlighted the age key, because we have duplicated that and
02:20:20
that's not allowed. So each key should be unique in a dictionary, just like,
02:20:24
the dictionaries we have in the real world, in a real dictionary we have a bunch of words
02:20:28
and they're definition each word is only listed once in a dictionary.
02:20:32
We don't have the word book twice. So let's delete the second
02:20:36
duplicate key value pair, so the keys should be unique,
02:20:40
and in this example, I'm using strings, but they can also be
02:20:44
numbers, we're going to look at that later, but the value can be anything, it can be
02:20:48
a string, a number, a boolean, a list, literally anything.
02:20:52
Now we can access each item in this dictionary
02:20:56
using square brackets. So, we type customer,
02:21:00
square brackets and then specify key like name
02:21:04
and this will return the value associated with
02:21:08
the name key. Let's print it on the terminal, have a look,
02:21:12
there you go, so, the name is John Smith, now
02:21:16
what if we pass a key that doesn't exist, lets say first date.
02:21:20
You run the program, you get a key error because we don't have
02:21:24
a key called birth date. Also, if we spell
02:21:28
name with let's say a capital N, we get the same
02:21:32
error because we don't have a key with the exact same sequence of
02:21:36
characters in this dictionary. Now to get around this we can
02:21:40
use the get method, so instead of using the square brackets
02:21:44
we call the get method and specify the key
02:21:48
Now if you use a key that doesn't exist here, it doesn't yell at us. Например,
02:21:52
if you pass birth date
02:21:56
it simply returns the non value. Earlier I told you that none is an object
02:22:00
that represents the absence of a value. Так
02:22:04
instead of getting a key error we get none and we can also option
02:22:08
supply a default value, for example, if this dictionary doesn't have this
02:22:12
key, we can supply the default value, let's say
02:22:16
January 1st 1980. Let's run the program
02:22:20
now instead of getting none we get this default value.
02:22:24
So, this is how we can access the value associated with the key
02:22:28
in a dictionary. We can also update these values for example
02:22:32
before a print statement we can write code like this, customer of
02:22:36
name, let's update the name to jack
02:22:40
smith, now this little warning is telling us here we can put jac
02:22:44
smith here instead of defining it once, and then update
02:22:48
Это. Don't worry about them, it doesn't really matter. Now with this line if
02:22:52
we print the name of this customer, we should see jack smith, let me show you.
02:22:56
So, I'm going to use the square bracket notation again, let's print
02:23:00
the name of the customer you can see that is updated here,
02:23:04
we can also add a new key here, let's set the
02:23:08
birthdate to some value like january first
02:23:12
1980. And then we can print it here,
02:23:16
so as you see we can easily add new key value pairs
02:23:20
to a dictionary. So this is the basics of using dictionaries
02:23:24
in python. They're extremely important and they have a lot of applications in the real
02:23:28
world. Okay, here's an exercise for you. So here we have
02:23:32
this program that asks our phone number. Let's type 1
02:23:36
234. We type it in digits and then this will translate
02:23:40
it, to words, take a look. Enter, it prints, 1, 2, 3,
02:23:44
4. That's a pretty cool program, so go ahead and
02:23:48
spend a few minutes on this exercise, it's pretty easy, I will see you
02:23:52
next.
02:23:56
Alright, so first we need to get the users phone number, we call the input function
02:24:00
with the label phone, we get the result and store it
02:24:04
in this variable, now let's say the user enters 123
02:24:08
4. So we need to look through this string, get each character and
02:24:12
translate it to a world, so what we need to implement this scenario.
02:24:16
is a dictionary, because a dictionary is a structure that allows us to
02:24:20
a key to a value. So we can have a dictionary with keys
02:24:24
like 1234. And we map each of these keys
02:24:28
to a word. So we cannot put digit 1 to
02:24:32
the word 1 we can map 2
02:24:36
to two you get the point. So let's define
02:24:40
a dictionary, you can call it digits, underline mapping
02:24:44
now this dictionary I'm going to add a few key value pairs.
02:24:48
One, we map it to 1, 2, we
02:24:52
to 2, 3, to 3,
02:24:56
and finally, 4 to 4. Now technically we should
02:25:00
add all the digits from 0 to 9, but I don't want to waste all your time
02:25:04
typing repetitive things here, you got the point. So lets move on,
02:25:08
now we need to look through the phone string. Так
02:25:12
4 character in phone, we get each
02:25:16
character and then use it to access a key value pair in
02:25:20
dictionary. So, digits underline mapping
02:25:24
we can use square brackets or call the get method,
02:25:28
I would prefer to use the get method, so in case the user enters some character
02:25:32
that is not part of our dictionary, our program is not going to yell at them.
02:25:36
So, we call the gt method and pass this character
02:25:40
a the key, and if we don't have this key, we can supply
02:25:44
a default value like exclamation mark, so with this we get a word
02:25:48
now we need to add this word to an output string, so we can define
02:25:52
an output string, initially we set it to an empty string,
02:25:56
in each iteration we get this and add it to our output string.
02:26:00
So, we type output, plus equals.
02:26:04
This and we should also add a
02:26:08
space at get. So the words are not close to each other, okay?
02:26:12
That's all we have to do. Now finally let's print
02:26:16
this output, run our program, so I want to
02:26:20
type 1, 3,4, 5, lets
02:26:24
see what we get. We get 1, 3, 4 with an exlamantion
02:26:28
mark.
02:26:32
In this tutorial I'm going to show you something really cool
02:26:36
that you can do with dictionaries, so here in this program you can type
02:26:40
a message like good morning followed by a smiley face,
02:26:44
when we press enter, we get this beautiful smiley face, or
02:26:48
we can type i am sad, with a sad smiley face
02:26:52
and it gets translated to this beautiful emoji.
02:26:56
So this is another application if using dictionaries, we have a dictionary
02:27:00
that maps these characters into smiley faces.
02:27:04
So lets go ahead and build this program together, we start by
02:27:08
calling the input function, here we pass a greater than symbol
02:27:12
as an indicator for the user to type a message, we give that message, store
02:27:16
it here, as you know that is a string, now we need to
02:27:20
split this string by a space, so if the user types
02:27:24
good morning with a smiley face, we want to break this down into
02:27:28
3 words, good morning, and smiley face.
02:27:32
To do that we can call the split method. So we call
02:27:36
message.split and pass
02:27:40
a string with one space as a separator. What this method
02:27:44
does is basically it goes through this string and anywhere it finds this
02:27:48
character, in this case a space, it uses it as a boundary to
02:27:52
separate this string into multiple words. And then it will return
02:27:56
a list. Let me show you. So let's store that here, words, and then
02:28:00
Then print it on the terminal,
02:28:04
let's go ahead and run our program. So if you type good morning
02:28:08
sunshine, enter, we get a list with three items
02:28:12
each item is a string, okay? Сейчас,
02:28:16
back to our program, we need to define a dictionary for mapping special characters
02:28:20
like these 2 into a smiley face, so,
02:28:24
we can call that emojis
02:28:28
set it to curly braces, here we add a key value pair,
02:28:32
a smiley face, and we map that to a string,
02:28:36
in this string we want to add an emoji, if you're on a mac keyboard you can press
02:28:40
control command and space and this should bring up
02:28:44
this emoji box, if you're on Windows honestly I
02:28:48
really don't know how you can do this, but there must be applications who do this for you. So lets go
02:28:52
ahead and pick this happy smiley face, good,
02:28:56
now lets add another key value pair, or sad face
02:29:00
we map this to,
02:29:04
this face here, good. So, we
02:29:08
have a list of words now we need to look through this list, get
02:29:12
each word and potentially map it to an emoji.
02:29:16
So we can write a for loop for word in words,
02:29:20
now we want to go to our dictionary, and see if you have an item with this
02:29:24
word as the key. If you have an item with that key, we get
02:29:28
it's value, otherwise we want to use the same word. So if a user types
02:29:32
good morning, we don't want to translate those words, we just want to return those. So that is the case,
02:29:36
where we use the get method to supply a default
02:29:40
value, so we wan to get an item with a key word, and
02:29:44
if we don't have an item with that key, we simply use that word as
02:29:48
the default value. Now similar to the exercise that we did in the last tutorial
02:29:52
we need an output variable. So let's define that here,
02:29:56
output set it to an empty string, now back to line
02:30:00
9, we get the return value of the get method,
02:30:04
and add it to our output variable. So output
02:30:08
plus equals whatever we get from the get method, and finally
02:30:12
we need to append a space at the end.
02:30:16
That's it, we're done. So let's print the output
02:30:20
and run our program and I'm going to type good morning
02:30:24
sunshine with a smiley face, we get that
02:30:28
beautiful, let's try the sad face as well, I am sad.
02:30:32
Очень плохо. Beautiful! So as you can see
02:30:36
dictionaries have a lot of use cases in real applications.
02:30:44
Here's a solution from the last tutorial where we created an emoji
02:30:48
converter. Now so far we have been writing all our code right here,
02:30:52
in app,py, but as our programs grow we need a better way to organize our code.
02:30:56
We need to break up our code into smaller, more manageable
02:31:00
and more maintainable chunks which we call functions. So function
02:31:04
is a container for a few lines of code that perform a specific
02:31:08
task for example you have learned about a few of the built in functions in
02:31:12
python like print, and input, each of these functions
02:31:16
have a purpose, they know how to perform a specific task. So when we
02:31:20
build large complex programs, we should break up our code into smaller
02:31:24
reusable chunks which we call functions to better organize our code.
02:31:28
And that's what I'm going to show you in this tutorial. So let's write this simple
02:31:32
program, for printing a greeting message. So we're going to do a print,
02:31:36
hi there, and lets add another message
02:31:40
welcome aboard. So here we have a simple
02:31:44
program with only two lines of code. Now let's say these two lines
02:31:48
potentially we're going to need them in other programs so we can put them in a function that
02:31:52
we can reuse. Let me show you how to do that, so,
02:31:56
we start typing out death, that is a reserve keyword in
02:32:00
Python, and it's short for define. When Python interpreter sees this it
02:32:04
knows that we're defining a function, next we need to give our function
02:32:08
a name, lets say greet_user.
02:32:12
So all the best practices you learned about naming your variables also apply here,
02:32:16
which means we should name our functions with lower case characters
02:32:20
if there are multiple words, we need to separate them using an underscore
02:32:24
and you should always, always, always use meaningful
02:32:28
descriptive names for your functions. So, here we define a function
02:32:32
called greet user, after that we'll need to add parenthesis
02:32:36
followed by a colon. Now you know that whenever we add a colon at the end of a line
02:32:40
we're telling python that we're defining a block of code. So when we
02:32:44
press enter, the next line is indented. Now any code that we write here
02:32:48
will belong to this function. So I'm going to move these two lines
02:32:52
these two print statements inside of our function. You can simply
02:32:56
press tab to indent them, beautiful, also lets remove
02:33:00
this extra line break, that is better, so these two lines
02:33:04
now are part of our greet user function, so whenever we
02:33:08
call this function, these two lines will be executed. Okay? Сейчас,
02:33:12
let's remove indentation so here we are outside of our function,
02:33:16
let's do a print statement and print start
02:33:20
after that let's call our function, so greet user.
02:33:24
And finally let's do another create statement and print
02:33:28
finish. Now we have this little warning here, this
02:33:32
underline, if you hover your mouse over this line, this tool was telling you
02:33:36
that we should add two blank lines after a function definition. This is coming from
02:33:40
pep8 which is a document that defines the best practices for
02:33:44
formatting our code. We'll look at that in the future. So for now to make pycharm
02:33:48
happy, lets add an extra line break to this function
02:33:52
so whenever we define a function we need to add two lines breaks after.
02:33:56
Okay? so, now let's run our program and see what happens.
02:34:00
Alright, so we have 4 messages on the terminal
02:34:04
first we get the start message then we get the messages
02:34:08
coming from our create function, so either and welcome aboard, and finally we see
02:34:12
the finished message. So let me explain the flow of our program
02:34:16
when python runs this code it doesn't actually print these
02:34:20
two messages on the terminal because these two lines of code are inside
02:34:24
of this function, so they would only get executed if we call
02:34:28
this function. If we don't call this function, these lines don't get executed.
02:34:32
Okay? So the execution of our program actually starts here,
02:34:36
the first message that we see on the terminal is the start message. After
02:34:40
that, Python sees that we are calling the greet function, so
02:34:44
it will jump over here and then execute these two lines.
02:34:48
Then, it will jump out of this function and continue the normal
02:34:52
execution of our program so it will print the finish message on the terminal.
02:34:56
So this is how functions work. Also note that the order of this
02:35:00
code matters, so here we're calling the greet function after
02:35:04
after we have defined it. If you try and call it before you define it you will see an error.
02:35:08
For example, if we call the greet
02:35:12
user function right here, see we immediately get this red underline
02:35:16
which says unresolved reference, greet user which basically
02:35:20
means python doesn't know what is this greet user, it's not defined anywhere.
02:35:24
So we always define our functions first, and then
02:35:28
call them.
02:35:32
Here's a function we created in the last tutorial
02:35:36
now I got a question for you, what is the difference between
02:35:40
calling this functions nd the print function of python? The difference
02:35:44
is that the print function takes some information, in this case
02:35:48
the message that we want to print, but our greet function doesn't take
02:35:52
any information. Wouldn't it be nicer if you could pass the name of the user here and then
02:35:56
instead of saying hi there, you could print the name of the user. So,
02:36:00
in this tutorial, I'm going to show you how to pass information to your functions, and
02:36:04
that is pretty easy, so back to the definition of our greet
02:36:08
user function, inside of these parenthesis, we can add parameters
02:36:12
these parameters are pale holders for receiving information.
02:36:16
For example, you can add a name parameter, and we can pass the
02:36:20
name of the user when calling this function. So let's pass Jon
02:36:24
here, now when we call this function and pass this value
02:36:28
this name parameter will be set to Jon. So it
02:36:32
will act like a local variable that we defined inside of this function.
02:36:36
Just imagine, we didn't have this parameter, and instead we had
02:36:40
a variable like name that was set to jump. Now here we could simply
02:36:44
print the name of this user, so we could use a formatted string,
02:36:48
and print the value of the name variable, right? Сейчас,
02:36:52
we don't really have this local variable defined in this function
02:36:56
we have a parameter, it's exactly the same thing. Так
02:37:00
with these parameters we can receive information in our functions. Now let's go ahead and
02:37:04
run this program, so take a look.
02:37:08
We get Hi John welcome aboard, we can take this to the next
02:37:12
level. Now we can call this function one more time. Так
02:37:16
greet user, and this time supply a different name. Let's say Mary.
02:37:20
So we are reusing our greet function and passing it a different
02:37:24
value. Imagine if we didn't have this function you would have to
02:37:28
repeat this line twice , once for hi jon and another time for hi mary.
02:37:32
So this is the benefit of defining functions, we can take a few
02:37:36
lines of code that have a specific purpose and put them inside of a
02:37:40
function, so now let's run our program one more time
02:37:44
there you go. So you get hi job, welcome aboard, then you get hi mary
02:37:48
welcome aboard. Now note that when a function has a parameter
02:37:52
we are obligated to pass a value for that parameter.
02:37:56
So if you remove jon from here and run
02:38:00
our program, we get this type error, greet user,
02:38:04
missing one required positional argument.
02:38:08
Argument in programming is the value that we supply to a function, so
02:38:12
back to this example, marrying this case is an
02:38:16
argument that we pass to the name parameter. And lot of
02:38:20
programmers don't know the difference between parameters and arguments and think they are the same.
02:38:24
But they are not, parameters are the holes or placeholders
02:38:28
that we define in our function for receiving information,
02:38:32
arguments are the actual pieces of information that we supply to these functions.
02:38:36
Okay? So, let's bring back
02:38:40
this jon string, now we can also define multiple
02:38:44
parameters, for example, let's rename this parameter to first name as I told
02:38:48
you before, you can right click here, go to refactor and then
02:38:52
rename, or preferably you can use a short cut. So the shortcut for
02:38:56
this on Mac is shift and f6.
02:39:00
And this brings up the renamed dial up box, here we can change this to first
02:39:04
underline name. Now we can add a second parameter
02:39:08
so comma followed by last underline name
02:39:12
so back to our formatted string, let's also print
02:39:16
the last name, beautiful, so here when calling this function,
02:39:20
then we can supply another argument so jon
02:39:24
smith and lets delete this line we don't really need it anymore
02:39:28
run our program, take a look, hi jon smith,
02:39:36
so in the last tutorial you learned that whenever
02:39:40
we define parameters for our functions we should always supply
02:39:44
values otherwise we'll get an error. Let's look at that error one more time.
02:39:48
So In going to delete this second argument and only pass jon.
02:39:52
Run our program, we get this message,
02:39:56
greet user missing one required, position
02:40:00
argument. So these arguments that you have here like jon
02:40:04
and smith you refer to these as positional arguments.
02:40:08
Which means their position or argument matters. In other
02:40:12
words, the first argument we add here is the value or the first parameter
02:40:16
and the second argument is the value for the second parameter.
02:40:20
So if you change their position or order, we'll get different results.
02:40:24
Let's take a look. Let's pass smith first and then
02:40:28
jon. Okay, good, delete, now let's
02:40:32
go with this, so instead of getting Hi Jon Smith,
02:40:36
we get hi smith jon. So that is the reason we refer
02:40:40
to these arguments as positional arguments, they're positioned or
02:40:44
order matters. But in python we also have keyword arguments, and
02:40:48
with those the position doesn't matter. Let me show you how they work. So,
02:40:52
let's say here you want to pass Jon as the value for the first
02:40:56
name parameter. We can simply specify that here. So first name
02:41:00
equals jon. Now what we have here is a keyword argument.
02:41:04
the key word argument. So this combination of having the parameter name,
02:41:08
followed by it's value is what we call a keyword argument, and what we get with this keyword
02:41:12
argument the position doesn't really matter. So here we're supplying
02:41:16
Jon as an argument fort he first parameter. Now similarly,
02:41:20
we can use a keyword argument for smith, so last
02:41:24
name equals smith, so that we have 2
02:41:28
keyword arguments. So with these keyword arguments we don't have to worry about
02:41:32
the order of the parameters. Now that doesn't mean we should always use keyword arguments.
02:41:36
На самом деле, нет. Most of the time we use positional arguments, but
02:41:40
in certain situations these keyword arguments helming us improve
02:41:44
the readability of our code. So on line 7 it's quite clear
02:41:48
that we are supplying smith as the last name and jon
02:41:52
as the first name. Now in this particular example, even if we didn't have
02:41:56
the keyword arguments, just passing two positional arguments like jon
02:42:00
and smith, would be sufficient, because it's easy to guess
02:42:04
what is the purpose of these arguments. But sometimes you're dealing with functions
02:42:08
and you're passing numerical values to them, in those situations
02:42:12
it may not be quite clear what those values represent. Let me show you an example.
02:42:16
Let's say we have a function for calculating the total cost of an order,
02:42:20
so we still call that calculate, underline cost,
02:42:24
so when calling this function, you need to supply three pieces of information.
02:42:28
One is the total cost of all the order items lets say 50
02:42:32
dollars. The other is the shipping cost, let's say
02:42:36
5 dollars, and the last piece is discount, let's say 0,
02:42:40
.1. Someone reading this code, may not be sure
02:42:44
what these three values represent, in this case, we can improve
02:42:48
the readability of this code, by using keyword arguments. So we can
02:42:52
prefix each value with the name of parameter they target, for example,
02:42:56
we can set total to 50 and then
02:43:00
shipping to 5, and then discount to 0.1.
02:43:04
Now if you give this code to someone else, they
02:43:08
can immediately tell what these values represent. So that is the power
02:43:12
of keyword arguments. So here's what I want you to take away.
02:43:16
For the most part, use positional arguments, but if you're dealing with
02:43:20
functions that take numerical values, see if you can improve the
02:43:24
readability of your code by using keyword arguments. You simply
02:43:28
prefix the arguments that you pass with the name of their parameters and this will
02:43:32
increase the readability of your code. Now there is one more thing you need to know about
02:43:36
keyword arguments. These keyword arguments should always come after
02:43:40
positional arguments. Let me show you what I mean. So,
02:43:44
back to our simple greet user function, let's use a keyword argument
02:43:48
for the first thing. So, let's set
02:43:52
first name to jon and see what happens. So we immediately get this error and
02:43:56
positional argument after keyword argument.
02:44:00
So when calling this function we're supplying one keyword argument
02:44:04
and one positional argument, and python doesn't like this. So,
02:44:08
if you're mixing positional and keyword arguments, you should always use
02:44:12
and then the keyword arguments.
02:44:16
In other words, lets remove this keyword argument here,
02:44:20
so jon is now a positional argument, is targeting the first
02:44:24
parameter. Now after this positional argument we can
02:44:28
supply any number of keyword arguments, so if you set last name to smith
02:44:32
look, python doesn't have any problem with this because we are adding
02:44:36
a keyword argument after a positional argument.
02:44:40
So let's quickly recap, for the most part use positional arguments
02:44:44
if you're dealing with functions that take multiple numerical values
02:44:48
and it's not quite clear what those values represent, use keyword arguments
02:44:52
to improve the readability of your code, and finally if
02:44:56
your passing both positional and keyword arguments, use the
02:45:00
keyword arguments after the positional arguments.
02:45:08
So far you have learned how to create functions and send them information using
02:45:12
their parameters in this tutorial I'm going to show you how to create functions that return
02:45:16
values, this is particularly useful if you're doing some kind of
02:45:20
calculation your function and you want to return the result to whoever is using your
02:45:24
function. let me show you. So let's start by defining a
02:45:28
function, called square, this function simply calculates
02:45:32
the square of a number. So we need to add one parameter here,
02:45:36
that is is our number, now here we want to calculate number
02:45:40
times number, that is the square of a number.
02:45:44
Now to return this color outside of this function we simply
02:45:48
use the return statement. So return. Сейчас,
02:45:52
our square function is very simple, it only had one line of code.
02:45:56
But in a real program, you might have a function that has ten lines of code to calculate
02:46:00
something. So, this return statement is very
02:46:04
valuable. So now we can return values to the caller of our function.
02:46:08
So, with this, when we call the square function,
02:46:12
let's say we give it 3, now this function returns a value,
02:46:16
just like an input function of python, this input function
02:46:20
waits for the user to type something and press enter and then it will
02:46:24
return the user's input as a string so we can get it
02:46:28
and store it in a variable like this, right? We have the same story with our
02:46:32
story, with our square function. So our square function returns the value
02:46:36
we can simply get it and store it in a variable. Let's call that
02:46:40
result. Now, we can print
02:46:44
result on the terminal, there you go, so result is 9,
02:46:48
we could also pass this function called
02:46:52
directly inside of the print function without defining a separate variable.
02:46:56
Sometimes this is useful for writing shorter code, so in this case.
02:47:00
So, in this case, we don't really need this result variable. We simply want to print
02:47:04
the square of 3. So, we could simply pass this function
02:47:08
call right here, as an argument for the print
02:47:12
function. So let's delete this variable now our code is
02:47:16
shorter so with this we're calling the square function, this returns a
02:47:20
value and we'll pass that value as an argument to the print function.
02:47:24
Okay? When we run this program, we get the exact same
02:47:28
result. There you go. Now what happens if we don't
02:47:32
use a return statement in our function. So in the last example we simply used
02:47:36
a print statement. Let's temporarily remove
02:47:40
this return statement and print the result
02:47:44
on the terminal. Like this. So let's run our program
02:47:48
one more time and see what we get. We see two things, the number
02:47:52
9, and none. What is happening here? Что ж
02:47:56
when Python interpreter executes this code, first it will call
02:48:00
the square function. So the control moves to the square function
02:48:04
here we calculate the square of this given number and then print it
02:48:08
on the terminal. That is the reason we see 9 right here,
02:48:12
now, by default, all functions return the value
02:48:16
none. So if we don't have a return statement
02:48:20
here, by default python returns none. None
02:48:24
is an object that represents the absence of a value, it's like nothing
02:48:28
or null ic, c++ java and Javascript.
02:48:32
So, in this example, we didn't have a return statement, and
02:48:36
by default python returned none from this function.
02:48:40
So, after this square function is executed, the value none
02:48:44
is returned and passed as an argument to the print function, that is the reason
02:48:48
we see none on the second line. So here are the two things
02:48:52
you need to take away from this tutorial. By default all functions in Python
02:48:56
return none. You can change that, so if you have a function that
02:49:00
calculates something, you can return the result using the return statement.
02:49:08
Here's the code for our emoji converter program that we wrote earlier.
02:49:12
If you missed that tutorial, make sure to go back and watch it, as
02:49:16
I told you before, there is a table of content right below this video in the
02:49:20
description. So we can simply click on the emoji converter tutorial to watch it.
02:49:24
Now, your exercise is to reorganize this code using a function.
02:49:28
So I want you to extract a function in this code, because this algorithm
02:49:32
for converting these smiley faces into emoji's is something that
02:49:36
we probably want to use in a couple different applications. We can use it in a chat
02:49:40
application in an email application and so on. We don't want to write all this code every time
02:49:44
we want to convert these characters into smiley faces.
02:49:48
So, out of all these lines of code that we have from line 1 to
02:49:52
line 10, the lines 10-2 belong to our
02:49:56
algorithm, all these lines together implement this feature.
02:50:00
So, you should put these lines in a separate function,
02:50:04
Now, why don't we have the input in this function? Because
02:50:08
the input will can come in different forms, currently we're using the import function
02:50:12
to receive the input from the terminal, but in other applications
02:50:16
we might receive the input from a graphical user interface, so the input can come in
02:50:20
different forms. We don't want to put that in our function, because this line will not be reuseable.
02:50:24
You want to give our function the actual message,
02:50:28
as a string. We don't care how we got that message. In one
02:50:32
program you might get it from the terminal, in another program you might get it from
02:50:36
a graphical user interface. So that is the reason this line up code should not
02:50:40
be in that function. By the same function, you shouldn't include
02:50:44
the last line in that function because what we do with the output is different from
02:50:48
one program to another. In this program, we are printing the output
02:50:52
in another program, you might send an output as an email, or as a response in
02:50:56
a chat application, so as a general rule of thumb you're function should
02:51:00
not worry about receiving input and
02:51:04
printing it. These lines of code should not belong to your functions. So go
02:51:08
ahead and reorganize this code by extracting a function.
02:51:16
Alright, on the top, first we need to define our function. So first we type
02:51:20
def, give our function a name like emoji_
02:51:24
converter, so the name of this function clearly tells me what
02:51:28
it does. Each function should be responsible for one and only one task,
02:51:32
and that task should be clearly explained in the name of the function.
02:51:36
So, our emoji converter function should take
02:51:40
a parameter, we call that message, that is a string, right? Colon
02:51:44
now we need to move the lines
02:51:48
5 all the way to the end of our for block
02:51:52
into the function, so let's select all these lines, you can
02:51:56
cut them from here, by pressing command and x on Mac, or
02:52:00
control and x on Windows, then we paste it here,
02:52:04
as you can see these lines are automatically indented
02:52:08
so, they are part of the emoji converter function, if this didn't happen on your
02:52:12
computer, make sure to select these lines and use the
02:52:16
tab to indent them. Alright, so here's our emoji converter function
02:52:20
beautiful. Now after that
02:52:24
in the main flow of our program, first we get the input from the user
02:52:28
we store it in this variable message and then we call
02:52:32
emoji converter and pass this message,
02:52:36
this function should return a value, that is what we use to calculate
02:52:40
the end of this function, so right after this for block we need to add
02:52:44
a return statement, return output,
02:52:48
now that our function returns a value, we can get it and store it
02:52:52
in a separate variable, let's call that result
02:52:56
and then we can simply print that here, or
02:53:00
we can make this code shorter, we don't really need this code here so we can simply
02:53:04
call the emoji converter, and print the result.
02:53:08
Like this. Now here we have an underline because
02:53:12
as I told you before we need to blank lines after
02:53:16
our function definitions. So currently we have only one blank line
02:53:20
we need to add another black line, good, let's go ahead,
02:53:24
and run this program, and make sure everything works as before
02:53:28
so I'm going to type a message like good morning with a smiley face
02:53:32
good, let's run it one more time, times that,
02:53:36
to add okay beautiful, so, here's the
02:53:40
final result, we defined this function called
02:53:44
emoji converter, this function takes a parameter called message.
02:53:48
And finally returns the output.
02:53:56
In this tutorial I'm going to teach you how to handle errors in your
02:54:00
python programs, so let's start by writing a small program
02:54:04
to get the user age from the terminal. So we call the input variable
02:54:08
input, and a label here,
02:54:12
like age, this returns a string, so we need to pass it to
02:54:16
the end funciton and store the result in
02:54:20
a variable called age, now let's print age to make sure you have
02:54:24
implemented everything properly we run our program, we type
02:54:28
20, 20 is printed here, beautiful, now look at
02:54:32
the exit code of this program, exit code 0 means
02:54:36
our program terminated successfully, there were no errors, but what if
02:54:40
we run this program one more time and instead of entering
02:54:44
a numerical value, we enter something like asd.
02:54:48
We get a value error with his message invalid literal
02:54:52
for int with base 10. Basically what this message is telling
02:54:56
us is that this string asd does not contain
02:55:00
a valid home number that can be converted to an integer. Now look at the exit
02:55:04
code of this program, exit code 1 means our exit code crashed,
02:55:08
so 0 always means success and anything but 0 means crash
02:55:12
now as a good python programmer you should anticipate this situation.
02:55:16
You don't want to let your entire program crash just because the user entered
02:55:20
an invalid value. So instead of letting the program
02:55:24
crash you should handle the situation and print a proper error message, and
02:55:28
that's what I'm going to show you in this tutorial, now before we get any further
02:55:32
look at the type of error we get here, value error,
02:55:36
so remember this, we're going to get back to this shortly
02:55:40
now how can we handle these errors, in python we have a construct called
02:55:44
try accept we use that to handle errors.
02:55:48
Let me show you how it works. So on the top
02:55:52
we type try: now as you know we are defining
02:55:56
a code block so, I'm going to move these two lines,
02:56:00
inside of our try block so press tab here.
02:56:04
And remove this black line, now these two lines are part of our
02:56:08
try block, right? So after try we type
02:56:12
accept, and then we add the type of the error
02:56:16
that our program may encounter, that is value error
02:56:20
okay? Then, we add a colon and in this block we can
02:56:24
define what should happen if our program encounters
02:56:28
an error of type value error. In this case we want to print
02:56:32
a proper error message, so print,
02:56:36
invalid value. So with this try and accept we are telling python
02:56:40
hey, go ahead and try running one or these two lines of code,
02:56:44
if you encounter, an error of type. Value error
02:56:48
then instead of crashing the program, try this error message on the terminal
02:56:52
so this is how this works. Now more accurately in programming
02:56:56
we reefer to this kind of error as an exception. So an exception
02:57:00
is a kind of error that crashes our program. So our
02:57:04
user enters an invalid value, this line of code
02:57:08
in line 2 will raise an exception, and on line 4 will catch it
02:57:12
and print this error message, so our program will no longer
02:57:16
crash. Let me show you. So let's go ahead and run this
02:57:20
age 20, everything
02:57:24
works just like before and the exit code is 0, let's
02:57:28
rerun this program, and enter asd,
02:57:32
so we get this proper error message invalid error menu and once again
02:57:36
the exit code is 0, so that means our program completed successfully.
02:57:40
Didn't crash, now, we can also handle different kinds of
02:57:44
errors or exceptions, for example right when we get the age
02:57:48
let's define a variable income and set it to 20,000.
02:57:52
And then define another variable called risk and set it
02:57:56
to income divided by age.
02:58:00
Let's run this program and enter 0 as the game to see what happened.
02:58:04
So 0 is obviously a numerical value
02:58:08
so when we enter this value, technically we shouldn't get any exceptions.
02:58:12
Take a look. Our program crashed, we
02:58:16
did a 0 division error, because we cannot divide a number by 0.
02:58:20
Once again look at the exit code, so we couldn't catch this kind of error or
02:58:24
this kind of exception with this accept block.
02:58:28
Accept block is only cashing exceptions of type value
02:58:32
error. And this happens when we try to convert a nonnumerical value,
02:58:36
to an integer. So in a situation like this. We should handle
02:58:40
different kinds of exceptions, we can add another
02:58:44
except statement for an exception of type 0
02:58:48
division error. Now in this block we can print a
02:58:52
different kind of message, like age cannot be
02:58:56
0. Let's run our program one more time. Сейчас,
02:59:00
I'm going to enter 0 as the age so we get this
02:59:04
error message age cannot be 0 and look at the exit code.
02:59:08
It's 0, so our program didn't crash, so to recap, we
02:59:12
`used try accept blocks to handle exceptions that are
02:59:16
raised in our programs, as a good programmer you should always anticipate
02:59:20
these kind of exceptions and handle them properly.
02:59:28
In this tutorial I'm going to talk to you guys about comments in python.
02:59:32
We use comments to add notes or comments to our programs.
02:59:36
For example, here I'm going to make a print statement,
02:59:40
sky is blue. Now, before that, I
02:59:44
can add a comment using a hi sign and then whatever we type here
02:59:48
is going to get ignored it's not going to get executed. Let me show you so
02:59:52
let's run this program, look we only see this
02:59:56
message. Sky is blue. So with this comment we can explain
03:00:00
something about our code, we can use it as reminders to fix things or
03:00:04
clear things up, or we can use it to communicate things with other developers
03:00:08
reading our code, why we have written this code in a certain way.
03:00:12
These are good use cases for using comments, we can also
03:00:16
have comments over multiple lines, so we can simply add more
03:00:20
comments, each line should start with a new hi sign. Now
03:00:24
one thing you need to avoid when using comments is explaining what the
03:00:28
code does. So here's an example of a bad comment.
03:00:32
Let me just delete these two lines, and with this comment I'm going to
03:00:36
say print sky is blue. Why
03:00:40
is this a bad comment, because it's telling me the obvious, it's telling me
03:00:44
this slide is going to print sky is blue. Now the problem with this comment is
03:00:48
that apart from being verbose and repetitive, if you come here,
03:00:52
and change sky to ocean, now this comment gets
03:00:56
outdated. So overtime we change this code, then we have to come back and
03:01:00
modify the corresponding comment. So I've seen some developers
03:01:04
add comments in front of their functions, for example, they define
03:01:08
a function let's say a square that takes a number
03:01:12
and simply returns number times number.
03:01:16
But it is obvious that this function calculates and returns the
03:01:20
square of the given number. So there is really no need to add a comment and
03:01:24
explain that. Calculates and returns the
03:01:28
square of a number. This is very repetitive and it creates
03:01:32
noiser code. Someone else reading your code they get distracted with all
03:01:36
these unnecessary comments, so use comments to explain whys and hows.
03:01:40
Not why's if you have made certain assumptions, we can use
03:01:44
comments to explain those assumptions. Or we can use them to add notes to remind yourself
03:01:48
or other developers to do something in the code.
03:01:52
So comments are good, but too much of a good thing is a bad thing.
03:02:00
In this tutorial I'm going to talk to you guys about classes in python.
03:02:04
Classes are extremely important in programming and they're not
03:02:08
specific to python, in fact, a lot of other programming languages
03:02:12
do support the notion of classes. We use classes to define new types.
03:02:16
For example, so far you have learned about the basic types in Python
03:02:20
like numbers, strings, and booleans,
03:02:24
these are the basic or simple types in python, you also learn
03:02:28
about a couple of complex types like lists and
03:02:32
dictionaries. While these types are extremely useful, they cannot
03:02:36
always be used to model complex concepts, for example, think about
03:02:40
the concept of a point, or a shopping cart. A shopping cart is not
03:02:44
a boolean, it's not a list, it's not a dictionary, it's a different kind of
03:02:48
thing. So we can use classes to define new types to
03:02:52
model real concepts. Now in this new model I'm going to show you how to
03:02:56
define a new type called point, and this new type is going to have methods
03:03:00
for working with points. For example, back to our main program. Let's
03:03:04
create a list, numbers, 1, 2, 3,
03:03:08
you know that here, when we type that dot,
03:03:12
functions or methods available in list objects, now similar to this,
03:03:16
we're going to create a new type called point, this point is
03:03:20
going to have metas like move, draw, get,
03:03:24
distance from another point, these are the operations that we can
03:03:28
perform on points. So let me show you how to do this.
03:03:32
We start by defining a class by using the class keyword,
03:03:36
and right after that we give our class a name. Now look at the
03:03:40
naming convention I've used here. I've capitalized the first letter here, this is what we call
03:03:44
a pascal naming convention. So the naming convention we
03:03:48
used for naming our classes is different from the convention we use for naming
03:03:52
our variables and functions. For variables and functions we always
03:03:56
use lower case letters and we separate multiple words using
03:04:00
an underscore. But when naming classes, we don't use an underscore
03:04:04
to separate multiple words, instead we capitalize
03:04:08
the first letter of every word. So in this case our class has only a single
03:04:12
word, if you had multiple words, let's say email client
03:04:16
look I've capitalized the first letter
03:04:20
of every word. Once again, this is called pascal naming convention
03:04:24
and it comes from the old pascal language that you might have heard of.
03:04:28
So, back to our point class. Here we add
03:04:32
a colon which means we're going to define a block, now
03:04:36
in this block we can define all the functions or methods that belong
03:04:40
to points, for example, we can define a function called
03:04:44
move for moving a port, now note that as soon as we
03:04:48
type open parenthesis, pycharm automatically adds self here,
03:04:52
this is a special keyword and we're going to get back to this shortly.
03:04:56
So, for now, in this method, let's print
03:05:00
move on the terminal, now let's define another
03:05:04
method like draw, so define draw
03:05:08
and in this method, let's print draw on the terminal, now
03:05:12
let's remove the indentation, we're done
03:05:16
with the definition of our point class, so we need to add two line breaks
03:05:20
okay, so with this class we defined a new
03:05:24
type with this new type we can create new objects, so
03:05:28
an object is an instance of a class, a class simply defines
03:05:32
the blueprint or the template for creating objects, and
03:05:36
objects are the actual instances based on that blue print.
03:05:40
So we can have tens of hundreds of points on the screen, these are the
03:05:44
objects or the instances. So to create an object,
03:05:48
we type out the name of our class and then call it like a function
03:05:52
this creates a new object and then returns it. So then we can store
03:05:56
that object in a variable, let's call that point 1,
03:06:00
there you go, now when we use the dot operator.
03:06:04
Look, we have these two methods that we
03:06:08
defined, draw and move, we also have a bunch of other methods that we
03:06:12
start with two underscores, these are called magic methods
03:06:16
we'll look at them later in the course. Now, let's call the draw method
03:06:20
of our point object, and run our program
03:06:24
so you can see draw is printed on the terminal. Now
03:06:28
apart from methods these objects can also have attributes and these attributes
03:06:32
are like variables that belong to a particular object. Например,
03:06:36
here, after we've defined .1.
03:06:40
We can set .1.x to
03:06:44
10. And .1.1 to 20.
03:06:48
Now we can easily print out these attributes, let's print
03:06:52
.1.x and run our program one more time
03:06:56
take a look, so the x coordinate of .1 is 10.
03:07:00
Now we can create another object, let's call that.2
03:07:04
so .2 once again we type out the name
03:07:08
of our class and then call it like a function. Now this object is completely
03:07:12
different then the first object. So if you print
03:07:16
.2.x
03:07:20
look we get this attribute error, because this point object doesn't have an
03:07:24
attribute called, so each object is a different
03:07:28
instance of our points class. Now here
03:07:32
we can assign a value to .2.x. Let's
03:07:36
send that to 1, and then run our program so we can see the
03:07:40
x coordinates of .2 is 1. So to recap
03:07:44
we use classes to define new types, these types can have
03:07:48
methods that we define in the body of the class and they can also
03:07:52
have attributes that we can set anywhere in our programs.
03:08:00
You have learned how to create new types using classes
03:08:04
now therein a tiny problem in this implementation.
03:08:08
We can create a pooint object without an x or y coordinate
03:08:12
let me show you. So point we create this
03:08:16
object here, and before we set point.x let's
03:08:20
print point .x run our program
03:08:24
we get this attribute error which you
03:08:28
saw in the last tutorial, so point object has no attribute called x
03:08:32
This is the problem we have here, it is possible,
03:08:36
to have a point object without an x or y coordinates.
03:08:40
And that doesn't really make sense, because whenever we talk about a point,
03:08:44
we ned to know where that point is located. To solve this problem, we
03:08:48
use a constructor. A constructor is a function that gets called
03:08:52
at the time of creating an object. So here on line 9, when creating this
03:08:56
point object, we want to pass values for x or y
03:09:00
coordinates, let's say 10 and 20, and with this,
03:09:04
this point object that we get here, will have it's
03:09:08
x and y coordinates initialized. So how do we do this?
03:09:12
We need to add a special method in this class called constructor.
03:09:16
So, on the top, I define a new function,
03:09:20
look at the name of this function, double underscore init, double under
03:09:24
score. So init is short for initialized, and this is the
03:09:28
function or the method that gets called when we create a new point object.
03:09:32
Now, press enter, so this automatically adds,
03:09:36
self in parenthesis, we're going to come back to this shortly.
03:09:40
Now, right after self, we want to add 2 extra parameters,
03:09:44
x and y, so let's type out x and y,
03:09:48
and then in the body of this method, we should read the values past
03:09:52
here, and use them to initialize our object, so when we pass
03:09:56
10 and 20, these arguments will be used for
03:10:00
x and y parameters. Now to initialize
03:10:04
our object, we type our code like this. Self.x equals
03:10:08
x. And then self.y equals y.
03:10:12
What is going on here, this self that you see here is a reference to the current
03:10:16
object. So, back to line 13,
03:10:20
when we create a new point object, self references that object in
03:10:24
memory, the same object, that we're referencing using this cariable.
03:10:28
So earlier we typed point.x equals 10,
03:10:32
with this code we set the x attribute of this point object.
03:10:36
Now what we have in the constructor is exactly the same, we use the self
03:10:40
to reference the current object and then we set the x attribute
03:10:44
to the x argument passed to this function. So,
03:10:48
using this init method, we can initialize our objects and
03:10:52
we refer to this method as a constructor, this method is used to construct
03:10:56
or create an object, okay? so,
03:11:00
Now, let's remove line 14, so we created
03:11:04
point object with these values and then print point.x let's run our program
03:11:08
there you go, x is 10, we can also change
03:11:12
these values later, so just before printing point.x we can set
03:11:16
point.x to 11 and then run our program
03:11:20
so x is updated, beautiful, alright, here's a
03:11:24
exercise for you. I want you to define a new type called person
03:11:28
these person objects should have a name attribute as well as a talk
03:11:32
method. This is a very easy exercise so,
03:11:36
you can tackle it in probably a couple of minutes.
03:11:40
Alright, so
03:11:44
first we start with a class keyboard, we define this person class
03:11:48
once again look at the naming convention I have used here, the first letter
03:11:52
of the first word in this case the only word is uppercase.
03:11:56
Now, in this class we define all the methods we need, currently we only have
03:12:00
method that is the talk method, so define talk,
03:12:04
pycharm automatically adds self, we come back to this shortly,
03:12:08
for now let's just print talk.
03:12:12
So this is the body of our person class. We remove the indentation
03:12:16
and add two line breaks after defining our
03:12:20
classes. Now we can create the personal object, let's call that jon,
03:12:24
we set it to person, we can call jon.
03:12:28
talk, let's run the program so we get this
03:12:32
message, beautiful, but our person objects should also have
03:12:36
a name attribute, it doesn't make sense to have a person without the name.
03:12:40
So that is when we use the constructor function. So on the top,
03:12:44
we add a new method, at the name of this method is double
03:12:48
underscore, init double underscore. So we
03:12:52
call this method a constructor. Now in this method we need to
03:12:56
add another parameter which is name, so we
03:13:00
simply set self.name to name. Once
03:13:04
again, self references the current object, we're setting the name
03:13:08
attribute of the current object, to the name argument passed to this method.
03:13:12
With this we can go back to line 9, and
03:13:16
when creating a person object we pass the name, let's see jon smith
03:13:20
now let's print jon.name and run our program
03:13:24
there you go. So jon Smith is printed on the terminal, beautiful,
03:13:28
so this is all you had to do as part of this exercise. But
03:13:32
let's make this program a little more interesting. Instead of printing
03:13:36
this boring message here, let's print hi, I am Jon Smith.
03:13:40
So, we can use a formatted string with a message
03:13:44
like Hi, I am, now we want to dynamically
03:13:48
add the name of this person. How do we do this? Well, look at
03:13:52
the parameter of this talk method. As I told you before,
03:13:56
every method in our class should have this parameter, self.
03:14:00
And they should be the very first parameter of each method, okay? So,
03:14:04
with this self we can get reference to the current object, so
03:14:08
we can add curly braces and type out self
03:14:12
.name. Thsi returns the name attribute of the current
03:14:16
person object. With this we can remove
03:14:20
line 10, where we print jon.name and simply call
03:14:24
jon.talk. Lets run our program.
03:14:28
Hi, I am Jon Smith. There we go, beautiful.
03:14:32
Now we can build another person object, let's say Bob, is a new person
03:14:36
called Bob Smith, when we say
03:14:40
Bob.talk. And run our program
03:14:44
we get a different message, hi I'm Bob Smith, so
03:14:48
each object is a different instance of a person class.
03:14:56
In this tutorial Im going to talk to you about inheritance in Python,
03:15:00
inheritance is a mechanism for using code and once again
03:15:04
it's no limited to python, most languages that support classes
03:15:08
also support inherence. So let ms how you how this works. Let's say
03:15:12
we have this dog class with a simple walk method, in this method
03:15:16
we're simply printing the walk message on the terminal, now let's say
03:15:20
in real program, instead of just one line of code here we're going to have 10 lines of
03:15:24
code. Now, what if in the future we want to define a
03:15:28
another class let's say cat and we want to add
03:15:32
this walk method there as well. Sow e'll have to repeat all that code,
03:15:36
in this new class, walk.
03:15:40
Это плохо. because you have repeated or duplicated our
03:15:44
code. In programming we have a principle called dry
03:15:48
which is short for don't repeat yourself.
03:15:52
Let's say sometime in the future, we discover a problem with our walk method. If you
03:15:56
have repeated or duplicated this method in many other places, then we'll
03:16:00
have to come back and fix that problem in every single place we have
03:16:04
duplicated this code. So that's why in programming we should not define something
03:16:08
twice. So how can we solve this problem.
03:16:12
There are different approaches, one approach that is easier to understand for beginners is inherence
03:16:16
Now here's how it works. We define a new class called
03:16:20
maml and move the walk method right there. Then we'll have
03:16:24
the dog and cat classes inherit that method
03:16:28
from their parent just like how humans inherit certain
03:16:32
attributes or behaviors form their parents. That' exactly the same, so
03:16:36
on the top, we define a new class, let's call it
03:16:40
mammal then we need to move the walk method there. So,
03:16:44
we select it, cut it, using command and x on Mac, or
03:16:48
control x on Windows and then paste it here, beautiful,
03:16:52
now we want our dog class to inherit this class from the mammal class
03:16:56
so right after the class name we add parenthesis and
03:17:00
then type out the name of the parent class. In this case, mammal.
03:17:04
That's all we have to do. So with his the dog class
03:17:08
will inherit all he methods defined in the mammal class.
03:17:12
Now there is a tiny problem here, if you look at line 9, there is a
03:17:16
red underline here. The reason this is happening is because
03:17:20
python doesn't like an empty class, so right now our dog
03:17:24
class is empty, it doesn't have anything, we either need to add methods
03:17:28
specific to dogs or just to make Python happy,
03:17:32
we can use the path statement, and that basically means nothing.
03:17:36
We're telling python interpreter, hey, pass this line, don't worry about it. But with this, we
03:17:40
don't have an empty class, okay? Now as I told you before
03:17:44
after each class I should have two line breaks so right now we
03:17:48
only have one line break and that is the reason we have this little warning here, so let's add
03:17:52
another black line, beautiful, so our dog class is
03:17:56
inheriting the walk method from the mammal, you need to apply the same change
03:18:00
to the cat class. So we'll have cat
03:18:04
inherit from mammal, and then,
03:18:08
use the path statement here. With these changes,
03:18:12
now we can create either a dog or cat object, let's say dog,
03:18:16
one, we set it to a dog object, and
03:18:20
when we type dot look we have the walk method that is defined
03:18:24
in the mamall class. We can easily call it, let's run our program
03:18:28
there you go, you see the walk message,
03:18:32
so both the dog and cat classes are inheriting all the classes
03:18:36
methods defined in their parent class. Now here we can add methods
03:18:40
specific to dogs, for example, we can define a method called
03:18:44
bark, and then print bark.
03:18:48
Now, we don't need the path statement because we already defined
03:18:52
one method in our dog class. So now when we type out
03:18:56
dog1. look we have two methods
03:19:00
one is the walk method that we inherited and the bark method that we just
03:19:04
defined in the dog class. Similarly, we can add a method
03:19:08
specific to a cat, for example, we can define a method called
03:19:12
be annoying, I hate cats, so let's print
03:19:16
annoying , now when we create the cat
03:19:20
object, let's remove that, cat1
03:19:24
and type out cat1. you have these two methods
03:19:28
dog and be annoying. So these are the basics of inheritance in python
03:19:32
Now there is more to this that really goes beyond the scope of this beginners tutorial.
03:19:36
If you're interested to learn more about inheritance and other mechanisms
03:19:40
for reusing code, I encourage you to get my complete Python course.
03:19:48
In this tutorial, I'm going to talk to you about modules in python.
03:19:52
A module in python is basically a file with some python code.
03:19:56
And we use modules to organize our code into files.
03:20:00
Just like sections in a super market. When you go to a super market there are different sections
03:20:04
for fruits, vegetables, cleaning products, and so on. We don't have
03:20:08
one section with all the products in the super market. We have the same concept
03:20:12
in programming. So instead of writing all our code, instead of writing
03:20:16
all the functions and classes in app.py we want to break up our code
03:20:20
into multiple files. We refer to each file as a module.
03:20:24
With this, not only is our code better organized and structured,
03:20:28
but we'll also have the ability to reuse our code. Например,
03:20:32
over here in app.py, I've defined two functions for converting
03:20:36
weight from pounds to kilograms and vice versa.
03:20:40
Now we can take these two functions and put them in a separate module
03:20:44
called converters, and then we can import that module into any
03:20:48
program that needs these converter functions. Let me show you how to do this.
03:20:52
So, let's open up our project panel and right
03:20:56
click the project, go to new, and add the new file,
03:21:00
we're going to call this file, converters.py.
03:21:04
Then, we go back to app.py
03:21:08
select all this code, cut it and then
03:21:12
paste it into our new module. converters.py.
03:21:16
With this we have cleaned up our app module it's not bloated with different
03:21:20
functions, so as we write more functions with classes, we put them in their
03:21:24
corresponding modules, a module should contain all the related
03:21:28
functions and classes, okay? Now you want to
03:21:32
import the converters module into our app module, and that is really easy, on the
03:21:36
top we write import converters
03:21:40
without extension, so we don't add .py we only type out the name of
03:21:44
the file. Let me close that project panel. Сейчас,
03:21:48
this converter is an object so we can use the dot operator
03:21:52
to access it's members. So currently we have defined
03:21:56
these two functions inside of our module, kilogram to pound,
03:22:00
and pounds to kilograms. So we can easily call one of these functions
03:22:04
let's pass 70 kilos get the result and print it out.
03:22:08
Run our program, so,
03:22:12
that is under 55 pounds. Now there is also another
03:22:16
syntax for importing modules, let me show you, so
03:22:20
instead of importing the entire module we can import specific functions from that
03:22:24
module. Here's how it works. We type out from
03:22:28
then we add the name of our module, so converters
03:22:32
import, now here if you press control and space
03:22:36
we can see the list of all the functions defined in this module.
03:22:40
So here we can grab one of these functions let's say kilogram to pound, and
03:22:44
with this we can directly call this function just like
03:22:48
the function defined in this file. App.py. Compare
03:22:52
what we have on line 4 to what we have on line 6. On line 6
03:22:56
we'll have to prefix this function with the name of an object
03:23:00
converters. So we have to type converters. and then we'll be able to
03:23:04
access this function. In contrast. When we import
03:23:08
a specific function from our module, then we can easily call that function
03:23:12
without prefixing it with the module name. So here's what
03:23:16
you need to take away. We use modules to better organize our code. Instead of
03:23:20
writing all the code, instead of writing all the functions in one file, you break up
03:23:24
our code across multiple files. Each file is called
03:23:28
a module and it should contain all the related functions and classes
03:23:32
then we can import a module into another module, in this case, we are importing
03:23:36
the converters module into our app module. And as you saw,
03:23:40
there are two ways to import this module, we can import the entire module, and then
03:23:44
we'll get an object with the same name as the module so we can
03:23:48
type converters . and then we'll be able to access all the
03:23:52
functions and classes defined in this module. The other appraoch
03:23:56
is to impot a specific function or class from a module using the
03:24:00
from import statement. Now here
03:24:04
is your exercise. Earlier in the course you had an exercise for finding the
03:24:08
largest number in the list. So here on the top we have
03:24:12
a list of numbers, initially we set max to the first number in this list
03:24:16
then, we look through this list, get each number,
03:24:20
if the current number is grater than max, then we reset max.
03:24:24
And finally when we are done with our loop we print max on the terminal.
03:24:28
Now here's what I want you to do. This code currently
03:24:32
has no organization. We don't have any functions, we don't have any modules, we wrote all
03:24:36
the code in app.py, that is okay for small programs,
03:24:40
but as your programs grow, you need to properly organize your code into
03:24:44
classes and modules. So, as part of this exercise, I want
03:24:48
you to write a function, call it find max.
03:24:52
This function should take a list, and return the largest number in that list.
03:24:56
Now after you do this, go ahead and put this function
03:25:00
in a separate module. So extract it from here, and put it in a module,
03:25:04
called utils. So in this module we're going to have a bunch of
03:25:08
utility functions, oaky? Then import the utility
03:25:12
module into the current module and call this function.
03:25:16
Finally, get the result and print it on the terminal, this is a
03:25:20
fantastic exercise to teach you how to properly organize your code. So,
03:25:24
go ahead and spend a couple minutes on this exercise.
03:25:28
So the first
03:25:32
step is to define a function called find max. So on the
03:25:36
top, I'm going to define function, find max
03:25:40
this function should take a list of numbers, so we
03:25:44
add a parameter called numbers. Now inside of this function you
03:25:48
want to have these few lines, this is the algorithm for finding the
03:25:52
largest number in a list, we don't want to bring the first line, because this
03:25:56
is where we create a list. So somewhere in our program we're going to create this list,
03:26:00
and tehen pass it as an argument to pass max
03:26:04
function. Okay? So, let's go ahead and grab
03:26:08
these few lines, cut them, and put them inside
03:26:12
of find max function. Alright, so we find the
03:26:16
largest number in this list, finally we need to return it, so,
03:26:20
return max. So here's our function. Now we
03:26:24
need to move this into a separate module. So let's go to the panel
03:26:28
right click the project and add a new
03:26:32
file, we can also add a new python file that's the same, let's call that
03:26:36
utils so if you add a new python file
03:26:40
pycharm automatically adds .py extension, but if you go to
03:26:44
new file we'll have to explicitly type out
03:26:48
.py. So make sure to get the extension right.
03:26:52
Now, back to app.py, let's cut this code and
03:26:56
paste it into this new module, okay beautiful.
03:27:00
Now I'm going o go back to app.py and import our new module.
03:27:04
We can either import the entire module, so import utils
03:27:08
and then access individual functions so we can call utils
03:27:12
.find max or we can explicitly
03:27:16
import this function from the utils module. It doesn't really make a difference.
03:27:20
So, we could type from utils
03:27:24
import find max. And then we
03:27:28
don't need to prefix this with the name of it's object, so we simply call
03:27:32
find max. Now we need to call this after we initialize our list.
03:27:36
So first we need to define the list of numbers.
03:27:40
Then, we pass that list as an argument to find max
03:27:44
we get the result which is max and finally we print it
03:27:48
on the terminal. let's go ahead and run our program, so the
03:27:52
largest number is 10, beautiful,
03:27:56
now one last thing before we finish this tutorial, here we have this little warning
03:28:00
under max and the tool tip says shadows built in name
03:28:04
max. The reason we see this is because we actually have a function called
03:28:08
max. And it does the exact same job
03:28:12
as our find max function. So this is actually built into python.
03:28:16
But I ask you to do it as an exercise because it's a great exercise for beginners.
03:28:20
Now, back to the warning, this warning is basically telling us that we are
03:28:24
overwriting the built in max function in python
03:28:28
so we are changing the meaning of this function, and this is considered a bad practice,
03:28:32
let me show you what I mean. So let's comment out what we have on line 4,
03:28:36
by putting a hash sign here, we can also use,
03:28:40
a short cut command and slash on Mac, or control on slash
03:28:44
on Windows. So now this line is commented out. Look at the
03:28:48
color of max here, it's purple, it's the same color as print. And this is the color
03:28:52
used to identify the built in functions. So now we can call
03:28:56
this function and give it a list of numbers
03:29:00
run our program we get the same exact result however,
03:29:04
if we bring this line back, once again we can use the same
03:29:08
shortcut that is command and slash on Mac or control slash on Windows.
03:29:12
Now, we are redefining max, so up to
03:29:16
this line, max used to be a function, but after line 4 is executed
03:29:20
max is set to an integer, that is the largest number in this list.
03:29:24
So, we'll no longer be able to call it on line 5,
03:29:28
let's run our program and see what happens. So there you go,
03:29:32
we get this type error, int object is not
03:29:36
callable, because max is now an integer, it's not a function,
03:29:40
so we cannot call it. So to solve this problem, we can rename
03:29:44
this variable to something else. So right click here.
03:29:48
Go to refactor and rename,
03:29:52
and rename this to maximum.
03:29:56
So you can see the warning is gone. As you can see we have the same warning
03:30:00
in our utils module. So here we're redefining max
03:30:04
and as I told you before this is a bad practice. We're changing the
03:30:08
meaning of built in functions in python. So,
03:30:12
let's rename these as well, I'm going to use the short cut that is shift and
03:30:16
f6 there you go and here we can change this to
03:30:20
maximum. Enter, done.
03:30:28
In this tutorial we're going to talk about packages in python,
03:30:32
packages are basically another way to organize our code, so currently
03:30:36
we have only 3 files for modules in our project but a real project
03:30:40
can contain hundreds or even thousands of modules.
03:30:44
We don't want to add all those modules here, because over time this directory will get
03:30:48
bloated with so many files, so a better approach is to organize related
03:30:52
modules, inside of a package, so a package is a container
03:30:56
for multiple modules In file system terms a package is
03:31:00
a directory or folder. So in our project we can add a new directory
03:31:04
and in that directory we can add all the directed modules, as a metaphor think
03:31:08
of a mall. When you go to a mall or a shopping center there are different
03:31:12
sections for mens women and kids clothing, so that is
03:31:16
ilke a package, now when you go to the mens section, there are different areas
03:31:20
fior different kinds of products, we have a section for shoes, t shirts,
03:31:24
jackets, and so on, so each of these is like a module, so,
03:31:28
in this tutorial, I'm going to show you how to create and use packages in Python,
03:31:32
here in our project panel, right click the panel and
03:31:36
add a new directory.
03:31:40
Let's call this directory e commerce. So we're going to create
03:31:44
a package called e-commerce and in this package we're going to have
03:31:48
all the modules related for an ecommerce application. Например,
03:31:52
we can have modules for sales, shipping, customer service
03:31:56
and so on. So let's go ahead
03:32:00
Now here we have an empty directory, in order to convert this to a package
03:32:04
we need to add a special file in it. So, right
03:32:08
click this directory and add a new python file,
03:32:12
call that file double underscore in it, double underscore
03:32:16
this is a special convention in Python.
03:32:20
When Python interpreter sees a file with this name and
03:32:24
name in a directory, it treats this directory as a package, we also have a
03:32:28
shortcut for that in pycharm so let me delete this directory
03:32:32
and start again. So delete, once again right click
03:32:36
the project, and go to new but instead of creating a new directory
03:32:40
we can create a new python package, let's call
03:32:44
our package ecommerce as you can see
03:32:48
pycharm automatically creates this file for us so we don't have to manually create
03:32:52
Это. Okay? Now, in this package, let's add a new module,
03:32:56
so a new python file, let's call it
03:33:00
shipping okay? Now in this module we want to have
03:33:04
a function for calculating the shipping costs. So define
03:33:08
calculate, underline, shipping.
03:33:12
Now don't worry about parameters or implementation, we simply print
03:33:16
calculate underline shipping.
03:33:20
Now lets say you want to import this shipping module
03:33:24
into our app module, with this new structure this shipping
03:33:28
module is now part of the ecommerce package, so we cannot import a direct
03:33:32
you have to start from the ecommerce package. So,
03:33:36
bak to app,py once again there are two ways to import this module.
03:33:40
We can import the entire module or we can
03:33:44
import one of it's functions or classes. So let me show you both approaches.
03:33:48
First, we're going to import the entire module. Now what is the name of our
03:33:52
package? it is ecommerce, right? So ecommerce.
03:33:56
shipping. So instead of typing import
03:34:00
shipping we type import ecommerce
03:34:04
.shipping. we have to prefix it with the name of it's package.
03:34:08
Now to access any of the functions or classes in this module
03:34:12
we'll have to type out ecommerce.shipping.
03:34:16
and there you go. Now we can access the calculate shipping
03:34:20
function. So let's go ahead and run our program,
03:34:24
we see this message printed on the terminal, beautiful. However
03:34:28
with this approach, every time you want to call one of the functions
03:34:32
to this module, we'll have to prefix it with ecommerce.
03:34:36
shipping. that is very verbose. So when working with packages
03:34:40
we often use the second approach, using the
03:34:44
from statement. So we can type from ecommerce
03:34:48
.shipping import
03:34:52
calculate shipping. Now we don't have to prefix this function
03:34:56
with ecommerce.shipping, and we can call it multiple times
03:35:00
in this module, so our code is a little bit shorter. But what if
03:35:04
you want to use multiple functions in this shipping module. We can either import them here,
03:35:08
so calculate shipping, comma, let's say calculate_
03:35:12
tax. Or we can import the entire module and then
03:35:16
access all he functions or classes in that module. So,
03:35:20
let me revert this back. To import the entire module
03:35:24
we type from ecommerce so we remove.shipping
03:35:28
so from this package, import
03:35:32
the shipping module. Now the shipping module,
03:35:36
is an object so we can access
03:35:40
all the functions and classes defined here, using the dot operator, so
03:35:44
shipping. there you go, calculate shipping. So to
03:35:48
recap, when using the from statement we can either start from
03:35:52
the package and import a specific module, or we can
03:35:56
start from package.module
03:36:00
and then import a specific function. Like calculate shipping.
03:36:04
So, this was the basics of using packages in
03:36:08
python. As I told you before, packages are extremely important, especially
03:36:12
when you want to work with a framework like django, we use django for building
03:36:16
web applications with python, and I'm going to show you that later in this course.
03:36:20
So in Django we have quite a few packages and
03:36:24
each package contains several modules. So make sure to watch the tutorials,
03:36:28
about modules and packages one more time, otherwise you're going to get confused later
03:36:32
when we get to Django.
03:36:36
In this tutorial I'm going to talk to you
03:36:40
guys about the built in modules in python, so python
03:36:44
comes with a standard library that contains several modules for common
03:36:48
tasks such as sending emails, working with date and time,
03:36:52
generating random values and passwords and so on. There are so many modules
03:36:56
already built into Python and that means there is already lots of functionality
03:37:00
that we can reuse. Let me show you where you can find
03:37:04
this standard library. So open up this browser
03:37:08
and search for python 3, module index,
03:37:12
make sure to add the version number, because the modules in python 2 are
03:37:16
different from modules in python3. So here we search for python 3
03:37:20
module index, and the first page here, you can see is
03:37:24
python module index, or python 3, let's go ahead,
03:37:28
so these are all the modules built into python,
03:37:32
for example we have modules for working with date and time,
03:37:36
we have modules for sending emails for encoding values,
03:37:40
there are so many modules here. Now the explanation of all these is
03:37:44
beyond the scope of this course, that really requires it's own course.
03:37:48
Because we have so many modules here, but don't let this list intimidate you.
03:37:52
This is not something that you need to learn right now, as you learn python
03:37:56
as you build more applications, gradually you will get familiar with more modules
03:38:00
here, in fact nobody knows all the modules in python
03:38:04
standard library. Everybody knows some modules based on the applications they have built.
03:38:08
So in this tutorial, I'm going to show you how to use one of the built in modules,
03:38:12
for generating random values. So on the top,
03:38:16
we import the random module, now because
03:38:20
random is a built in module, we don't need to have a file here
03:38:24
called random.py. So python interpreter knows that random is a built
03:38:28
in module as long as it knows where to find it.
03:38:32
Now if you're curious where this random module is stored on the disk, let me show you, so
03:38:36
here in the project panel, expand external
03:38:40
libraries, then expand python 3,
03:38:44
and then one more time python 3.7 library
03:38:48
route. So this is a folder somewhere on your computer, in this folder, we have
03:38:52
all the built in modules in python. So,
03:38:56
if you scroll down, you should be able to find.
03:39:00
The random module. There you go. It's right here. So random.
03:39:04
py. You can open this and this shows you the source
03:39:08
code of this module. there you go. Now in this tutorial,
03:39:12
we don't want to worry about hat, so let's go back to our app.py,
03:39:16
and use this module to generate random values. So when we import
03:39:20
this module, now we have this object, random, so we can use the dot
03:39:24
operator to acces it's methods. One method that is useful
03:39:28
here is the random method, and every time we call it it generates
03:39:32
a random value between 0 and 1. So here we can do a for loop,
03:39:36
let's say for I in,
03:39:40
range 3. So just to refresh your memory we are using the
03:39:44
range function to create a range object. We can look through this range object
03:39:48
and in each iteration this object will spit out a value.
03:39:52
So with this for loop, we can execute this code 3 times. Now, let's
03:39:56
indent this. Okay, and finally, let's print the result,
03:40:00
There you go. So we can see
03:40:04
that in each iteration we get a new random value between 0 and 1.
03:40:08
Now what if we want a random value for a particular age?
03:40:12
Let's say random values between 10 and 20, well,
03:40:16
there is another method here, rand int, we use 2 arguments here
03:40:20
to specify our range, let's say 10 and 20.
03:40:24
Run our program one more time. Now we have the numbers 20
03:40:28
13 and 18. If we run our program one more time,
03:40:32
We get different values, so 20, 19, 11, one more time.
03:40:36
Look, you also have another powerful method for
03:40:40
randomly picking an item from a list. Let's say we have a list of team members and you want to
03:40:44
randomly pick someone as the leader. Let me show you how to do that.
03:40:48
So, we define the list of team members, we set it to
03:40:52
jon, mary, bob,
03:40:56
and mosh. Now we can call random
03:41:00
.choice and pass our members list
03:41:04
this method randomly picks a method from this list and returns it. SO,
03:41:08
we can store the result in leader and then
03:41:12
print it on the terminal. let's run our program,
03:41:16
so now the leader is mary, if you run our program one more time
03:41:20
this line is mosh now it's mosh again one more time,
03:41:24
it really likes mosh, you get the point. Так
03:41:28
the random module is very powerful, and it has a lot of applications.
03:41:32
Now here's a very cool exercise. I want you to write this program to
03:41:36
roll a dice. So every time we run this program we get a different value.
03:41:40
Now we have 3 in 1, next time we get 3 and 6, one more time
03:41:44
5 and 6, 4 and 3, double one, that's a very cool exercise.
03:41:48
So before we get started, I want you to pay attention to a few things.
03:41:52
I want you to define a class called dice
03:41:56
in this class we're going to have a method called rope so every time we
03:42:00
call this method, we get a tuple, a tuple remember is a list of
03:42:04
values but values cannot be changed, you cannot add a new item to it, we
03:42:08
cannot remove it. So it's like a read only list. So every time,
03:42:12
we call the row method, we should get the tuple of two random values.
03:42:16
So go ahead, and do this exercise, You'll see my solution next.
03:42:24
Alright, we start by importing the random module on the top,
03:42:28
then we define a class called dice:
03:42:32
this class we want to have a method called row. So define row
03:42:36
parenthesis, this automatically adds self, now in this method,
03:42:40
you want to generate two random values between 1 to 6.
03:42:44
So we call random.randint.
03:42:48
And pass 1 and 6. So this generates the first number,
03:42:52
we can ut that here, now let's call this one more time,
03:42:56
so I'm going to copy what we have on line 5, put it here, and
03:43:00
change this variable to second. So we have two variables first and second.
03:43:04
With two random values, finally we need to return them,
03:43:08
in a tuple, so return parenthesis instead of square brackets,
03:43:12
first and second, now
03:43:16
in python when you want to return a python from a function, you don't have to add
03:43:20
this parenthesis, so you can simplify your code and python will automatically
03:43:24
interpret this as a tuple. So we are done
03:43:28
with a definition of our class, we remove the indentation and add
03:43:32
two line breaks. Now we create an object of this type
03:43:36
so you set dice to dice
03:43:40
next we roll the dice, so dice.roll and
03:43:44
print the result on the terminal, that's all you have to do.
03:43:48
Let's run this program, so now we get 2 and 5,
03:43:52
lets run it one more time, 3 and 2, 1 and 1, beautiful.
03:43:56
Now we have this little warning here, that says
03:44:00
expected 2 black lines found 1. Once again this is
03:44:04
coming from pep 8, pep is short for python and
03:44:08
proposal. We have so many python enhancement proposals or peps.
03:44:12
Pep 8 is a very famous 1, and in this document we have
03:44:16
all the best practices for formatting our code. So pep
03:44:20
8 says, that after we define our classes we should have 2 lines breaks, we've already done that
03:44:24
so the reason this is complaining is because we had 1 line break before
03:44:28
the class, so let's add one more line break, now pycharm
03:44:32
is happy. So basically pycharm is following all the best
03:44:36
practices defined in pep8. Now you don't have to memorize
03:44:40
any of these best practices, as you code in pycharm, pycharm gives you a little more
03:44:44
warning, and gradually you will learn how to properly format your code, so it's
03:44:48
readable by other people.
03:44:52
In this tutorial, I'm going to show you
03:44:56
how to work with directories in python. So here in python3,
03:45:00
module index, you can see we have a module called path lib which provides an object
03:45:04
oriented file system pact. That basically means it provides
03:45:08
classes that we can use to create objects to work with directories and
03:45:12
files. So, if you click here, you can see how this module
03:45:16
works, we can see all kinds of examples. For example, here on there basic
03:45:20
useage, you can see this is how we import the path
03:45:24
class from the path lib module. Let me zooming so you can see
03:45:28
clearly. Okay, so look, from path lib, that's
03:45:32
our module, import path, note the naming convention.
03:45:36
P is capitalized, that means path is a class, so we need to create
03:45:40
an instance of this class as you can see, right here,
03:45:44
now there's so much documentation here, you can read this on your own, but let me quickly show you
03:45:48
a few examples to help you get started. So after pycharm
03:45:52
on the top, from the path led module, that's
03:45:56
import the path class. Now we need to create,
03:46:00
a path object to reference a file or directory
03:46:04
on our computer. So there are basically to ways to do this we can use an absolute
03:46:08
path, or a relative path which basically
03:46:12
means a path starting from the current directory. Например,
03:46:16
if you wanna reference this ecommerce directory in our project, we can
03:46:20
use the relative path. So we start from the current directory and then
03:46:24
go somewhere else. With absolute paths we start from the root
03:46:28
of our hard disk. For example, if you're on Windows you might have
03:46:32
an absolute path like this, c drive, backslash,
03:46:36
program, files, backslash microsoft,
03:46:40
so these are directories in c drive.
03:46:44
On Windows we use a backslash to build a path. If you're on
03:46:48
Mac or Linux, your paths will look a little bit different, so
03:46:52
instead of backslash we have a forward slash lets say user/local
03:46:56
/bin. So these are examples of absolute paths. В
03:47:00
this tutorial we're going to work with he relative path to work with this ecommerce
03:47:04
directory that we have in our project. Now if you didn't create this directory
03:47:08
earlier, simply right click on the project and then go to new
03:47:12
directory. oaky? So, let's close this panel,
03:47:16
we create a path object, now,
03:47:20
if you don't pas an argument here, this will reference the current directory
03:47:24
alternatively, we can pass string, in this string we can
03:47:28
add a file or a directory. let's say the ecommerce
03:47:32
directory. Now this runs a path object, so we store it here,
03:47:36
now this path object has a few interesting methods
03:47:40
for example, we can check to see if a path exists by calling
03:47:44
the exist method. This simply returns a boolean so let's print it on the terminal,
03:47:48
there you go. So this path exists,
03:47:52
what if it changes to ecommerce 1, and
03:47:56
run our program and get false, we can also create a new directory
03:48:00
for example, let's change our path to email, now when we
03:48:04
run this program, obviously we don't have this directory but we can
03:48:08
create it by calling the mk dir method
03:48:12
so make directory. Let's run our program
03:48:16
alright, this method returns none which basically means
03:48:20
it doesn't return any values. Now if you look at the project panel you can see
03:48:24
here we have a new directory called emails, we can also delete this directory
03:48:28
so, instead of mk dir we call
03:48:32
rmdir which is short for remove directory, but
03:48:36
let's go ahead, now we can see that directory is gone. We can also see
03:48:40
all the files and directories in a given path, that is, very useful if you want to
03:48:44
write a little program to automate something. Например,
03:48:48
you can iterate over all the spreadsheets in a directory one them and
03:48:52
process them. Let me show you. First we change the path
03:48:56
to the current directory and then we call the glob
03:49:00
method. With his method we cans each for files and
03:49:04
directories in the current path. So as the first argument we need to pass a string
03:49:08
that defines a search pattern. We can type an asterisk
03:49:12
and that means everything, all files and all directories.
03:49:16
We can optionally add an extension, so to get all the files, you
03:49:20
need the files you use star.star. With this
03:49:24
pattern, we'll only get the files in the current directory. But not the directories.
03:49:28
We can also search for all the py files, or all the excel
03:49:32
spreadsheets. Anything. So let's search for all the py files
03:49:36
in the current directory, now when we run our program
03:49:40
we get this generator object. Generator object
03:49:44
are kind of an advanced topic, and they are beyond the scope of this beginners
03:49:48
python course. But for now all you need to know is we can iterate
03:49:52
or loop through these generator objects. So instead of
03:49:56
printing this generator object, let's just iterate over it using
03:50:00
a for loop, so, for, file in,
03:50:04
the generator object that is returned from the glob method. q
03:50:08
Let's print file.
03:50:12
We run our program, there you go. So these are all the
03:50:16
py files in my current directory, this could be different on your machine
03:50:20
if you didn't follow the exercises I gave you earlier. For example, this
03:50:24
utils.py, we created this as part of one of the exercises earlier in this course.
03:50:28
So don't worry if the files you see here are different on your machine.
03:50:32
So, you can use the glob method to search for files using
03:50:36
a pattern, we can also get all the files and directories in the current
03:50:40
path, so, we just use one asterisk, then
03:50:44
run our program, take a look, so we have this
03:50:48
ecommerce directory, we have notes.txt, this is a file I
03:50:52
added earlier just to write notes as part of my presentation so you're not going to have
03:50:56
this file. We also have a bunch of directories and files.
03:51:04
Even though python's standard library is comprehensive and has
03:51:08
so many modules for common tasks, it's not complete by any means.
03:51:12
That's why we have this directory called python package
03:51:16
index. Or pypi. And in this directory you can find hundreds
03:51:20
of packages for doing awesome things. These are packages that people like you
03:51:24
and I have built as part of our projects, and then they have published it as part of this directory.
03:51:28
For other people to use. So that's why we have a fantastic community in python,
03:51:32
there are so many python developers out there and there are so many packages
03:51:36
right in front of us to reuse in our programs, let's say
03:51:40
you want to send text messages in your programs, you don't have to build this functionality from scratch,
03:51:44
we can simply come to pypi.org and
03:51:48
search for sms aas you can see there are so many
03:51:52
projects or apckages that give you this functionality. Of course not every
03:51:56
package, not every project is complete or bug free, some of them are still
03:52:00
in development or they have bugs, but if you look around I'm pretty sure
03:52:04
for any kind of function you can imagine there is a good
03:52:08
reliable and well documented package for you. In my complete python course,
03:52:12
I will show you some of those most useful packages on pypi. For example
03:52:16
you will learn how to access the information on yelp.com in your
03:52:20
programs. So you can write a program and search for businesses
03:52:24
registered on Yelp. Let's say you want to search for the best barber
03:52:28
in New York City. I will show you how to do that. You will also learn how to use a technique called
03:52:32
web scraping, which means you can build an engine and have that engine
03:52:36
browse a website, and extract information from HDML files.
03:52:40
This is the same technique that Google does to index various
03:52:44
websites. So they have several engines, or web crawlers, these web crawlers
03:52:48
are continuously looking at various websites and extracting information
03:52:52
from their pages. When you publish a blog post Google's web crawler
03:52:56
finds the title of your post, its keywords and so on. So,
03:53:00
I'm going to show you how to do that with Python, we'll also look at browser automation, and this is extremely
03:53:04
powerful, because you can automate testing of your web
03:53:08
applications. So you might get a job as a test engineer, and
03:53:12
your daily job is to browse a website, click here and there, fill out this form, that form, and
03:53:16
ensure that this website is functioning properly. You can automate all that
03:53:20
with a powerful python package called selenium, as I have shown in my complete, as I show in my complete
03:53:24
python course. Now in this tutorial, I'm going to show you how to install
03:53:28
packages, from pypi.org. So,
03:53:32
here on pypi.org let's search for open py
03:53:36
xl. This is a package that we use for working with excel
03:53:40
spreadsheets. So let's search for this package, there you go, so currently
03:53:44
it's at version 2.5. On the top you can see,
03:53:48
this instruction pip install open pyexcel.
03:53:52
this is the command that we need to type in the terminal window to
03:53:56
install this package into our program, so back to pycharm,
03:54:00
here on the status bar. You can open up a terminal window for executing
03:54:04
various commands. So let's open it, now if you're on Windows
03:54:08
you're probably going to see something different instead of this dollar sign, don't worry about that
03:54:12
just execute this command I'm going to show you. So pip
03:54:16
install open py xl
03:54:20
Make sure to spell everything properly. So pip is the tool,
03:54:24
that comes with a python installation, and we use it to install or uninstall
03:54:28
packages registered on pypi.org. So here,
03:54:32
we're using pip to install this package. open py
03:54:36
xl. Enter, let's go ahead with that, it's going to take a few
03:54:40
seconds, oaky done, now we can import this package and it's
03:54:44
modules just like the built in modules in python, or the modules that we have
03:54:48
in our project. Now if you're curious where this package
03:54:52
is stored on disc let me show you. So open up the project panel,
03:54:56
and then expand external libraries, next
03:55:00
expand python 3, and then expand sight packages.
03:55:04
This is where all these packages that we installed with pip are stored.
03:55:08
So here we have open py xl, you can open this,
03:55:12
in this folder we have another folder called cell, now
03:55:16
Now, look what we have here you have this init
03:55:20
type, earlier I told you that whenever we add this file to a folder, python treats
03:55:24
that folder as a package, so sell is a package, and this
03:55:28
package we have is modules. Sell, interface, read only and text.
03:55:32
So as you can see, this package openpyxl has several
03:55:36
subpackages like cell, start, chart sheet and so on.
03:55:40
And in each package we have several modules, in the next tutorial
03:55:44
I will show you how to work with excel files.
03:55:48
So we have covered all the core concepts in Python, I hope you have learned a lot.
03:55:52
please support my hard work by liking this video and sharing it with others.
03:55:56
And be sure to subscribe to my channel for more tutorials like this. Next we're
03:56:00
going to work on our first python project that involves automation.
03:56:04
You're going to write a python program that can process thousands of spreadsheets
03:56:08
in under a second. Are you excited? Let's get started.
03:56:16
In this tutorial I'm going to show you something really awesome you can do with python. You're going to
03:56:20
learn how to process spreadsheets, and this is extremely valuable
03:56:24
in situation where you have hundreds or thousands of spreadsheets that need to
03:56:28
be updated. If you want to do this by hand it may take hours or days
03:56:32
weeks, or even months, you can simply build a python program in less then
03:56:36
half an hour. And have that python program, automatically process thousands of spreadsheets
03:56:40
in under one second. So, here we're going to work on this
03:56:44
excel spreadsheet. You can download this below this video.
03:56:48
In this spreadsheet we have three columns, transaction ID,
03:56:52
product ID, and press. Now don't worry about the fourth column yet.
03:56:56
So in this spreadsheet we're going to record all kinds of transactions, but let's say
03:57:00
due to an error, it could be a human error or a system error. The price that we have
03:57:04
here is wrong. Let's say we need to decrease this by 10 percent.
03:57:08
If you want to do this manually, we'll have to come back here and
03:57:12
add a formula, so we typed out equal sign, let's say you want to recalculate
03:57:16
say you want to recalculate the value of this cell.
03:57:20
have to get that and then multiply it by 0.9
03:57:24
and that is like 90% of the original price, we are reducing the original
03:57:28
reducing the price by 10%. Now when you hit enter you can see the updated price.
03:57:32
Next we'll have to come back here, select this cell and
03:57:36
apply the same formula to all the other rows. Now what if you have thousands of rows
03:57:40
here? You'll have to scroll up and down, this is going to be very tedious.
03:57:44
So we're going to write a python program that will do this for us. It's going to
03:57:48
auotmate this process and not only that it will also
03:57:52
add this beautiful chart right here,
03:57:56
once again if you want to open up hundreds or thousands of spreadsheets
03:58:00
and add a chart to each one, this is going to take at least a week or two
03:58:04
Our python program is going to do all of this in a matter of seconds.
03:58:08
So, let's get started. Alright the first thing I want you to do is
03:58:12
to download this transactions file and add it to your project.
03:58:16
I put the link below this video for you to download. So if you're wondering
03:58:20
how to put this in this project, you can simply right click the project,
03:58:24
and if you're on Mac you have this item where
03:58:28
reveal in finder, if you're on Windows you should see something like reveal
03:58:32
in explorer, or file explorer, or whatever it's called
03:58:36
when you click this, this opens up the direct
03:58:40
on your machine where this is stored. So simply copy paste
03:58:44
the transactions file right here. Сейчас,
03:58:48
here on the top, first we need to import the open py excel package.
03:58:52
So import open py excel, we can give it a
03:58:56
an alias to make our code shorter. So asxl.
03:59:00
This is not required but it just makes our code a little bit cleaner.
03:59:04
Let me show you. So now instead of typing open pyxl.
03:59:08
we type xl. okay so that's an alias for
03:59:12
this package. Now in this package we have a function for loading an xl
03:59:16
workbook. So let's call load workbook,
03:59:20
and as the argument we pass transactions.
03:59:24
.xlsx. So this we load
03:59:28
our excel workbook and return a workbook object.
03:59:32
Okay? Now if you open this workbook, you can see you add only 1
03:59:36
sheet, and that is called sheet 1, so to access that you use
03:59:40
square brackets, and specify the name of the sheet,
03:59:44
that is sheet one, make sure to spell this with a capital
03:59:48
S. Because this is case sensitive, if you don't spell it properly
03:59:52
you're going to get an error, so this returns a sheet,
03:59:56
now in this sheet, we have various cells. Так
04:00:00
next you need to learn how to access a particular cell, and that is very easy.
04:00:04
back to py charm, with this sheet object, you can use
04:00:08
square brackets and give the coordinate of a cell.
04:00:12
Coordinate is the combination of the column and the row.
04:00:16
For example, this cell it's coordinate is a1.
04:00:20
So back to pycharm, we can type a1, and this returns
04:00:24
our first cell. Also, there is another approach to getting
04:00:28
a cell, instead of using square brackets with a string, we can
04:00:32
use the cell method of the sheet object, so,
04:00:36
sheet.cell, you pass the row and the column, so row
04:00:40
and column 1 these return the exact same
04:00:44
cell. Now let's print the value of this cell, cell.value
04:00:48
and run our program so
04:00:52
the value is transaction id, beautiful,
04:00:56
so now we need to iterate over all these rows and for each row we need to get the value
04:01:00
in the third column. That is the price. We'll get that and then multiply
04:01:04
by 0.9. So first we need to know how many rows
04:01:08
we have in this spreadsheet. We can get that from the sheet object so sheet
04:01:12
has an attribute called mx_
04:01:16
row. Let's print this, so in this sheet,
04:01:20
we have 4 row, and you can verify that here. So we have
04:01:24
a total of 4 rows. So we need to add a for loop.
04:01:28
that would generate the numbers 1-4. So,
04:01:32
let's delete this print statement, nd add a for loop
04:01:36
for row in were going to use the range function unction to generate a range of numbers,
04:01:40
starting from 1, all the way to sheet
04:01:44
.max_grow. Plus 1. The reason we're
04:01:48
adding 1 to this, is because as I told you before this range function
04:01:52
will generate numbers, starting from this value all the way to this
04:01:56
value, but it will not include the second value. So currently
04:02:00
max row returns 4, if you use range of 1-4 this will generate
04:02:04
the numbers 1, 2, and 3, but not 4.
04:02:08
So to include 4, we need to add 1 to it. Let's go over here,
04:02:12
so we tied sheet.max underline row plus 1.
04:02:16
Now before going any further let's just print row and make
04:02:20
sure our program is working up to this point. So let's run
04:02:24
this, we get the numbers 1-4 beautiful.
04:02:28
So now we can easily get the cells in the third column. However
04:02:32
we don't really want this first cell, that's the heading.
04:02:36
so technically you want to ignore the first row. Back here, you want to change
04:02:40
our range function, and start from 2. Now,
04:02:44
we're going to use sheet.cell to get access to the cell
04:02:48
at this row. And the column should be 3.
04:02:52
We get a cell object, let's print it's value
04:02:56
and make sure you're on the right track, so run the program
04:03:00
these are the values we get. 5.95
04:03:04
6.95 and 7.95 these are the
04:03:08
values of the third column. Next we need to multiply each
04:03:12
value by 0.9 so instead of printing
04:03:16
cell.value we multiplied by 0.9 and this is
04:03:20
the corrected underline price,
04:03:24
so this is the mistake we're going to make with our program, now
04:03:28
we need to add a new cell to our worksheet, so we want to add all the corrected
04:03:32
prices, ia new column, it could also overwrite the values in this column,
04:03:36
but in this tutorial I'm going to show you how to add a new column.
04:03:40
So using the same method, now we need to get a reference to the cell, to the given
04:03:44
row, but in the fourth column. So, we call sheet
04:03:48
.cell, and pass row and four as the arguments.
04:03:52
Once again, this returns a cell object, let's store that in a
04:03:56
separate variable and call it
04:04:00
price_cell. So note that my variable names are
04:04:04
very descriptive. There is no guess work. You have corrected price which holds
04:04:08
actual value and we have corrected price, which is a cell
04:04:12
object in this spreadsheet. Next we have to set the value in this
04:04:16
cell. So we set corrected price cell.
04:04:20
value to this corrected price. With these few lines
04:04:24
we can easily update our spreadsheet, but first we need to save it. So,
04:04:28
after our for loop, we call workbook.
04:04:32
save. Now let's save this in a new file because we don't want to
04:04:36
accidentally overwrite the original file in case our program has a bug
04:04:40
so, I'm going to call that transactions 2.sms
04:04:44
ex. And finally let's run our program,
04:04:48
so, you can see that happened in a split of a second, now here we have a new file
04:04:52
tranactions 2. When we open this we get something like this.
04:04:56
So you can see we have this 4th column with the updated prices. Красивая.
04:05:00
So half of the problem is solved, now we need to add a chart here.
04:05:04
To add a chart, we need to add a couple classes on the top, so,
04:05:08
after this import statement let's type out from
04:05:12
open py excel.chart, import, bar chart,
04:05:16
comma, reference.
04:05:20
So lets see what's going on here. In this package you have a module
04:05:24
chart, and from this module we're importing two classes, bar chart,
04:05:28
and reference. Again, look at the naming convention used
04:05:32
Вот. The first letter of e very word is capitalized. Also it's better
04:05:36
to add a line break after our import statements to make our
04:05:40
code cleaner. So, before we save our workbook, we need to
04:05:44
add achart to the current sheet. First we need to select a range
04:05:48
of values. For this exercise, I'm going to select the values in the fourth column/.
04:05:52
So all the values in rows 2-4 these are
04:05:56
the values I'm going to use in our chart. Now in this part 2 example it doesn't really
04:06:00
make sense to add a chart per transaction, but that doesn't really matter
04:06:04
we just want a bunch of numbers to create a chart, so after our
04:06:08
for loop, we're going to use the reference class to select a range of
04:06:12
values. Now the first argument in the constructor is the
04:06:16
sheet. So we pass our sheet here, then we add
04:06:20
4 keyword arguments, the first one is min_row, we set this to
04:06:24
2. The second one is max_row we set
04:06:28
this to the maximum row in this sheet. That is sheet,
04:06:32
.max_row, so we want to select the cells in row
04:06:36
2-4. kay? Now to make this code a little bit cleaner
04:06:40
I'm going to put this on a new line, so we
04:06:44
can see clearly, now this is going to select all the cells
04:06:48
in all the columns in these rows. That's not what we want.
04:06:52
we only want the values in the fourth column, so back here
04:06:56
we need to set a couple more key word arguments men_call
04:07:00
or column, we set that to for, and also
04:07:04
max underline call, we set that to 4 as well. So we are limiting the range
04:07:08
of cells we're selecting to the fourth column.
04:07:12
Now, we're creating an instance of the reference class, let's store the
04:07:16
result in a variable called values, so this values object
04:07:20
will have all these values in the fourth column, now we are ready to create
04:07:24
a chart, so we create an instance of the bar chart class
04:07:28
and store it in this object.
04:07:32
Next, we call chart.add_date and
04:07:36
pass our values. That is pretty straight forward finally we need to add this chart
04:07:40
to our sheet. So, we call sheet,
04:07:44
.add_chart and pass this chart object
04:07:48
We should also specify where we want to add this chart.
04:07:52
let's say we want to add it here, on row 2, after the fourth column.
04:07:56
So the coordinate of this cell is e2, and this is going to be,
04:08:00
the top left corner of our chart. So as the coordinate I'm going to
04:08:04
pass e2 that's all we had to do, done. Let's run our
04:08:08
program one more time, beautiful, let's open up the update
04:08:12
workbook. And here's the end result, so
04:08:16
right after the fourth column, we have this beautiful chart. Now we could take this to the next level,
04:08:20
we could add a legend here, we could change the color of these bars, we could even use a different
04:08:24
kind of chart, it doesn't have to be a bar chart. So to learn more about this we can
04:08:28
read the documentation for openpyxl. Так
04:08:32
our program is complete, for our code is dirty, it's not clean, it's not
04:08:36
organized. We don't have any functions here. We have written all the code in app.py.
04:08:40
So let's goo ahead and organize this code like a professional software developer.
04:08:44
So, on line 4, we are loading our workbook
04:08:48
then we're getting a reference to the first sheet, but we don't really need these two lines here
04:08:52
this is purely for demonstration to show you how to access a cell. So,
04:08:56
let's delete these unnecessary lines, this is a very important practice
04:09:00
as you're coding always look at your code, always review it, see if you have some code that is
04:09:04
not used. Always delete those. Okay, next we are iterating over
04:09:08
all the rows, fixing the prices, and then
04:09:12
we select the values to add a chart, and finally we save the workbook.
04:09:16
Now, if you were going to use this to automate the process of updating
04:09:20
thousands of spreadsheets, this program wouldn't work, because it's only
04:09:24
relying on this file. So we want o reorganize this code, and
04:09:28
move it inside of a function. This function should take the name of a function
04:09:32
So let's define a function. Let's
04:09:36
call it process_workbook.
04:09:40
It gets a file name. Now, we move all the code inside
04:09:44
of this function, so let's select everything, and press
04:09:48
tab, beautiful, now back
04:09:52
to our function, instead of loading this transactions file we're going to load
04:09:56
this file name, that's better,
04:10:00
Also, now that our program is working properly, there is really no need to store the
04:10:04
result in a separate file. So here we can
04:10:08
simply overwrite the same file. So let's pass
04:10:12
file name, that is the end of our function, so,
04:10:16
now, we have this reusable function, we can simply reuse this
04:10:20
to process thousands of spreadsheets. Earlier in this python course you learned
04:10:24
how to find all the files in a directory, so we can get each file in a directory
04:10:28
and pass the name of the file to this function, this function will go
04:10:32
ahead and update this spreadsheet in just a second or less.
04:10:36
So, that was just one example of using python to automate
04:10:40
repetitive boring task that waste your time. But automation is not
04:10:44
just about processing excel spreadsheets, there are so many things we can automate.
04:10:48
Here's a question for you, what do you want to automate, how do you want to use python to make your
04:10:52
life easier? Use the comment box below and let me know. I love to
04:10:56
hear about your ideas. Next we're going to work on project which involves machine learning, which is a
04:11:00
subset of artificial intelligence. Are you excited?
04:11:04
Let's get started.
04:11:08
In this section, you're going to learn about machine learning, which is a subset of
04:11:12
AI or artificial intelligence. It's one of the trending topics in the world,
04:11:16
these days, and it's going to have a lot of applications in the future. Here's an example.
04:11:20
Imagine I ask you to write a program to scan an image, and
04:11:24
tell if it's a cat or a dog. If you want to build this program using
04:11:28
traditional programming techniques, your program is going to get overly complex
04:11:32
You will have to come up with lots of rules to come up with specific curves
04:11:36
edges and colors in an image to tell if it's a cat or a dog.
04:11:40
But if I give you a black and white photo, your rules may not work, they may break.
04:11:44
Then you would have to rewrite them. Or I may give you a picture of a cat or a dog from a different
04:11:48
angle that we did not predict before. So solving this problem
04:11:52
using traditional programming techniques is going to get overly complex or
04:11:56
sometimes impossible. Now to make the matter worse. What if I ask you to extend
04:12:00
this program such that it supports 3 kinds of animals.
04:12:04
Cats, dogs, and horses, once again you will have to rewrite
04:12:08
all those rules. That's not going to work. So machine learning is a technique
04:12:12
to solve these kinds of problems, and this is how it works. We build
04:12:16
a model or an engine and give it lots and lots of data.
04:12:20
For example, we give it thousands or tens of thousands of pictures of
04:12:24
cats and dogs. Our model will then find and learn patterns and the input
04:12:28
data, so we can give it a new picture of a cat that we haven't seen before.
04:12:32
And ask it, is it a cat or a dog or a horse
04:12:36
and it will tell us with a certain level of accuracy, the more input data we give it, the more accurate
04:12:40
our model is going to be. So that was a very basic example,
04:12:44
but machine learning has other applications in self driving cars,
04:12:48
robotics, language processing, vision processing,
04:12:52
forecasting things like stock market trends and the weather, games and so on.
04:12:56
So that's the basic idea about machine learning. Next we'll look at machine
04:13:00
learning in action.
04:13:04
A machine learning project involves
04:13:08
a number of steps, the first step is to import our data which
04:13:12
often comes in the form of a csv file. You might have a database with lots of data,
04:13:16
we can simply export that data and store it in a csv file for the
04:13:20
purpose of our machine learning project. So we import our data, next,
04:13:24
we need to clean it. And this involves tasks such as duplicated data.
04:13:28
If you have duplicates in the data, we don't want to feed this to the model, because
04:13:32
otherwise our model will learn bad patterns in our data and will produce the wrong result,
04:13:36
so we should make sure that our input data is in a good, and clean shape.
04:13:40
If there is data that is irrelevant we should remove them, if there are duplicates
04:13:44
or incomplete we can remove or modify them, if our data is
04:13:48
text based, like the name of countries, or genres of music,
04:13:52
or cats and dogs, we need to convert them to numerical values.
04:13:56
So this step really depends on the kinds of data we're working with, every project
04:14:00
is different. Now that we have a clean data set, we need to split it
04:14:04
into two segments. One for training our model, and the other for
04:14:08
testing it, to make sure our model produces the right result.
04:14:12
For example, if you have 1,000 pictures of cats and dogs, we can reserve
04:14:16
80% for training, and another 20% for testing.
04:14:20
The next step is to create a model, and this involves selecting
04:14:24
an algorithm to analyze the data. There are so many machine learning algorithms
04:14:28
out there, such as decision trees, neural networks and so on.
04:14:32
Each algorithm have pros and cons in terms of accuracy and performance
04:14:36
so the algorithm you use, depends on the kind of problem
04:14:40
you're trying to solve and your input data. Now the good news isnthat we don't have to
04:14:44
explicitly program an algorithm, there are libraries out there that provide these
04:14:48
algorithms, one of the most popular ones, which we are going to look at
04:14:52
in this tutorial, is side kick learn. So we build a model using an algorithm ,
04:14:56
next we need to train our model. So we feed it our training data.
04:15:00
Our model will then look for the patterns in the data, so enxt
04:15:04
we can ask it to make predictions. Back to our examples of cats and dogs,
04:15:08
we can ask our model is this a cat or is this a dog and our model
04:15:12
will make a prediction, now the prediction is not always accurate
04:15:16
in fact when you start out, it's very likely your predictions are inaccurate.
04:15:20
So we need to envalue the predictions and measure their accuracy.
04:15:24
Then we need to get back to our model and either select a different algorithm
04:15:28
that is going to produce a more accurate result for the kind of problem
04:15:32
we're trying to solve. Or fine tune the parameters of our model.
04:15:36
So each algorithm has parameters that we can modify to optimize the
04:15:40
accuracy. So these are the high level steps that you follow in a machine learning
04:15:44
project. Next we'll look at the libraries and tools for machine learning.
04:15:52
In this lecture we're going too look at the popular python library
04:15:56
that we use in machine learning projects. The first one is numpy which
04:16:00
provides a multidimensional array. A very, very, popular library.
04:16:04
The seconnd one is pandas, which is a data analysis library that
04:16:08
provides a concept called data frame. Data frame is a two dimensional
04:16:12
data structure similar to an excel spreadsheet. So we have rows and columns
04:16:16
we can select columns in a row or a column or a range of rows and
04:16:20
columns, again, very very popular in machine learning
04:16:24
and data science projects. The third library is mad plot lib which
04:16:28
is a two dimensional plotting library for creating graphs on plots.
04:16:32
The next library is sidekick learn, which is one of the most popular machine learning
04:16:36
libraries that provides all these common algorithms like decision trees,
04:16:40
neural networks and so on. Now, when working with machine learning
04:16:44
projects, we use an environment called jupiter for writing our code, technically we can still
04:16:48
use vs code or any other code editor, but these editors
04:16:52
are not ideal for machine learning projects, because we need to frequently
04:16:56
inspect the data, and that is really hard in environments like vs code and
04:17:00
terminal. If you're working with a table of 10 or 20 columns
04:17:04
visualizing this data in a terminal window is really, really difficult and messy, so thats why we use jupiter.
04:17:08
So that's why we use jupiter, it makes it really easy to inspect our data.
04:17:12
Now to install jupiter, we are going to use platform called anaconda.
04:17:16
So, head over to Anaconda.com/download.
04:17:20
On this page you can download Anaconda distribution for your operating system,
04:17:24
so, we have distributions for Windows Mac and
04:17:28
Linux. So let's go ahead and install
04:17:32
Anaconda for python 3.7. Download,
04:17:36
Alright, so
04:17:40
here's Anaconda, download it on my machine, let's double click this.
04:17:44
Alright, first it's going to run a program to determine if the software can be installed.
04:17:48
So, let's continue and once again continue,
04:17:52
pretty easy, continue one more time,
04:17:56
I agree with the license agreement, we can use the default
04:18:00
you ca use the default installation location so don't worry about that, just click install,
04:18:04
give it a few second, now the beautiful thing about Anaconda is it will install
04:18:08
jupiter, as well as all those data popular science libraries
04:18:12
like numpy, Pandas and so on. So we don't have to manually install this
04:18:16
using pip. Alright now as part of
04:18:20
the next step Anaconda is suggesting to install Microsoft vs code. Мы
04:18:24
already have this on our machine so we don't have to install it we can go with continue
04:18:28
and close the installation, now finally we can move the
04:18:32
this to trash because we don't need this installer in the future.
04:18:36
Alright, now open upa terminal window and type
04:18:40
jupiter, with ay, space, notebook.
04:18:44
This will start the notebook server on your machine. So enter
04:18:48
there you go. This will start the notebook server
04:18:52
on your machine, we can see these default messages here, don't worry about them, now
04:18:56
it automatically opens a browser window, pointing to local host
04:19:00
port 888. This is what we call
04:19:04
jupiter dashboard. On this dashboard we have a few tabs, the first tab
04:19:08
is the files tab, and by default, this points to your home directory.
04:19:12
So every user on your machine has a home directory, this its my home directory
04:19:16
on Mac, you can see here we have a desktop folder as well as documents,
04:19:20
downloads and so on. On your machine you're going to see different folders, so somewhere
04:19:24
so somewhere on your machine you need to create a jupiter notebook. I'm going to go to desktop
04:19:28
here's my desktop I don't have anything here, and then
04:19:32
click new, I want to create a notebook for python
04:19:36
3. In this notebook we can write python code, and execute it line by line.
04:19:40
We can easily visualize our data as you can see over the next few videos. So,
04:19:44
let's go ahead with this,
04:19:48
alright, here's our first notebook, you can see by default it's called
04:19:52
untitled, let's change that to Hello World so
04:19:56
this is going to be the hello world of our machine learning project. Let's
04:20:00
rename this now if you look at your desktop you can see this file
04:20:04
hello world.ipynb. This is a jupiter
04:20:08
notebook. It's kind of similar to our py files where we write our
04:20:12
python code, but it includes additional data that jupiter uses to execute our
04:20:16
code. So back to our notebook, let's
04:20:20
do a print hello world.
04:20:24
And then, click this run button here
04:20:28
and here's the result printed in jupiter, so we don't have to
04:20:32
navigate back and forth between the terminal window we can see all the result
04:20:36
right here. Next I'm going to show you how to load a data set from a
04:20:40
csv file in jupiter.
04:20:48
Alright, in this lecture we're going to download a data set from a very popular website called
04:20:52
caggle.com. Caggle is basically a place to do data science projects.
04:20:56
So the first thing you need to do is to create an account, you can sign up with Facebook,
04:21:00
Google, or using a custom email and password, once you sign up then come back
04:21:04
here, on caggle.com, Here one the search bar
04:21:08
search for video game sales.
04:21:12
This is the name of a very popular data set that we're going to use in this lecture. So,
04:21:16
here in this list you can see the first item with this kind of reddish
04:21:20
icon, so, let's go with that, as you can see this data
04:21:24
set includes the sales data for more then 16,000 videos
04:21:28
games. On this page you can see the description of various
04:21:32
columns in this data set, we have rank, name, platform,
04:21:36
year, and so on, so here's our data source, it's a csv file
04:21:40
called vg sales.csv, as you can see there are over 16,000
04:21:44
rows, and 11 columns in this data set.
04:21:48
Right below that you can see the first few records of this data set.
04:21:52
So, here's our first record, the ranking for this game is 1, it's the wi sport
04:21:56
game for wii as the platform and it was released in the year 2006,
04:22:00
now, what I want you to do is go ahead and
04:22:04
download the data set, and as I told you before you need to sign in
04:22:08
before you can download this. So this will give you a zip file as you can see here,
04:22:12
here's our csv file, now I want you to
04:22:16
put this right next to your jupiter notebook, on my machine that is on my desktop
04:22:20
so I'm going to drag and drop this onto the desktop folder.
04:22:24
Now, if you look at the desktop you can see here's my
04:22:28
jupiter, hello world notebook, and right next to that we have
04:22:32
vgsales.csv. With that, we go back
04:22:36
to our jupiter notebook, let's remove the first line and instead
04:22:40
import pandas
04:22:44
as pd. With his we're importing pandas module
04:22:48
and renaming it to pd, so we don't have to type pandas. several times in
04:22:52
this code. Now let's type pd.
04:22:56
read_csv. And pass the
04:23:00
name of our csv file. That is vgsales.
04:23:04
csv. Now because this csv file, is in the current folder right next to our jupiter notebook,
04:23:08
we can easily load it, otherwise we have to supply the full path
04:23:12
to this file. So, this returns a
04:23:16
data frame object which is like an excel spreadsheet. Let me show you.
04:23:20
So we store it here, and then we can
04:23:24
simply type df to inspect it. So one more time let's run this program
04:23:28
here's our data frame with these rows and these columns so we have
04:23:32
frank name platform and so on. Now this data frame object
04:23:36
has lots of attributes and methods that we're not going to cover in this tutorial,
04:23:40
that's really beyond the scope of what we're going to do, so I'm going to leave it up to you to
04:23:44
read pandas documentation or follow other tutorials to find out about pandas data frames.
04:23:48
But in this lecture, I'm going to show you some of the most useful methods and attributes.
04:23:52
The first one is shape, so shape
04:23:56
let's run this one more time, so here's the shape of this data set, we have over
04:24:00
16,000 records and 11 columns.
04:24:04
Technically this is a 2 dimensional array of 16,000
04:24:08
and 11, okay? Now, we can see here we have another
04:24:12
segment for writing code. SO we don't have to write all the code in the first segment
04:24:16
so here in the second segment we can call one of the methods of the dataframe,
04:24:20
that is df.describe.
04:24:24
Now when we run this program, we can see the
04:24:28
output for each segment right next to it. So here's our first
04:24:32
segment, here we have these three lines, and this is the output of
04:24:36
the last line. Below that we have our second segment, here we're calling
04:24:40
the describe method, and right below that we have the output of
04:24:44
this segment So this is the beauty of jupiter, you can easily visualize
04:24:48
our datsa, doing this with vscode in windows is really tedious and
04:24:52
clunky. So what is the describe method returning? Basically it's
04:24:56
returning some basic information about each column in this data set, So,
04:25:00
as you saw earlier we have columns like rank, year and so
04:25:04
on. These are the columns with numerical values. Now for each column we have
04:25:08
the count which is the number of records in that column, you can se
04:25:12
our rank column has 16,5
04:25:16
-98 records whereas the year column has 16,3-
04:25:20
-27 records.. So this shows that some of our records don't
04:25:24
have the value for the year column. We have null values.
04:25:28
So in a real data science or machine learning project we'll have to use some
04:25:32
techniques to clean up our data set. One option is to remove the records
04:25:36
that don't have a value for the year column. Or we can assign them a default value.
04:25:40
That really depends on the project. Now another attribute for each column
04:25:44
is mean so this is the average of all the values, now
04:25:48
in the case of the rank column, this rank doesn't really matter, but look at the year.
04:25:52
So the average year year for all these video games in our dataset is
04:25:56
2006. And this might be important in the problem we're trying to solve.
04:26:00
We also have standard deviation, which is a
04:26:04
measure to quanitfy the amount of variation in our set of values, below that we have
04:26:08
min, as an example the minimum value for the year column
04:26:12
is 1980. So quite often when we work with a new data set,
04:26:16
we call the describe method to get some basic statistics about
04:26:20
our data. Let me show you another useful attribute.
04:26:24
So, in the next segment, let's type df.values.
04:26:28
Let's run this, as you can see this returns
04:26:32
a two dimensional array, this square bracket indicates the outer array
04:26:36
and a second one represents an inner array.
04:26:40
So the first element inn our outer array, is an
04:26:44
array itself, these are the values in this array, which basically
04:26:48
represent the first row in our data set. So the video game we ranking
04:26:52
1, which is called wii sports. So this was a basic
04:26:56
overview of pandas data frames, in the next lecture I'm going to show you
04:27:00
some of the useful shortcuts of jupiter.
04:27:08
In this lecture I'm going to show to you some of the most useful shortcuts in Jupiter,
04:27:12
Now the first thing I want you to pay attention to is this green bar on the left.
04:27:16
This indicates that this cell is currently in the edit mode, so we can
04:27:20
write code here. Now, if we press the
04:27:24
escape key, green turns to blue, and that means this cell is
04:27:28
currently in the command mode. So basically the activated cell can either
04:27:32
be in the edit mode or command mode. Depending
04:27:36
on the mode, we have different shortcuts, so here we're in the command mode.
04:27:40
If we press h, we can see the list of all the
04:27:44
keybord shortcuts, right above this list we can
04:27:48
see, Mac OS modifier keys, these are the
04:27:52
extra keys on a Mac keyboard. If you're a Windows
04:27:56
user you're not gong to see these. So as an example, here is the shape of the
04:28:00
command key, this is control, this is option,
04:28:04
and so on. With this guideline you can easily understand the shortcut associated with
04:28:08
each command. Let me show you. So here we have all
04:28:12
the commmands when a cell is in the command mode. For example, we have
04:28:16
this command, open the command palette. This is exactly like the
04:28:20
command palette that we have in vs code. Here is a short cut
04:28:24
to execute this command. That is command shift and F.
04:28:28
Okay, so here we have lots of shortcuts,
04:28:32
of course you're not going to use all of them all the time, but it's good to have a quick look here to see
04:28:36
what is available for you. Tis these shortcuts you can write code much faster.
04:28:40
So let me show you somme of the most useful ones. I'm going to close this,
04:28:44
now with our first cell in the command mode
04:28:48
I'm going to press b, and this inserts, a new
04:28:52
cell below this cell. We can also go
04:28:56
back to our first cell, press escape, now the cell is in the command
04:29:00
mode. We can insert an empty cell above this cell by pressing a.
04:29:04
So either a or b. A for above or
04:29:08
b for below. Now if you don't want this cell, you can press d
04:29:12
twice to delete it. Like this.
04:29:16
Now in the cell I'm going to print a hello world message. So print
04:29:20
hello world. Now, to
04:29:24
run the code in this cell, we can click on the run button here,
04:29:28
so, here's our print function, and
04:29:32
right below that you can see the output of this function. But note that when you run
04:29:36
a cell, this will only execute the code in that cell.

Описание:

Learn Python for AI, machine learning, and web development with this beginner-friendly course! 🚀 Get 6 months of PyCharm FREE with the coupon in the description! ❤️ Join this channel to get access to perks: https://www.youtube.com/channel/UCWv7vMbMWH4-V0ZXdmDpPBA/join 🚀 Want to dive deeper? - Check out my Python mastery course: https://codewithmosh.com/p/python-programming-course-beginners - Subscribe for more awesome Python content: https://www.youtube.com/channel/UCWv7vMbMWH4-V0ZXdmDpPBA?sub_confirmation=1 👉 New version available Watch here: https://www.youtube.com/watch?v=kqtD5dpn9C8 📕 Get the FREE goodies: - Python cheat sheet: https://mosh.link/python-cheatsheet - Supplementary materials (spreadsheet): https://github.com/mosh-hamedani/python-supplementary-materials - Get 6 months of PyCharm for free with this coupon code: MOSH_YOUTUBE - Redeem it at: https://www.jetbrains.com/store/redeem/ ✋ Stay connected: - Twitter: https://twitter.com/moshhamedani - Facebook: https://www.facebook.com/unsupportedbrowser - Instagram: https://www.facebook.com/unsupportedbrowser - LinkedIn: https://www.linkedin.com/school/codewithmosh/ ⭐ My favorite Python books - Python Crash Course: https://www.amazon.com/gp/product/1593276036?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593276036 - Automate the Boring Stuff with Python: https://www.amazon.com/gp/product/1593275994?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275994 - A Smarter Way to Learn Python: https://www.amazon.com/gp/product/B077Z55G3B?ie=UTF8&camp=1789&creative=9325&creativeASIN=B077Z55G3B - Machine Learning for Absolute Beginners: https://www.amazon.com/gp/product/1549617214?ie=UTF8&camp=1789&creative=9325&creativeASIN=1549617214 - Hands-on Machine Learning with scikit-learn and TensorFlow: https://www.amazon.com/gp/product/1491962291?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491962291 📖 TABLE OF CONTENT 00:00:00 Introduction 00:01:49 Installing Python 3 00:06:10 Your First Python Program 00:08:11 How Python Code Gets Executed 00:11:24 How Long It Takes To Learn Python 00:13:03 Variables 00:18:21 Receiving Input 00:22:16 Python Cheat Sheet 00:22:46 Type Conversion 00:29:31 Strings 00:37:36 Formatted Strings 00:40:50 String Methods 00:48:33 Arithmetic Operations 00:51:33 Operator Precedence 00:55:04 Math Functions 00:58:17 If Statements 01:06:32 Logical Operators 01:11:25 Comparison Operators 01:16:17 Weight Converter Program 01:20:43 While Loops 01:24:07 Building a Guessing Game 01:30:51 Building the Car Game 01:41:48 For Loops 01:47:46 Nested Loops 01:55:50 Lists 02:01:45 2D Lists 02:05:11 My Complete Python Course 02:06:00 List Methods 02:13:25 Tuples 02:15:34 Unpacking 02:18:21 Dictionaries 02:26:21 Emoji Converter 02:30:31 Functions 02:35:21 Parameters 02:39:24 Keyword Arguments 02:44:45 Return Statement 02:48:55 Creating a Reusable Function 02:53:42 Exceptions 02:59:14 Comments 03:01:46 Classes 03:07:46 Constructors 03:14:41 Inheritance 03:19:33 Modules 03:30:12 Packages 03:36:22 Generating Random Values 03:44:37 Working with Directories 03:50:47 Pypi and Pip 03:55:34 Project 1: Automation with Python 04:10:22 Project 2: Machine Learning with Python 04:58:37 Project 3: Building a Website with Django

Медиафайл доступен в форматах

popular icon
Популярные
hd icon
HD видео
audio icon
Только звук
total icon
Все форматы
* — Если видео проигрывается в новой вкладке, перейдите в неё, а затем кликните по видео правой кнопкой мыши и выберите пункт "Сохранить видео как..."
** — Ссылка предназначенная для онлайн воспроизведения в специализированных плеерах

Вопросы о скачивании видео

question iconКак можно скачать видео "Python Full Course for Beginners"?arrow icon

    Сайт http://uniloader.pro/ — лучший способ скачать видео или отдельно аудиодорожку, если хочется обойтись без установки программ и расширений.
    Расширение UDL Helper — удобная кнопка, которая органично встраивается на сайты YouTube, Instagram и OK.ru для быстрого скачивания контента.

    Программа UDL Client (для Windows) — самое мощное решение, поддерживающее более 900 сайтов, социальных сетей и видеохостингов, а также любое качество видео, которое доступно в источнике.

    UDL Lite — представляет собой удобный доступ к сайту с мобильного устройства. С его помощью вы можете легко скачивать видео прямо на смартфон.

question iconКакой формат видео "Python Full Course for Beginners" выбрать?arrow icon

    Наилучшее качество имеют форматы FullHD (1080p), 2K (1440p), 4K (2160p) и 8K (4320p). Чем больше разрешение вашего экрана, тем выше должно быть качество видео. Однако следует учесть и другие факторы: скорость скачивания, количество свободного места, а также производительность устройства при воспроизведении.

question iconПочему компьютер зависает при загрузке видео "Python Full Course for Beginners"?arrow icon

    Полностью зависать браузер/компьютер не должен! Если это произошло, просьба сообщить об этом, указав ссылку на видео. Иногда видео нельзя скачать напрямую в подходящем формате, поэтому мы добавили возможность конвертации файла в нужный формат. В отдельных случаях этот процесс может активно использовать ресурсы компьютера.

question iconКак скачать видео "Python Full Course for Beginners" на телефон?arrow icon

    Вы можете скачать видео на свой смартфон с помощью сайта или pwa-приложения UDL Lite. Также есть возможность отправить ссылку на скачивание через QR-код с помощью расширения UDL Helper.

question iconКак скачать аудиодорожку (музыку) в MP3 "Python Full Course for Beginners"?arrow icon

    Самый удобный способ — воспользоваться программой UDL Client, которая поддерживает конвертацию видео в формат MP3. В некоторых случаях MP3 можно скачать и через расширение UDL Helper.

question iconКак сохранить кадр из видео "Python Full Course for Beginners"?arrow icon

    Эта функция доступна в расширении UDL Helper. Убедитесь, что в настройках отмечен пункт «Отображать кнопку сохранения скриншота из видео». В правом нижнем углу плеера левее иконки «Настройки» должна появиться иконка камеры, по нажатию на которую текущий кадр из видео будет сохранён на ваш компьютер в формате JPEG.

question iconКак воспроизвести и скачать потоковое видео?arrow icon

    Для этого понадобится VLC-плеер, скачать его можно бесплатно с официального сайта https://www.videolan.org/vlc/

    Как воспроизвести потоковое видео через VLC-плеер: