TRANSCRIPTEnglish

Python Full Course for free 🐍

12h 0m 0s92,922 words15,121 segmentsEnglish

FULL TRANSCRIPT

0:00

What's up everybody? In this video, I'm

0:02

going to teach you everything you need

0:03

to know to start coding with Python.

0:05

I've also included 20 different hands-on

0:08

projects to help you learn. You can find

0:10

the entire list in the description of

0:12

this video. Our final project will be a

0:15

weather app that fetches real-time

0:16

weather data from an API. Even if you've

0:19

never coded anything in your life

0:20

before, I'll walk you through the

0:22

basics, the ABCs of programming. If that

0:25

sounds good to you, then I encourage you

0:27

to sit back, relax, and enjoy the

0:32

show. This course doesn't cost you

0:34

anything, but if you would like to help

0:36

me out, you can help increase its reach

0:38

by hitting the like button, leave a

0:40

random comment down below, and subscribe

0:42

if you'd like to be a fellow bro. Thank

0:44

you. I appreciate it. I don't like

0:47

boring introductions, so I say we just

0:49

jump right in. There's two things we'll

0:51

need to download. The first is a Python

0:53

interpreter to convert our written code

0:56

to machine code. We're going to head to

1:00

python.org, go to

1:02

downloads, and download the latest

1:05

version. We will open this

1:09

executable. If you're on Windows, you'll

1:12

want to check this check box, add Python

1:15

exe to path, and we will install now.

1:22

The setup was successful. And that's all

1:25

you need to do to download the Python

1:27

interpreter. The second download we'll

1:30

need is an IDE, an integrated

1:32

development environment. Basically, a

1:35

place where we can write code. For

1:37

IDEES, there's two popular choices when

1:40

writing Python code. PyCharm and VS

1:43

Code. If you already use VS Code, you

1:46

can stick with that. Just be sure to

1:48

download the Python extension. I find

1:50

PyCharm more beginner friendly if you've

1:52

never coded before. If you would like to

1:54

use PyCharm, go to

1:59

jetbrains.com/pycharm. And we will click

2:01

this green download

2:02

button. There's two versions of PyCharm,

2:06

the professional version and the

2:08

community version. The professional

2:10

version is paid for. I would not

2:12

recommend using it only because there's

2:14

plenty of free IDE on the market. We'll

2:17

use the community edition, the free one,

2:19

because I don't like to pay for things

2:21

and I'm sure you don't either. Select

2:23

the correct download for your operating

2:25

system. I'm running Windows. I will

2:27

download

2:30

PyCharm. We will open this

2:33

executable. Click next. You could select

2:37

a destination folder. I'll keep it as

2:39

is. Next, I'll create a desktop

2:43

shortcut, but you don't necessarily need

2:46

to. Click

2:48

next. Install. And we'll just have to

2:51

give it a

2:53

moment. Okay, the setup is now complete.

2:57

I'll check this checkbox to run PyCharm

2:59

when we close this

3:01

window. After opening PyCharm, we're

3:04

going to create a new

3:06

project. You can rename your Python

3:08

project. I'll keep it as is. You can

3:11

select a location. Again, I won't change

3:14

that. You can create a sample welcome

3:16

script, but for this tutorial, we won't.

3:19

Let's select the latest Python

3:22

version and create our new

3:25

project. In the menu to the left, we're

3:28

going to create a new Python file. File,

3:31

new, Python

3:34

file. Let's name this file main.

3:38

But really you can name it anything and

3:41

select Python

3:43

file. Python files end with the py file

3:49

extension. We should have our main

3:51

Python file within our Python project

3:53

folder. Now we're going to print

3:55

something to the console window. Within

3:58

our main Python file, we're going to

4:00

write a print statement. So type print

4:03

add a set of parenthesis. Between the

4:06

set of parenthesis, we will add a set of

4:08

double quotes to print something or

4:11

single quotes. Either one. My own

4:14

preference is double quotes. Normally in

4:17

a programming tutorial, the instructor

4:19

would tell you to print something such

4:21

as hello world, but we like to be

4:23

different

4:24

here. Instead, think of your favorite

4:27

food. In this case, I like pizza. I will

4:30

print I like pizza.

4:35

To run our Python program, we will click

4:38

the screen arrow to run our main Python

4:42

file. We should have a console window

4:45

that displays our output. I like pizza

4:48

or whatever your favorite food is. Let's

4:51

print another line of code.

4:54

Let's

4:56

print it's really

5:01

good. By adding a second print

5:03

statement, we are printing a second line

5:06

of

5:07

code. Now we'll discuss

5:09

comments. The Python interpreter doesn't

5:12

output comments. To write a comment, you

5:16

use a pound sign. I like to call this a

5:18

hashtag. My comment will be this is my

5:23

first Python

5:25

program. Comments are used as notes for

5:28

yourself or for other people reading

5:30

this code. If I were to run this code

5:33

again, this comment is not displayed to

5:36

the output. We still have I like pizza.

5:39

It's really good. All right, everybody.

5:41

So, that is your very first Python

5:43

program. And in the next topic, we'll

5:45

discuss variables.

5:49

All right, everybody. We are moving on

5:50

to variables. A variable is a container

5:54

for a value. There's four different data

5:56

types. We'll discuss strings, integers,

5:59

floats, and booleans. Yes, I know that's

6:01

a silly name. A variable behaves as if

6:05

it was the value it contains. Each

6:07

variable should have a unique name.

6:09

Let's say we have a variable of first

6:11

name. To assign a variable, you use the

6:14

assignment operator of equals. For text,

6:18

a string is a series of text. This can

6:20

be double quotes or single quotes. My

6:23

own preference is double quotes. Why

6:26

don't you type in your first name? This

6:29

variable of first name will behave as if

6:32

it was this value, this series of

6:34

characters. So to demonstrate this, I'm

6:37

going to print my first name

6:41

variable. So place it within a print

6:43

statement without quotes. That will

6:46

print your first name. Now, you don't

6:49

want this within

6:51

quotes because then you're literally

6:53

printing the word first

6:57

name. You could use your variable along

6:59

with some text by using what is called

7:02

an F string. That's the easiest way to

7:04

display a variable. So, you type F then

7:07

a set of quotes. The F means

7:10

format. So, let's say the word hello.

7:14

Then we will add our variable. We will

7:16

insert our variable into this text when

7:18

using an F string. To do that, you need

7:21

a set of curly braces. Then insert your

7:24

variable. So the result is hello,

7:28

whatever your first name is. In my case,

7:30

bro. Let's create another

7:33

variable. Let's say we have a variable

7:36

of food. Food equals think of your

7:39

favorite food. For me, I will type

7:42

pizza.

7:44

Let's print the

7:46

following. You like add a placeholder.

7:50

Again, I'm using an F

7:52

string. Our variable of food. Hello,

7:55

bro. You like

7:58

pizza. Let's create an

8:00

email. Use your own email or make up

8:03

one. Let's say my email is

8:05

bro123@fake.com.

8:11

Then let's print our

8:14

email. Your email is add a placeholder.

8:19

Display our email

8:22

variable. Your email is

8:27

bro123@fake.com. So these are strings.

8:30

I'm going to add a comment that these

8:32

are strings. A string is a series of

8:36

characters. They can include numbers but

8:38

we treat them as

8:40

characters. Now we have

8:42

integers. An integer is a whole number.

8:45

An example of this could be somebody's

8:48

age. How old are they? According to my

8:50

YouTube statistics, many of you are

8:52

between the ages of 18 through 24. Let's

8:55

say that I'm

8:56

25. Let me zoom in a little. Your

8:59

integer should not be within quotes

9:02

because it would be a string. Then

9:04

technically if I would like to work with

9:06

this variable again I'll use an f

9:09

string. Let's say you are add a

9:13

placeholder display our age

9:16

variable years

9:19

old. You are 25 years old.

9:23

Another example of an integer could be a

9:27

quantity. You are buying a certain

9:29

amount of something. Maybe I am buying

9:31

three items. I wouldn't have half an

9:34

item. This would be a float technically

9:37

rather than an integer. We are buying

9:39

three of

9:40

something. So let's print the

9:43

following. You are

9:47

buying. Add a placeholder.

9:49

display our

9:51

quantity

9:53

items. You are 25 years old. You are

9:57

buying three

9:59

items. Another example of an integer

10:01

could be an amount of people. Let's say

10:05

num of students like a

10:08

classroom. There are 30 students in our

10:11

class.

10:12

Then we will

10:14

print your class has add a

10:19

placeholder students. We will display

10:22

the number of students. Num of

10:26

students. Your class has 30

10:30

students. Those are integers. They're

10:32

whole numbers. And again, make sure

10:34

they're not within quotes because then

10:37

technically they would be a string.

10:40

integers we can use in arithmetic

10:41

expressions. If they were strings, we

10:45

couldn't. Then we have floats. Float

10:48

means floatingoint

10:51

number. A float is a number, but it

10:53

contains a decimal portion. An example

10:56

would be a price. What is the price of

10:58

something?

11:00

$10.99. Let's print our price. Print.

11:03

I'll use an F string. The price is add a

11:07

placeholder. display our

11:10

price. The price is

11:12

$10.99. Let's preede our placeholder

11:15

with a unit of currency. I'll pick

11:17

American dollars, but feel free to pick

11:19

something else. The price is

11:23

$10.99. So, floats contain a decimal

11:25

portion. What about a grade point

11:28

average

11:29

GPA? Let's say my GPA is 3.2.

11:36

Then I will print your GPA

11:43

is display our

11:46

GPA. Your GPA is

11:50

3.2. What about a distance? A distance

11:53

can contain a decimal portion.

11:56

5.5 kilometers maybe.

12:01

Then I will

12:02

print you ran. Add a placeholder.

12:06

Display our distance. Then I'll add km

12:09

for kilometers. Or you could add mi for

12:12

miles, but I'll stick with

12:15

kilome. You rand 5.5

12:19

km. Okay. Then we have booleans. A

12:22

boolean is either true or

12:27

false. Let's say we're a student. is

12:31

student equals. If we are a student, we

12:34

could say that this is true. True starts

12:37

with a capital T. If we weren't a

12:40

student, let's say we graduate, we could

12:42

say that this is false. Again, the first

12:45

letter is capital. Booleans only have

12:48

two options, true or false. So, let's

12:51

say that I am a

12:52

student. Then I will

12:55

print are you a student?

12:59

Then we will display our boolean value

13:02

of is

13:03

student. Are you a student? That is

13:07

true. With boolean values, we really

13:09

don't output them directly. You're more

13:12

likely to see them used internally

13:14

within a program, such as when working

13:16

with if statements. This is a topic

13:18

we'll discuss in the future, so don't

13:20

worry. You may see if is student. If

13:24

this variable is true, then we will

13:27

print the

13:29

following. Now, we don't need to use an

13:31

string. We're not going to insert any

13:33

variables. You are a student. If this

13:37

were false, we can add an else

13:40

clause where we will

13:42

print you are not a

13:47

student. Our variable of is student is

13:49

true. We will print the if statement.

13:53

You are a student. If this were false,

13:56

we will print whatever is within

13:58

else. You are not a student. Let's think

14:02

of a few more

14:03

examples. Is something for sale like a

14:07

car or a product of some sort? Let's say

14:10

that is true. I'll write another if

14:13

statement. If for sale, if this variable

14:17

contains true, we will do the following.

14:21

Let's

14:22

print that item is for

14:26

sale. Else if it's false, we will print

14:30

something

14:32

else. That item is not

14:38

available. For sale is set to

14:41

true. This variable is true. We will

14:44

print that item is for sale. else if it

14:47

were

14:48

false we print that item is not

14:51

available.

14:53

One more example. Let's say we have a

14:55

boolean variable of is online. Is

14:58

somebody online? I will set that to

15:02

true. If is online. If that's true, we

15:07

will print you are

15:10

online. Else we will

15:12

print you are

15:16

offline. Is online is set to true. We

15:19

will print you are online. else if it

15:22

were false we print you're

15:26

offline. All right everybody so those

15:28

are variables. A variable is a reusable

15:31

container for a value. There's four

15:33

basic data types for beginners. A string

15:36

which is a series of text, integers

15:39

which are whole numbers, floats which

15:42

are numbers but they contain a decimal

15:43

portion and booleans which are either

15:46

true or false. They're binary. Your

15:50

assignment in the comment section is to

15:52

post four variables. Post a string, an

15:55

integer, a float, and a boolean. Try and

15:58

think of a unique example if you can.

16:00

And well everybody, those are variables

16:02

in

16:05

Python. All right everybody, so we are

16:07

moving on to type casting. Typ casting

16:10

is the process of converting a variable

16:12

from one data type to another. We have

16:15

various functions to convert a value or

16:18

variable to a string, an integer, a

16:21

float or a boolean. Let's create some

16:24

variables. We will create a name

16:27

variable. Type in your full

16:29

name, an age, make up some

16:33

age, a GPA for grade point average,

16:36

let's say minus

16:38

3.2, and a boolean of is student. Are we

16:43

currently a student? Let's say that's

16:46

true. Now, you actually could get the

16:48

data type of a variable or a value by

16:51

using the type function. Then pass in a

16:54

value or variable. However, when I run

16:57

this, there's no output. So, I need a

17:00

print statement. We will print what is

17:03

returned by the type function. Get the

17:07

type of our name variable, then print

17:09

it.

17:11

So our name variable is a string

17:14

str. Our age

17:16

variable is an integer and

17:20

int GPA is a

17:25

float is student is a boolean. Using

17:29

these type cast functions we can convert

17:31

from one data type to another. Here's

17:34

how. Let's start with something simple.

17:36

Let's convert our GPA to an integer.

17:39

Currently, it's a float. I will reassign

17:43

GPA. Use the int function to type cast

17:46

to an integer. Then pass in my GPA. At

17:51

the end, we will print our

17:54

GPA. If we type cast 3.2 to a whole

17:57

integer, what would the result be? A

18:00

whole integer of three. We truncate the

18:03

decimal

18:05

portion. Let's convert our age to a

18:07

floatingoint number. We will reassign

18:10

our variable of

18:11

age. Use the type cast function a float.

18:15

Then insert our age

18:17

variable. Let's print our age

18:22

variable. And it should be a floating

18:24

point number

18:27

25.0. Now we'll cover strings. Let's

18:30

type cast our age to be a string. age

18:35

equals call the type cast function of

18:37

string str pass in our age

18:42

variable. So the result is still going

18:45

to appear the

18:46

same 25. However, it's a string not an

18:51

integer. And to prove that I will

18:53

enclose my age variable with the type

18:57

function. The type of variable age is a

19:00

string.

19:01

It would be the same as if we're taking

19:03

this number and enclosing it within

19:07

quotes. So this would make a difference

19:10

because let's say that I add one to age.

19:13

Age plus equals

19:15

1. Well, we would get a type error. Can

19:18

only concatenate strings, not integers

19:21

to a

19:23

string. However, if I were to add a

19:25

string of one to the end, we would be

19:27

using string concatenation. So let's say

19:30

it's my birthday and I add 1 to 25.

19:33

Well, since we're working with strings

19:35

now, the result would be 251. I am 251

19:40

years

19:41

old. So strings and numbers behave

19:45

differently. With numbers, we can use

19:47

them within arithmetic expressions.

19:49

Strings, not so much. We will take our

19:53

name variable and type cast it to a

19:55

boolean.

19:58

name equals call the typcast function of

20:01

bool pass in our name

20:04

variable. This has an interesting

20:06

result. So I'm going to print name.

20:09

Booleans are either true or false. If I

20:13

type cast my string of text into a

20:16

boolean that gives me

20:18

true. Now it really doesn't matter what

20:21

I write here. If I were to change my

20:23

name to a single character such as B,

20:26

this would still be true.

20:28

If our string variable was empty, there

20:31

were no characters within it, that would

20:33

actually give us

20:34

false. We could use this to check to see

20:37

if somebody enters in their name or not.

20:39

If somebody types in their name, then we

20:41

type cast it to a boolean. If somebody

20:44

skips entering in their name, that would

20:46

return false. We could reprompt the user

20:49

to enter in their name again. All right,

20:52

everybody. So, that is type casting. It

20:54

is the process of converting a variable

20:56

from one data type to another. This is

20:59

especially useful with handling user

21:01

input because user input is always a

21:04

string. There may be at times where we

21:06

want to convert it to an integer, a

21:08

float or a boolean. And well everybody

21:11

that is type casting in

21:14

Python. All right everybody, in this

21:16

topic I'm going to show you how we can

21:18

accept user input in Python. We use the

21:20

input function. It's a function that

21:22

prompts the user to enter in data and it

21:25

returns the enter data as a string.

21:28

Here's an example. To accept user input,

21:30

we will call the input function. When I

21:33

run this program, we need to enter in

21:36

data to our console

21:38

window like so, then hit enter. However,

21:42

we need a

21:43

prompt. We need to tell the user what we

21:46

want them to type in. So, let's ask a

21:48

question. Our prompt will be within

21:51

quotes. Let's say, "What is your

21:57

name?" Let's try this again. What is

21:59

your name? I can type in something. Why

22:02

don't you go ahead and type in your full

22:04

name, then hit

22:06

enter. Now, with this input, we're not

22:09

quite doing anything with it. The input

22:11

function is going to return some data as

22:14

a string. We can assign it to a variable

22:16

if we would like. Let's create a

22:18

variable of name. Name equals our user

22:23

input. Then once we have our name, let's

22:27

print a message. I'll use an fstring. We

22:30

will print hello. Add a placeholder.

22:34

Then insert our name variable within

22:35

that

22:36

placeholder. Let's try

22:38

this. What is your name? Type in your

22:41

name. Hit enter. Hello. Whatever your

22:45

name is. Let's try a different name. I

22:48

will pick Spongebob. Many people are

22:50

familiar with Spongebob. Hello,

22:53

Spongebob. This time we will ask a user

22:56

how old they are. Let's assign a

22:59

variable of age equals accept some user

23:02

input. We need a prompt within

23:05

quotes. How old are you?

23:10

Once we have our age variable, let's

23:13

print I'll use an f string. You are add

23:18

a placeholder our variable

23:21

age years

23:24

old. What is your name? Type in your

23:28

name. How old are you? Let's say that

23:31

I'm

23:32

25. Hello. Whatever your name is, you

23:36

are whatever your age is. Years old.

23:40

All right. So, let's say that it's our

23:42

birthday. Before we print our age

23:45

variable, let's

23:46

say happy

23:50

birthday. Since I'm not inserting any

23:52

variables within this print statement,

23:55

this doesn't need to be an F string.

23:58

You'll want to use an F string if you

23:59

want to insert variables. Before we

24:01

display the user's

24:03

age, let's take the user's age and

24:06

increase it by one. We could say age

24:08

equals age +

24:11

one. But there's one problem with

24:14

this. Type in a

24:16

name. How old are you? Type in an

24:20

age. And we have a problem. We have a

24:23

type error. Can only concatenate

24:26

strings, not integers, to

24:29

strings. When we accept user input, we

24:32

store that input as a string. Before we

24:35

increment our age by one, we'll need to

24:38

convert it to an integer. We can't

24:39

normally use strings within arithmetic

24:42

expressions. But we can do that with

24:44

integers and floats, though. After we

24:47

accept some user input for our age

24:49

variable, we could take our age variable

24:52

and type cast it as an integer, which we

24:56

talked about in the previous lesson. So

24:58

let's say age equals our age after we

25:02

type cast it then increment it by

25:05

one. So type in your

25:08

name type in an

25:11

age and we get this message hello your

25:14

name happy birthday you are whatever

25:17

your age is years

25:19

old. So strings we can't normally use

25:22

with arithmetic expressions. We would

25:24

have to type cast it to an integer or a

25:27

float. However, we could condense some

25:29

of these steps. We're taking up an extra

25:32

line to type cast our age as an integer.

25:35

What we could do instead is that when we

25:37

accept our user input, we can enclose

25:40

the input function within a type cast to

25:43

int. And that would work the same. Type

25:46

in your

25:48

name, type in an age, and this works the

25:52

same. And it takes less lines of code

25:55

and is more readable. I would say when

25:57

we accept user input, it returns that

26:00

input as a string data type. Then we

26:02

just have to type cast it to another

26:04

data type if we need to. And in this

26:06

case for age, we do. Now, we'll go over

26:09

a couple exercises because it's

26:11

important to practice what you've

26:13

learned. In this first exercise, we're

26:15

going to calculate the area of a

26:17

rectangle. We need to prompt the user to

26:20

enter in a length and the width of a

26:21

rectangle.

26:23

So we will create a variable of length.

26:26

We will accept some user input using the

26:28

input function. What is our prompt?

26:32

Let's say enter the

26:35

length. Let's do this with width. I'll

26:38

just copy and paste what we have. Width

26:42

equals enter the

26:45

width. So we have the length and the

26:47

width. To get the area of a rectangle,

26:50

we have to multiply the length by the

26:51

width. So let's say area equals our

26:56

length variable. Now to use

26:58

multiplication you use an asterisk.

27:00

We'll discuss different arithmetic

27:02

operators in the next lesson. So we have

27:04

length time width. That is the

27:08

area. I'm going to print our area

27:12

because I need to test something. Enter

27:15

the length. Let's say five 5 in 5 cm.

27:19

Doesn't matter. Enter the width. six, we

27:23

get a type error. Can't multiply

27:25

sequence by non-int non- integer of type

27:29

string. When we accept user input, it

27:32

returns a value of the string data type.

27:34

We can't use those strings in arithmetic

27:37

expressions. We're multiplying the

27:39

length times the width. We would need to

27:41

type cast them as an integer or a float.

27:44

Since we're working with basic geometry

27:47

such as calculating the area, let's do

27:49

float. So let's type cast our user input

27:52

as a float for both length and

27:59

width. Okay, let's try this again. Let's

28:03

say 5 * 6. The area that's returned to

28:06

us is 30.

28:08

30.0. This result contains a decimal.

28:11

It's a floating point number, a

28:14

float. So when we print the area, I'll

28:17

use an f string this time. The area is

28:22

I'll add a placeholder. Display our area

28:25

variable. Let's add a unit of

28:27

measurement afterwards. I'll pick

28:29

centimeters. Now, since we're working

28:31

with areas, if we would like to

28:33

technically be accurate. So, we could

28:35

say to the power of two or we could add

28:38

a superscript. So, if you would like

28:41

superscript 2 and you're on Windows,

28:43

make sure num lock is on, hold alt, then

28:46

type on the numpad

28:49

0178. So, we have a superscript of two.

28:53

Again, it's not really necessary for

28:55

this lesson. I just think it'd be cool

28:57

to include it because then it's

28:58

technically

29:00

accurate. All right, let's say that the

29:02

length is

29:03

6.1 and the width is 7.2.

29:08

The area is

29:11

43.92 cm squared because we're working

29:14

with areas. Let's cover a second

29:17

exercise. This time we will create a

29:19

shopping cart program. Exercise two,

29:22

we're going to create a shopping cart

29:23

program. We need three variables. An

29:26

item, a price, and a quantity of those

29:30

items. We will create a variable of

29:33

item. We will accept some user input.

29:37

What item would you like to

29:42

buy? What are we trying to purchase?

29:45

We'll keep the data type of the user

29:47

input as a

29:48

string. Then we need a price. What is

29:51

the price of each item we're buying? Use

29:53

the input

29:55

function. What is the

30:00

price? A price should be a floatingoint

30:03

number. For example, we might have

30:05

dollars and cents. We need a decimal. So

30:08

let's type cast our input as a float.

30:11

Then a

30:13

quantity. We will accept some user

30:16

input. Our prompt will be how

30:21

many would you

30:25

like? Quantities. They should be whole

30:28

numbers. Let's type cast our input as an

30:32

integer. Then we will have a total.

30:35

What's the total that we have to pay?

30:38

So, let's take the price of each item.

30:41

Use an asterisk for multiply our

30:44

quantity. Then, let's do a test run.

30:48

Let's print our

30:50

total. What item would you like to buy?

30:52

Let's say a pizza. What is the price?

30:57

$10.99. How many would you like? I would

31:00

like five

31:02

pizzas. and our total is

31:07

54.95. Let's say that before we display

31:09

the total, let's print the following.

31:12

I'll use an F string. You have

31:16

bought insert a placeholder. Display our

31:20

quantity

31:23

X item or items. I'll add slash

31:28

S. Then we will print I'll use an F

31:31

string again.

31:33

Your total

31:36

is display our

31:39

total. What item would you like to buy?

31:42

I would like to buy a pizza. What is the

31:45

price?

31:47

$10.99. How many would you like? I would

31:49

like nine pizzas. They're all for me.

31:52

I'm going to eat all of

31:54

them. You have bought 9 x pizzas. Your

31:58

total is 98.91.

32:01

Let's add a unit of currency before

32:03

this. Pick unit of currency before

32:05

displaying the total. I'll pick American

32:09

dollars. I would like to buy pizza. What

32:12

is the price?

32:15

$9.99. How many would you like? I would

32:18

like a dozen pizzas.

32:20

12. You have bought 12 x pizzas. Your

32:25

total is

32:28

$119.88. All right, everybody. That is

32:30

how to accept user input in Python. And

32:32

we've covered a few exercises. In the

32:35

next topic, we're going to create a Mad

32:36

Libs game. And that is how to accept

32:39

user input in

32:41

Python. All right, everybody. In this

32:43

video, we're going to create a game of

32:45

Mad Libs. Not because we have to, but

32:47

because I want to. It would be a good

32:49

exercise for us, just so we're more

32:51

comfortable with accepting user input.

32:53

If you're not familiar with Mad Libs,

32:55

Mad Libs is a word game where you create

32:57

a story by filling in the blanks with

33:00

random words. So, we're going to create

33:02

a story template. The story is going to

33:05

be missing some components. We will fill

33:07

in those components with random words

33:09

that we type in. Here's a story that

33:11

I've written myself. Print. Use an F

33:15

string. Today, I went to a insert a

33:20

placeholder zoo.

33:23

For our placeholder, we'll insert an

33:26

adjective. We'll insert a variable named

33:29

adjective. Adjective. Adjective one.

33:32

You're going to get an English lesson

33:34

today, too. An adjective is a

33:36

description of something. So, for our

33:39

zoo, adjective one could be

33:43

expensive,

33:44

large, dirty. An adjective describe

33:48

something. We'll fill this in when we

33:50

accept user input.

33:53

For our second print statement, let's

33:54

print the

33:56

following. In an

33:59

exhibit, I saw a placeholder. We'll

34:05

include a noun. Noun one. A noun is a

34:09

person, place, or thing in English.

34:12

Maybe a gorilla. A gorilla named

34:14

Harambe, for

34:16

example. Print. Use an F string. Let's

34:20

say our noun one whatever this is we can

34:23

reuse

34:25

variables

34:27

was we will create a second adjective

34:30

adjective 2 we will be describing

34:34

whatever noun one is this person place

34:37

or thing and we will insert a verb verb

34:42

one a verb is an action such as running

34:46

or eating. Then for our last statement,

34:50

let's print I was add a

34:54

placeholder. We'll create adjective

34:57

three. Adjective 3 will describe us. Now

35:01

we're going to fill in these variables

35:03

by accepting user input. We're going to

35:06

fill in adjective

35:07

one. We'll accept user input using the

35:10

input

35:11

function. Enter an adjective.

35:16

I'm going to add a reminder that an

35:18

adjective is a description of

35:24

something. Then we need noun

35:27

one. Noun one equals

35:30

input. Enter a noun. A noun is a person,

35:35

place, or

35:38

thing. Then we have adjective two. I'll

35:41

just copy adjective one. Paste it.

35:44

Change one to

35:46

two. Then a verb. Verb one equals

35:51

input. Enter a verb. I want verb one to

35:55

be in current tense. I'll ask the user

35:58

to end the verb with ing. Enter a verb

36:03

ending with

36:06

ing. Then it's current tense. our

36:09

person, place, or thing of noun one is

36:12

currently doing something such as

36:15

eating. And then adjective three. And

36:17

I'll just copy one of these

36:19

adjectives. Adjective 3 equals input.

36:23

Enter an adjective. Okay. And then we

36:25

are ready to run this. Enter an

36:28

adjective. An adjective describes

36:30

something. I will say

36:34

suspicious or some kids like to say

36:37

sussy or sus even. I've also heard of

36:40

kids nowadays using the word skipy. Feel

36:44

free to type in whatever you would like.

36:46

It is your story after all. I'm going to

36:48

say

36:51

suspicious. Enter a noun, a person,

36:53

place, or thing. I like to poke fun at

36:56

Mark Zuckerberg. So, I'm going to say my

36:58

person is

37:00

Mark

37:02

Zuckerberg. Enter an adjective. That is

37:04

a description.

37:07

Angry. Enter a verb ending with ing. So,

37:11

it's current tense. Uh,

37:15

screeching. Enter an adjective.

37:19

Happy. Here's my story. Today I went to

37:23

a suspicious zoo in an exhibit. I saw a

37:27

Mark

37:28

Zuckerberg. Mark Zuckerberg was angry

37:31

and screeching. I was happy. That's our

37:35

game of Mad Libs. It's a word game where

37:37

you create a story by filling in the

37:39

blanks with random words. Also, post the

37:43

output of your Mad Libs game in the

37:44

comment section down below because I

37:46

really want to read them. I want to see

37:48

what you guys came up with. And well

37:50

everybody, that is a Mad Libs game using

37:55

Python. Hey everybody, in this video I'm

37:58

going to show you all of the different

37:59

math that we'll need throughout the rest

38:01

of the series. I have a lot to cover and

38:03

I'll split this video into different

38:04

sections. We'll cover some basic

38:07

arithmetic operators, built-in math

38:09

functions, a few functions from the math

38:12

module, and then a few exercises. Be

38:14

sure to look at the timestamps if you

38:16

would like to skip ahead to another

38:17

section. Let's begin with some really

38:19

easy stuff. We're going to cover some

38:21

basic arithmetic operators. Let's say we

38:23

have a variable

38:26

friends. Currently, you have zero

38:29

friends. If you need to increment a

38:31

variable by one, you could say friends,

38:35

the name of the variable equals the name

38:37

of the variable again + 1. So, the plus

38:41

sign is the addition operator. And I

38:43

think we do have a little bit of

38:44

experience with that already. So if I

38:46

were to print my variable

38:49

friends, guess what? You now have one

38:52

friend. We could also shorten this line

38:54

of

38:55

code. You could say friends plus equals

39:00

1. That would do the same thing. This is

39:03

known as an augmented assignment

39:06

operator. That will give you the same

39:08

result. I prefer to use augmented

39:10

assignment operators just because they

39:12

take less text and I think they're

39:14

easier to read. Now let's use

39:16

subtraction. Friends equals

39:20

friends minus 2. So of course minus is

39:23

the subtraction operator. Uh you have -2

39:26

friends. I guess if you were to use the

39:29

augmented assignment operator that would

39:31

be friends minus equals

39:34

2. There you still have -2 friends.

39:38

Okay. Multiplication. Let's change

39:40

friends

39:41

to how about five. Friends equals

39:46

friends time

39:48

3. You now have 15 friends. Then the

39:52

augmented assignment operator version of

39:54

this would be friends time=

40:01

3. So again you have 15 friends. Let's

40:05

cover

40:07

division. Friends equals friends divided

40:12

by

40:14

two. So we have 2.5 friends. Somebody

40:18

was cut in half. We have half a friend.

40:20

Maybe it's just their legs or torso or

40:22

something. Then the augmented assignment

40:24

operator would be

40:26

friends / equals 2. And the result is

40:31

still the same.

40:34

Now exponents friends equals friends to

40:39

the power of two. So friends is

40:42

currently five. Friends to the power of

40:45

two would be 5 * 5 which is 25.

40:51

The augmented assignment operator

40:53

version of this equation would be

40:56

friends exponent equals

41:00

2 and again friends is

41:03

25. Then we have modulus. Modulus gives

41:06

you the remainder of any division.

41:08

Suppose we have 10 friends instead of

41:10

five. I will assign a new variable

41:14

remainder. Remainder equals friends. The

41:18

percent sign is known as the modulus

41:20

operator. It will give us the remainder

41:23

of any division. If I were to divide my

41:25

group of friends by three, we will have

41:27

one remaining. I'll store the remainder

41:30

within a separate variable. We would

41:31

have a remainder of one. It's kind of

41:33

like in class when the teacher says for

41:35

everybody in the class to go into groups

41:37

of three, then there's always that one

41:39

kid that's by themselves. That's kind of

41:41

the same concept. We're dividing our

41:43

friends into groups of three. then the

41:46

modulus will give you the remainder. If

41:48

we divided our group of friends into

41:50

groups of two, well 10 divides by two

41:53

evenly, so there is no remainder. So

41:56

that is the modulus operator. It's

41:58

fairly popular to use this operator to

42:00

find if a number is even or odd because

42:02

it will divide by two evenly if that

42:04

number is even. If the remainder is one,

42:06

that means that the original number is

42:08

odd. Okay, so yeah, those are some basic

42:10

arithmetic operators. addition,

42:13

subtraction, multiplication, division,

42:16

exponentiation, then

42:18

modulus. Now what we're going to do is

42:20

cover some built-in math related

42:22

functions. Suppose we have three

42:24

variables x=

42:27

3.14, y =

42:30

4, z = 5. It doesn't matter if these are

42:34

floating point numbers or whole

42:36

integers. The first is the round

42:38

function. We have a variable named

42:40

result. I'm going to round

42:44

x. So there is a built-in round

42:46

function. After the set of parenthesis,

42:49

we can add some value or variable to be

42:52

rounded. So we will round x to the

42:55

nearest whole integer. Then print the

42:59

result. So our result is three. So

43:03

that's the round

43:05

function. With the absolute value

43:07

function, we can find the absolute value

43:10

of a number. Uh let's change y to be -4

43:13

instead of

43:14

four. We'll take result equals abs which

43:19

means absolute value of y. The absolute

43:22

value is the distance away from zero as

43:25

a whole

43:26

number. The absolute value of -4 is

43:31

4. Let's change y back to

43:36

four. There's a built-in power function.

43:40

result equals

43:43

pow. Then we'll need a base and an

43:46

exponent. What's y to the power of

43:51

3? That would be 4 * 4 * 4, which is 64.

43:56

That's the power function. You can raise

43:59

a base to a given

44:01

power. The next two are really useful.

44:04

Using the max function, we can find the

44:07

maximum value of various values. What's

44:10

the maximum value between x, y, and z?

44:15

Then I'll just need to store this value.

44:17

Uh results equals the max between x, y,

44:21

and z. Well, the maximum value is

44:25

five. Otherwise, there's

44:31

min. What's the minimum value between X,

44:34

Y, and Z? That would be

44:38

3.14. Now, in this next section, we do

44:40

have some very useful constants and

44:42

functions from the math class, but we'll

44:45

need to import the math module at the

44:47

top of our text editor. So, import math.

44:51

If you need the value of pi, you'll type

44:54

the name of the math

44:57

module.py. And I'm just going to print

44:59

this. print

45:02

math.py. The value of pi is

45:06

3.14159 and a bunch of digits that come

45:09

after. If you're working with physics, I

45:11

do know that people use the constant e a

45:14

lot. We won't be using e in this video

45:17

series, but if you ever need access to

45:18

it, just type math. E, and that will

45:22

give you e, which is 2.71 something

45:25

something something. I believe e is

45:27

known as the exponential constant. If

45:30

you need the square root of a number,

45:33

let's say result

45:35

equals math.

45:38

SQRT, we can place a variable or a value

45:42

within the square root function. Uh

45:43

let's say we have x again.

45:46

x= 9. What is the square root of x? Then

45:51

I will print whatever the result

45:54

is. The square root of 9 is three. That

45:58

is the square root

46:01

function. There's a ceiling function.

46:04

Result equals

46:06

math dot seal. Seal will always round a

46:11

floatingoint number up. Suppose x is

46:16

9.1. So 9.1 rounded up is

46:20

10. Otherwise there's floor which will

46:24

always round a number down. result

46:26

equals math.f floor. Let's change x to

46:32

9.9. 9.9 rounded down is 9. Those are

46:37

some useful math functions. Let's go

46:38

over some

46:40

exercises. Okay, this first exercise we

46:42

are going to calculate the circumference

46:44

of a circle. We'll need the help of the

46:47

math module because there's some good

46:49

functions in there. To calculate the

46:51

circumference of a circle, the formula

46:54

is 2 * * r. Let's ask a user for a

46:59

radius because that's what r is. We'll

47:02

accept some user

47:04

input. Enter the radius of a

47:10

circle. We will type cast the input as a

47:14

floatingoint

47:16

number to calculate the circumference.

47:21

Again the equation is 2 * pi. We can get

47:26

that from the math module times whatever

47:29

the radius is. And the user is going to

47:32

type that in. Then we will print

47:34

whatever the circumference

47:36

is. Print. We'll use an fstring

47:40

the

47:42

circumference

47:43

is our variable circumference.

47:48

Enter the radius of a circle. I'll enter

47:51

10, actually

47:53

10.5. Their circumference is

47:57

65.97. If you want to round and truncate

47:59

some of these numbers, we can use the

48:02

round function. Round

48:04

circumference, then round to a given

48:06

decimal place. I'll round to two

48:09

digits. Again, 10.5 rounded is

48:14

65.97. You could add a unit of

48:16

measurement, too. Let's say centimeters

48:19

10.5 is

48:21

65.97 cm. All right, that is the first

48:25

exercise. For this next exercise, let's

48:28

calculate the area of a circle. We'll

48:30

import the math

48:32

module. We'll ask for a radius. Much

48:35

like before, radius equals

48:40

input. Enter the radius of a circle.

48:46

We'll cast our input as a floatingoint

48:51

number. The equation for the area of a

48:53

circle

48:55

is

48:57

pi time radius squared. We could easily

49:01

use the built-in power function to raise

49:04

our radius to the power of two. Then we

49:07

will display the area. print. I'm using

49:10

an F string. The

49:14

area of the circle

49:18

is our area to some unit of measurement.

49:22

Let's say centime

49:25

squared. Enter the radius of a circle

49:29

10.5. The area of the circle is

49:33

346.36. But I would like to round this

49:35

number to two decimal places.

49:38

I'll use that round

49:40

function and I'll place area and the

49:43

number of digits to round to within this

49:45

function. Let's try that again.

49:48

10.5. The area of the circle is

49:52

346.36 cm squared. That is the second

49:56

exercise. For this last program, we're

49:58

going to find the hypotenuse of a right

50:01

triangle. The formula to calculate the

50:04

hypotenuse of a right angle triangle is

50:07

C equ= the square of A^2 + B^2.

50:12

We'll begin by importing the math

50:14

module. We'll ask the user for the

50:16

lengths of side A and

50:19

B. A

50:21

equals

50:24

input. Enter side

50:27

A. We'll cast the input as a

50:30

floatingoint

50:32

number. We'll do the same thing with

50:34

side B.

50:37

B

50:40

equals enter side

50:44

B. Now this part's going to be

50:46

confusing. We'll calculate C. We'll need

50:48

A^2 + B ^ 2. We'll take A to the^ of 2

50:56

plus B to the^ of

50:59

2. Then we'll need the square root of

51:02

all of this. Whatever the result is, I

51:05

will surround this equation with math.

51:09

Square root and that should give us our

51:13

answer. Let's

51:16

print using an F

51:19

string. Side C

51:22

equals whatever C

51:25

is. So, enter side A three. Side B will

51:29

be four. side C is five. All right,

51:33

everybody. So, that was everything

51:35

related to some arithmetic operators and

51:37

math related functions in Python. And in

51:40

the next video, we're going to cover a

51:42

few things involving string

51:43

[Music]

51:45

formatting. Hey everybody, in this topic

51:48

I'm going to explain if statements. An

51:50

if statement is used to do some code

51:52

only if some condition we set is true.

51:56

Else we could do something else. It's a

51:58

basic form of decision-m. If it's true,

52:01

we do something. If it's not true, we

52:03

don't do it. Let's ask a user for their

52:05

age. Age equals

52:09

input. Enter your age. I will type cast

52:13

the input as an

52:16

integer. Depending on what the user's

52:18

age is, we can do one of a few things.

52:21

Let's pretend that the user would like

52:22

to sign up for a credit card, but in

52:24

order to do so, their age needs to be

52:26

greater than or equal to 18. Well, we

52:29

can check that. To use an if statement,

52:31

type if, then some condition. What would

52:35

we like to check? Let's check to see if

52:37

the user's age is greater than or equal

52:40

to 18. Then add a colon, then hit enter.

52:45

Any code underneath the if statement

52:47

should be indented. Make sure to pay

52:49

attention to that because that's easy to

52:50

miss. If the user's age is greater than

52:54

or equal to 18, let's print you are now

52:58

signed

53:00

up. If I were to run this code, I'll

53:03

type in my age. I'll type 21. Hit enter.

53:07

This statement is true. Therefore, we

53:09

will execute any code found within the

53:11

if statement. You are now signed up.

53:14

What if this condition was not

53:16

true? Let's say my age is 13. Well,

53:20

nothing happens. If the condition we

53:22

check is instead false, we skip over

53:25

this code. If you need to take a

53:28

different course of action, you could

53:29

add an else

53:31

statement. If this is true, do this.

53:35

Else, we can do something

53:37

else. Let's print a different

53:40

message. You must be 18 plus to sign

53:46

up. I'll type in my age again. I'll say

53:49

that I'm 13. Hit enter. You must be 18

53:53

plus to sign up. That's basically an if

53:55

statement. Do some code only if some

53:59

condition is true. Else you can do

54:01

something else entirely. It's a basic

54:04

form of decisionm. The else statement is

54:06

kind of like a last resort. We can check

54:09

more than one condition before reaching

54:11

the else statement. We can add an else

54:14

if statement which we just shortened to

54:17

e l i if meaning else if. else if let's

54:21

check if age is less than

54:26

zero then we'll print a different

54:28

message you haven't been born

54:34

yet. Now if I run this code I'll say

54:38

that my age is negative one.

54:41

This condition is false. We skip this

54:43

code. This condition is true. Therefore,

54:47

we will execute this code and we skip

54:49

the else statement. You haven't been

54:52

born yet. Let's add another else if

54:54

statement. You can add as many else if

54:56

statements as you want. Let's check to

54:59

see if somebody's age is greater than or

55:01

equal to 100. We'll print a different

55:04

message.

55:05

Let's print you are too old to sign

55:11

up. If I were to say my age is 111 years

55:16

old, well, it states you are now signed

55:19

up. The reason that we didn't reach this

55:21

part of our else if statement. That's

55:24

because this condition is still

55:26

technically true. You do need to pay

55:28

attention to your order of if and else

55:30

if statements. If I want to be sure that

55:32

nobody over 100 is signing up, I should

55:36

probably move this to the

55:39

beginning. If age is greater than or

55:42

equal to 100, then else if age is

55:46

greater than or equal to 18, we'll do

55:48

something

55:50

else. Enter your age. I am 111 years

55:53

old. You are too old to sign up. So

55:56

those are if statements. If some

55:58

condition is true, do something. else if

56:01

you can check something else. If no

56:04

above conditions are true, you could do

56:06

something else entirely. It's kind of

56:08

like the default. Here's another

56:09

example. We'll ask a user if they would

56:12

like some food. Response equals

56:17

input. Would you like

56:21

food? We'll have the user type in Y for

56:25

yes or N for no.

56:32

If our

56:33

response now to check to see if two

56:36

values are equal, you would use double

56:39

equals. If the response is equal to y,

56:44

then we will

56:47

print have some

56:50

food. The doubles equal sign is the

56:52

comparison operator. It will check to

56:55

see if two values are equal. You don't

56:58

want one equals because that's the

56:59

assignment operator. Python in this case

57:02

thinks we're attempting to assign the

57:04

character y to response. So for

57:07

comparisons use double

57:11

equals else we can

57:15

print no food for

57:19

you. So would you like food? I'll type

57:22

y. Have some

57:24

food. Let's try it again. I'll type no

57:28

and for no. No food for

57:31

you. Here's a third example. We'll have

57:34

a user type in their name. Name equals

57:38

input. Enter your

57:42

name. If our name is equal to an empty

57:47

string, that means they didn't type in

57:49

anything. So, let's yell at the user.

57:53

You did not type in your

58:00

name. Else we will print using an

58:05

fstring hello whatever the name

58:09

is. Enter your name. I'm just going to

58:11

hit enter. You did not type in your

58:14

name. Let's run this again. I'll type in

58:17

my

58:17

name. And we have executed the else

58:20

statement this time. Hello

58:23

bro. So one important thing that you

58:25

should know is the use of booleans with

58:28

if statements. Suppose we have some

58:30

boolean variable named for sale. I'll

58:34

set this to be true. Now using an if

58:36

statement you can just use the boolean

58:39

variable in place of a condition because

58:41

a condition would evaluate to be true or

58:44

false.

58:46

We could just say if for sale if that's

58:50

true then let's

58:53

print this item is for

58:58

sale. Else we will

59:02

print. This item is not for sale. For

59:08

sale is set to be true. This item is for

59:11

sale.

59:13

If this variable were

59:15

false, well then the item is not for

59:18

sale. Let's try a different variable.

59:20

How about

59:22

online?

59:24

If

59:26

online, the user is online. Else the

59:32

user is

59:35

offline. So the user is

59:39

offline. I'll change the boolean to

59:41

true. the user is

59:44

online. So with if statements, you can

59:46

either write a condition or you could

59:48

use a

59:49

boolean. All right, everybody. So those

59:51

are if statements. Do some code only if

59:55

some condition is true. Else you can do

59:58

something else. It's a basic form of

60:00

decision-m and those are if statements

60:03

in

60:05

Python. Hey everybody, this is a remake

60:08

of my Python calculator program for

60:10

absolute beginners. All you need to know

60:12

to complete this exercise is just if

60:14

statements and how they work. So let's

60:16

get started. For this exercise, a user

60:18

is going to select an arithmetic

60:20

operator. Operator equals input. We will

60:24

ask the user to enter an

60:28

operator. This will be plus for

60:30

addition, minus for subtraction,

60:33

asterisk for multiplication, and a

60:35

forward slash for division. You could

60:37

enter more than this, but I don't want

60:39

to make this exercise too complicated.

60:41

We will create a variable of num one to

60:44

contain our first number. Let's say we

60:46

would like to add two numbers together.

60:48

What is the first number going to

60:51

be? Enter the first

60:55

number. And let's do this with the

60:57

second

60:59

number. Num two. Enter the second

61:04

number. Let me show you something.

61:06

I'm going to add num one and num two

61:09

together. Num one plus num two. We'll do

61:13

a test

61:14

run. Enter an operator. I would like to

61:17

use addition. Enter the first number 10

61:21

and 11. Well, the result is

61:25

1,1. When we accept user input, they are

61:28

string data types. What we've ended up

61:30

doing is string concatenation. We've

61:33

concatenated the string of 11 to 10.

61:36

That's why we ended up with 1,1. We'll

61:39

have to convert these two strings to be

61:41

floating point numbers by type casting

61:44

them as a

61:49

float. So enclose your input functions

61:52

with a type cast a float. And now we

61:55

should be able to add those two numbers

61:57

together. So let's add 10 and 11 and we

62:01

get 21.0. 0. Depending on the operator

62:04

that the user selects, we'll use some if

62:06

statements to determine that. We will

62:09

check if our operator variable is equal

62:12

to a character of

62:16

plus. And for now, I'll write pass as a

62:18

placeholder. We'll get back to this

62:20

later. Else if our

62:23

operator is equal to minus, we will use

62:28

subtraction. And for now, I'll write

62:30

pass.

62:32

Else if operator is equal to an asterisk

62:35

for multiplication, we will

62:39

multiply. Else if our operator is equal

62:42

to a forward slash for division, we will

62:45

divide. If our operator is addition,

62:49

let's create a variable of

62:52

result. Result equals num 1 + num

62:57

2. For

63:00

subtraction, it's going to be num 1

63:02

minus num

63:04

2. Multiplication would be num 1 * num

63:09

2. Then division would be num 1 / num 2.

63:15

Then we just have to print the result.

63:17

Print our

63:19

result. Be sure to do this with each of

63:22

the else if statements as

63:24

well. And let's see what we have.

63:27

Let's add 5.5 +

63:33

6.9. That gives us

63:35

12.4. Let's

63:37

subtract

63:39

420 minus

63:41

0.69. That gives us

63:45

419.31. Let's test

63:47

multiplication. Multiply

63:50

3.14 times

63:52

3.14, which gives us 9.8596.

63:56

8596. Then

63:59

division. Let's

64:01

divide 69 by

64:05

13. And that gives us a really long

64:07

number. So you could round a number if

64:10

you would like. We would enclose our

64:12

result within the round

64:16

function. And we'll just update each of

64:19

these print

64:21

statements. This will round to the

64:23

nearest whole integer. So let's divide

64:26

420 by

64:28

13. Let's say that we would like three

64:31

digits after the decimal. Within the

64:34

round function, we could add comma 3 for

64:36

three decimal

64:39

places. Enter operator. Let's use

64:43

division. Divide 420 by

64:47

69. So that gives me

64:50

6.087. So, we can round to a given digit

64:54

after a decimal. In this case, three

64:57

places. What if somebody types in an

64:59

operator that doesn't exist, like the

65:01

word

65:02

pizza? Then I will divide two

65:05

numbers. Well, let's add an else

65:07

statement. If somebody selects some

65:10

input that is invalid, let's let them

65:13

know. I'll use an fring.

65:16

Let's say that the operator that the

65:18

user has

65:20

selected is not valid. And let's try

65:24

this again. Enter an operator pizza.

65:27

Enter the first number 420 and

65:31

69. Pizza is not valid. Let's say is not

65:34

a valid operator instead. That makes

65:38

more

65:39

sense. Pizza will be my operator.

65:44

First number is 420. Second number is

65:47

69. Pizza is not a valid

65:50

operator. All right everybody. So that

65:52

is a very simple Python calculator

65:54

program you can make as a

65:58

beginner. Hey there, it's me again. In

66:01

today's topic, we're going to create a

66:03

weight converter program in Python. This

66:06

is an exercise that will follow up the

66:08

lesson on if statements. We'll convert

66:10

pounds to kilog or kilog to pound. The

66:13

user is going to decide. We will begin

66:15

by creating a weight variable. We will

66:17

assign some user

66:19

input. Enter your

66:22

weight. We will convert this input into

66:25

a floatingoint

66:26

number. So add that cast. Then we will

66:29

ask for a unit. Is this weight in

66:32

kilogram or

66:34

pounds?

66:36

Input kilogram

66:39

or pounds.

66:42

We want the user to type in either K for

66:45

kilogram or L for pounds. And these are

66:49

capital letters, by the

66:51

way. Using an if statement, let's first

66:53

check to see if our unit is equal to a

66:57

capital K. That means the current weight

67:00

is in kilogram. We need to convert that

67:03

weight to pounds.

67:05

Let's reassign weight equal

67:09

to our weight

67:12

times

67:15

2.205. Else if unit is equal to L, we

67:21

need to convert to

67:22

kilogram. Weight equals weight divided

67:26

by

67:29

2.205. Else the user did not type in

67:31

something that was valid. Let's

67:34

print using an

67:37

fstring

67:39

unit was not

67:42

valid. At the end of our program, we

67:45

will print the new weight. I'll use an

67:48

fstring. Your weight

67:52

is our new weight after it's reassigned.

67:56

Now, we need a unit of measurement. This

67:58

is what I'm thinking we'll do within our

68:01

if and else if statements. Let's

68:03

reassign our unit. We're reassigning

68:06

unit to be lbs for

68:10

pounds. Else if unit equals kgs for

68:17

kilogram in our results, we will display

68:20

our new unit. Let's take a look. Enter

68:24

your weight. Actually, I'm just going to

68:26

make one change. I'm going to add colon

68:29

space there. That's much better.

68:32

Enter your

68:33

weight. Let's say I'm 180 lb. This is in

68:38

pounds. I'll type capital L. Your weight

68:41

in kilog is

68:44

81.63. I think I'm going to round this.

68:47

I will enclose the weight variable

68:48

within a round

68:50

function. We will round to one decimal

68:52

place. Let's try this again. Enter your

68:56

weight. Maybe I'm 81

68:58

kg. I'll type k for kilogram.

69:02

Your weight is 178.6 lb. Let's make sure

69:06

that this else statement works, too.

69:09

Enter your

69:10

weight. 180

69:13

pizzas. Pizzas was not valid. So, we're

69:16

still displaying our output. We would

69:18

want to avoid that if somebody doesn't

69:20

type in a valid unit. So, let's cut this

69:25

line. Then, paste each within the if and

69:28

else if

69:29

statements. When we exit the else

69:31

statement, we're not printing the

69:33

output. So, let's make sure that this

69:36

works. Enter your weight. I am 180

69:41

pizzas. Pizza was not

69:43

valid. All right, everybody. Well, that

69:46

is a weight converter program in Python.

69:48

I thought this would be a helpful

69:50

exercise now that we have finished the

69:52

section on if statements. And yeah, that

69:54

is a weight converter program in Python.

69:59

Hey everybody. In this topic, we're

70:01

going to create a temperature conversion

70:03

program as an exercise. We'll begin by

70:05

asking what the current unit of

70:07

measurement is. Unit

70:10

equals will accept some user

70:13

input. Is this

70:17

temperature

70:19

in

70:22

Celsius or Fahrenheit?

70:29

C

70:31

slashF then we will ask for the

70:34

temperature. I'll store the temperature

70:36

in a variable named temp meaning

70:38

temperature. temp equals

70:42

input enter

70:45

the

70:47

temperature. Then we should cast our

70:49

user input as a floatingoint

70:53

number. If unit is equal to

70:59

C, I'll fill this in momentarily. I'm

71:02

just going to write pass as a

71:05

placeholder. Else if unit is equal to F,

71:10

we will do something

71:13

else. Else, let's print something. Just

71:16

an error message of some sort using an F

71:19

string.

71:22

unit

71:24

is an invalid unit of

71:29

measurement. Let's test this else

71:32

statement. Is the temperature in Celsius

71:35

or Fahrenheit? What if I were to type K

71:37

for Kelvin? I'll make up some

71:39

temperature like 100. K is an invalid

71:43

unit of measurement. All right, we know

71:45

the else statement works. Let's convert

71:47

Fahrenheit to Celsius using this

71:49

formula. We will take our

71:52

temperature

71:54

equals 9 * our

71:58

temp /

72:01

5 +

72:03

32. I'll take all of this and use the

72:05

round function. We'll round to one

72:08

decimal

72:10

place. Then we will print the current

72:12

temperature in

72:14

Fahrenheit. I'll use an F

72:17

string. The

72:20

Temperature

72:22

in Fahrenheit

72:25

is our temp

72:27

variable degrees

72:29

Fahrenheit. Let's test this if

72:33

statement. Is the temperature in Celsius

72:36

or Fahrenheit? It is currently in

72:38

Celsius. What is 33° in Celsius

72:42

converted to

72:43

Fahrenheit? The temperature in

72:45

Fahrenheit is 91.4°.

72:48

All right, so this section is working.

72:50

Let's work on the else statement. Else,

72:53

if our unit is currently in Fahrenheit,

72:55

we'll convert to

72:58

Celsius. That formula is temp

73:02

equals our temperature minus 32

73:06

* 5 /

73:09

9. Then I will round the result to one

73:13

decimal place.

73:18

Then we'll print the temperature in

73:21

Celsius. The temperature in Celsius is

73:26

temp° C for

73:29

Celsius. Is the temperature in Celsius

73:31

or Fahrenheit? It is currently in

73:35

Fahrenheit. Enter the temperature.

73:40

91.4. The temperature in Celsius is

73:43

33.0°.

73:46

Well everybody that is a simple

73:47

temperature conversion program in

73:57

Python. All right people, we're talking

73:59

about logical operators today. Logical

74:02

operators allow us to evaluate multiple

74:04

conditions. We can link them together.

74:06

There's three we'll discuss or and not.

74:11

We'll begin with or. With or we can

74:13

check more than one condition. If at

74:16

least one of those conditions is true,

74:18

then the entire statement is true.

74:20

Here's an example. Let's say we have an

74:22

outdoor event. And I will create two

74:25

variables. One temp, meaning

74:27

temperature. Let's say that this is in

74:30

Celsius, 25° C. Pick Fahrenheit if you

74:33

would like. And I will create a boolean

74:36

variable of is raining. I will set that

74:39

to be false. It is currently not

74:41

raining. If the temperature is too hot,

74:44

too cold, or it's raining, then I will

74:48

cancel this outdoor event. We'll write

74:50

an if statement to check that. If our

74:53

temp short for temperature is greater

74:56

than let's say 35 35° C then I'll use

75:01

the or logical operator or if our temp

75:05

is less than

75:07

zero or if is raining is

75:12

true. If one of these conditions is

75:15

true, we're going to cancel our outdoor

75:18

event. So let's print the following. The

75:22

outdoor event is

75:27

cancelled. Else we will print something

75:31

else. The outdoor

75:34

event is still

75:39

scheduled. The temperature is reasonable

75:42

and is raining is false. It's not

75:46

raining. So we print the else clause.

75:49

The outdoor event is still scheduled.

75:52

What if the temperature was really hot,

75:54

like

75:58

36°? Well, the outdoor event is

76:00

cancelled. What if it's cold?

76:05

-5°. The outdoor event is canled. This

76:08

condition was true. Therefore, we

76:10

execute the if statement. Or what if the

76:13

temperature is reasonable, but it's

76:15

raining? Is raining is true.

76:18

Well, then the outdoor event is still

76:20

canled. So with the or logical operator,

76:24

at least one of these conditions needs

76:26

to be true. If one of these conditions

76:28

is true, you could consider the entire

76:30

statement

76:31

true. Now let's cover and. With and, we

76:35

can link two conditions together. Both

76:37

conditions must be true in order for

76:40

that entire statement to be true. So

76:42

again let's say we have temp short for

76:45

temperature and we have a boolean

76:47

variable of is sunny. I will set that to

76:50

be

76:51

true. We will check if our temp is

76:55

greater than or equal to

76:59

28° and is it sunny. Is

77:04

sunny if it's hot and if it's sunny. If

77:08

this is true, let's print the

77:11

following. It is hot

77:14

outside. For fun, I'm going to add an

77:17

emoji, but you don't have to. I just

77:20

think it's more entertaining that way,

77:21

but you do you. And I will

77:26

print it is

77:30

sunny. Sometimes these emojis are

77:33

formatted differently. I'm just going to

77:34

copy it from somewhere else. That's

77:36

better. Currently, the temperature is 25

77:39

25° C and it's sunny. This condition was

77:42

false, but this one is true. With the

77:45

and logical operator, both conditions

77:48

must be true in order for us to execute

77:50

this block of code. If our temperature

77:53

was

77:55

30°, well, then both conditions are

77:58

true. It is hot outside and it is sunny.

78:02

Let's write a few more. Let's add else

78:05

if. Else if the temp is less than or

78:10

equal to

78:11

zero and is

78:14

sunny. We will print something

78:16

else. It is cold

78:20

outside. I'll change the

78:23

emoji and it is

78:25

sunny. Let's set the temperature to

78:28

be5°.

78:31

It is cold outside and it is

78:34

sunny. Both these conditions are true.

78:37

So we do this

78:38

instead. You can link as many conditions

78:40

together as you would like. Let's see if

78:43

our temperature is within a certain

78:45

range. Else if temp is less than 28 and

78:51

our temp is greater than zero and is

78:58

sunny. to check to see if something is

79:00

within a certain range. There is a

79:02

shortcut too. PyCharm is recommending

79:04

this. We can simplify chain

79:07

comparisons. So this effectively does

79:09

the same thing. If 28 is greater than

79:12

our temp and our temp is greater than

79:15

zero and it's sunny, then we will print

79:19

it is warm outside rather than

79:27

hot. and it's still sunny. So, let's say

79:30

our temperature is 20° C and it's

79:34

sunny. It is warm outside and it is

79:38

sunny. Now, we have the not logical

79:41

operator. It inverts the condition. We

79:44

are checking to see if something is

79:45

either not false or not true. So, let's

79:49

check to see if it's not sunny. Really,

79:52

I'll just copy what we have and paste

79:54

it.

79:58

else if not is

80:03

sunny then that means it's

80:12

cloudy and let's use a cloud

80:19

emoji. So basically not does the

80:21

opposite of what you're looking for. We

80:23

are checking if not is sunny. Is sunny

80:26

is false. Then this condition is true.

80:30

Okay. Let's say our temp is

80:33

28. Is sunny is now

80:37

false. It is hot outside. It is cloudy.

80:41

What if our temperature was

80:45

zero? It is cold outside. It is cloudy.

80:48

What if the temperature was reasonable

80:50

like 20°?

80:53

It is warm outside. It is cloudy. So not

80:56

it inverts the condition. If it's true,

80:59

it's now false. If it's false, it's now

81:02

true. All right, everybody. So those are

81:04

logical operators. They allow us to

81:06

evaluate multiple conditions. With or,

81:10

at least one condition must be true.

81:12

With and, both conditions must be true.

81:14

And not. Not does the opposite. It

81:17

inverts the condition. We check if

81:20

something is not false or not true. And

81:23

well everybody, those are logical

81:24

operators in

81:27

Python. Hey everybody. So today I got to

81:30

explain conditional expressions in

81:32

Python. A conditional expression is a

81:35

oneline shortcut for using an if else

81:38

statement. If you're familiar with other

81:40

programming languages, this is also

81:41

known as the trinary operator. It

81:44

behaves similarly. Using conditional

81:46

expressions, we can print or assign one

81:49

of two values based on a condition.

81:51

Here's the formula. Return X if our

81:54

condition is true. Else return Y. Here's

81:57

a basic example. We will create a

82:00

variable for number just num. Let's say

82:03

our number is five. I'm going to print.

82:06

Then within our print statement, I will

82:08

write a conditional expression following

82:10

this formula. I'll just copy and paste

82:12

it. Let's check to see if our number is

82:16

positive. Let's print the text positive

82:20

if our condition. What are we checking?

82:23

Let's check to see if num is greater

82:26

than zero. That means it's positive. If

82:29

this condition is false, we will instead

82:32

print whatever comes after else.

82:35

Else negative number is five, that will

82:39

print positive. If our number was neg 5,

82:42

well, this condition would be false. We

82:44

would instead print negative. Let's go

82:47

over another. Let's check to see if our

82:50

number is even or odd. Let's set num to

82:54

be

82:55

six. This time I will assign the result

82:57

to a variable. Our result

83:01

equals take our

83:04

formula. Let's

83:06

assign even

83:09

if our

83:11

num modulus 2 is our number divisible by

83:16

two. Does that equal zero? Else return

83:20

odd. Then let's print our

83:23

result. R

83:27

result number is six that is even. If

83:30

it's five then it's odd.

83:33

assign even if our number is divisible

83:36

by two. Else return

83:40

odd. Let's create variables A and

83:45

B. A will equal 6. B will equal

83:50

7. Let's create a variable of max num

83:55

equals. Follow our formula again.

84:00

return variable a if a is greater than b

84:05

else return b between a and b which is

84:08

the maximum number that would be b of

84:12

seven let's find the minimum this

84:16

time min num a if a is less than b else

84:23

return b the minimum number between 6

84:26

and 7 is

84:31

This time we'll take an age. Age equals

84:34

25. We will create a variable of status

84:37

equals. Use our formula

84:40

again. Return a string of adult. If our

84:46

age is greater than or equal to 18. Else

84:49

return a string of child. Then we will

84:53

print our status. Our age is 25. that's

84:56

greater than or equal to 18, we will

84:58

print adult. If our age was 13, then we

85:02

are a child. We will instead return

85:06

child. Let's work with the

85:08

temperature. Temperature equals 30°

85:13

C. So that's

85:15

hot. Let's create a variable of weather.

85:19

assign a string of hot if our

85:23

temperature is greater than 20. Else we

85:27

will return a string of cold. What's the

85:30

weather outside today? Based on the

85:32

temperature it is hot. If our

85:35

temperature was

85:37

20 then the weather is cold. Okay, last

85:42

example. We will work with a user role.

85:46

I will set this to be admin.

85:51

We will define a variable of access

85:53

level

85:55

equals again follow our

86:00

formula return the text of full access

86:05

if our condition of user ro is equal to

86:11

a string of admin else we will

86:15

return limited

86:19

access. Our user role is an admin. Let's

86:22

print our access level and we have full

86:25

access. But what if we were a

86:27

guest? Well, then we have limited

86:30

access. All right, everybody. Those are

86:32

conditional expressions. They're a

86:34

oneline shortcut for the if else

86:37

statement. It's similar to the turnary

86:39

operator in other programming languages.

86:41

Using conditional expressions, we can

86:44

print or assign one of two values. based

86:47

on a condition, you follow the formula

86:49

of return x if our condition is true,

86:53

else return y if it's false. And well

86:56

everybody, those are a few examples of

86:58

conditional expressions in

87:02

Python. Hey everybody, in this topic I'm

87:04

going to cover a few useful string

87:06

methods that you may be interested in.

87:08

Then at the end of this video, we will

87:10

work on an exercise where we will

87:12

validate some user input. As we know a

87:14

string is just a series of characters.

87:17

Let's ask a user for their full name.

87:20

Name equals

87:22

input enter your full

87:29

name. The first method I'll show you

87:31

well technically this is a function. The

87:33

length function will give us the length

87:36

of a string. How many characters is it?

87:38

we will find the length of our variable

87:41

name after the user types in some input.

87:44

This function returns an integer. I'll

87:46

store that result within a variable. Uh

87:49

let's just say result. Then I will print

87:52

whatever the result

87:55

is. Why don't you go ahead and type in

87:57

your full

88:00

name. The length of this string in my

88:03

example is eight characters. That does

88:06

include spaces too. 1 2 3 4 5 6 7 8. If

88:11

you ever need the length of a string,

88:13

there is the length function. Let's move

88:15

on. If we were to type our variable name

88:18

followed by a dot, we have access to a

88:21

whole bunch of different methods. We

88:23

have the find method. The find method

88:26

will return the first occurrence of a

88:29

given character, the position. Let's

88:31

find any spaces.

88:34

I'll store the result within a variable

88:36

named

88:39

result. I will type in my full

88:43

name. The first occurrence of a space,

88:46

that's what we set, is at position

88:48

three. When working with indexes, we

88:50

always begin with zero. This first

88:52

character would have an index of zero,

88:55

then 1 2 3. That's why the find method

88:58

returned three in place of four. Let's

89:00

find the first occurrence of a capital

89:05

B. See, it's zero. How about

89:12

O? For me, that would be two. So

89:15

remember, it's always the first

89:17

occurrence. If you need the last

89:19

occurrence, there is a different

89:22

method, which is R find. R meaning

89:26

reverse. We will find the last

89:28

occurrence of an

89:33

O that has a position of five. 0 1 2 3 4

89:39

5. If Python isn't able to locate a

89:42

given character, it will return negative

89:44

1. Let's find any I don't know uh

89:52

Q's. Python could not find any lowercase

89:55

Q's. The rfind method will return

89:57

negative 1 if there are no results. We

90:00

can capitalize the first letter in a

90:02

string by using the capitalize function.

90:05

Name dot

90:10

capitalize. This method will return a

90:12

string. I will reassign that to

90:15

name. Then we will print our name

90:18

capitalized.

90:20

I'll be sure to type in my name, all

90:23

lowercase. Since this is all one string,

90:26

only the first letter is capitalized,

90:29

even though I'm including a first and

90:31

last name. The upper method will take

90:33

all of the characters in a string. Then

90:36

make them all

90:37

uppercase. Follow your variable that

90:39

contains a string followed

90:42

byupper. Then I will reassign the result

90:45

to my name variable to overwrite it.

90:48

Enter your full

90:50

name. All of the letters are now

90:53

uppercase. There is also lower to make

90:56

all of the characters

90:57

lowerase. Name equals name dot

91:05

lower. Yep. All the characters are

91:07

lowercase. Now the is digit method will

91:11

return either true or false. If a string

91:14

contains only digits, the result is a

91:17

boolean, true or false. I'll store that

91:20

within a variable named result, then

91:22

print

91:24

result. So if I were to type in my full

91:27

name, is digit returns false. There are

91:31

not only digits within that string. If

91:34

my string was some combination of

91:36

alphabetical characters and numbers,

91:39

this method will still return false. It

91:41

only returns true if my string only

91:44

contains

91:45

digits. I'll just type in 1 2 3. See

91:49

that's true. That is the isdigit

91:52

method. Otherwise, we have is alpha name

91:58

is

91:59

alpha. The is alpha method will return a

92:02

boolean true or false depending if a

92:05

string contains only alphabetical

92:08

characters. I'll type in my full name.

92:11

So, the reason that this came up false

92:12

is because my full name contains a

92:15

space, which is not an alphabetical

92:19

character. If I typed in my full name

92:22

excluding any spaces, this would now be

92:24

true. Is alpha would also return false

92:27

if my name contained any sort of digits.

92:30

Bro 1 2 3. And that is also

92:32

false. That is the is alpha method.

92:37

Now let's ask for a phone

92:40

number. Phone number equals

92:46

input. Enter your phone

92:50

number. With the phone number, they

92:52

typically contain dashes. Let's count

92:54

how many dashes are going to be in

92:56

somebody's phone

92:58

number. Phone

93:01

number

93:02

dot count method. Let's count the amount

93:05

of dashes. So, place a character within

93:09

the count method. This method will

93:11

return an integer. Let's store that

93:13

within a variable. Result equals phone

93:17

number.

93:18

Method. So, type in some phone

93:21

number. 1-23

93:25

4-56-

93:28

8901. We have three dashes within the

93:30

string. 1 2 3. That is the count method.

93:35

We can count how many characters are

93:37

within a

93:39

string. We also have the replace method.

93:42

Honestly, the replace method is probably

93:44

one of the most useful methods of

93:46

strings. We can replace any occurrence

93:48

with one character with another.

93:51

Replace. Let's replace any

93:53

dashes with maybe a space. This method

93:58

will return a new string. I'm going to

94:00

reassign this to our phone number

94:02

variable.

94:04

Then print the phone

94:05

number. Enter your phone number.

94:12

1-234-567-8901. So, here's my new phone

94:14

number, but we've replaced all of the

94:16

dashes with spaces. Even better yet, we

94:19

could eliminate all the dashes

94:21

completely by replacing the dashes or

94:24

another character with an empty string.

94:33

1-234-567-8901. Here's our new phone

94:35

number without any dashes. We've

94:37

replaced all dashes with an empty

94:39

string, no characters. If you would like

94:42

a comprehensive list of all of the

94:43

string methods available to you, you can

94:46

use the help function. Type in the data

94:48

type string string. Then I will print

94:51

whatever the result

94:54

is.

94:57

Here's a bunch of methods you might be

95:00

interested in in the future. Capitalize,

95:02

case, fold, center, count, encode, ends

95:06

with, just to name a few. All right,

95:09

everybody. Here's an exercise for you.

95:11

We will validate some user input. We

95:14

would like a user to enter in a valid

95:17

username. However, there's a couple of

95:19

rules. The username can be no more than

95:22

12 characters long. The username must

95:25

not contain any spaces and the username

95:29

must not contain any

95:31

digits. Let's assign a variable named

95:34

username equals

95:37

input. Enter a user

95:42

name. First, let's check to see if our

95:45

user input is more than 12 characters

95:47

long. We can do that using the length

95:50

function. we will find the length of our

95:54

username. The length function returns an

95:56

integer. Let's check to see if the

96:00

length of our username is greater than

96:02

12 characters. If it is, we'll print a

96:07

message. Your

96:10

username can't be more than 12

96:14

characters.

96:18

else we will print using an

96:22

fstring welcome whatever our username

96:25

variable

96:27

is. Let's try it. I'll type in my first

96:31

name, last name, then add a whole bunch

96:34

of characters

96:36

afterwards. Your username can't be more

96:38

than 12

96:40

characters. Let's type in something

96:42

that's under 12

96:45

characters. Yep. And that appears to

96:47

work. Okay, so we have accomplished task

96:50

number one. Our username can't be more

96:53

than 12 characters. Next, our username

96:56

must not contain any

97:00

spaces. We can use the find method of a

97:03

string.

97:05

Username.find. We will find any spaces.

97:08

That's a character. If no spaces are

97:11

found, this method will return -1.

97:15

Using an else if

97:18

statement I'll add not if the find

97:22

method of

97:26

username

97:29

equals1. If the result is not -1 meaning

97:34

we found a space we will print your

97:39

username can't contain

97:44

spaces. I'll type in my first and last

97:47

name. You might need to think of

97:49

something that's underneath 12

97:52

characters. Your username can't contain

97:54

spaces. So, we have accomplished rule

97:57

number two. Three. Username must not

98:00

contain

98:01

digits. We can use the is alpha method

98:04

of

98:05

strings. The is alpha method returns a

98:08

boolean if a string only contains

98:10

alphabetical characters. So, let's copy

98:14

that. I'll add another else if statement

98:17

not username is

98:22

alpha. Then we will

98:25

print your

98:28

username

98:30

can't contain numbers. I guess

98:34

technically is alpha would check for

98:36

spaces too, but I'd rather have that be

98:38

handled within a different if statement.

98:42

All right, I'll type in a username. I'll

98:46

include some

98:47

digits. Your username can't contain

98:50

numbers. All right, I think we've

98:52

accomplished this. Let me make up a

98:55

username following these three rules.

98:59

Yep, it seems to check out. All right,

99:01

everybody. And that is a few useful

99:03

string methods that you may be

99:05

interested

99:07

in. Hey everybody. In this topic, I'm

99:10

going to explain string indexing.

99:12

Indexing allows us to access the

99:15

elements of a sequence using a set of

99:17

square brackets, also known as the

99:19

indexing operator. Using this set of

99:22

square brackets, following a string,

99:24

there are up to three fields that we can

99:26

fill in. We can access a starting point

99:29

in the string, an ending point, and a

99:32

step. Here's an example. Suppose we have

99:34

a credit card number.

99:36

credit number equals and I'll just make

99:40

up some number 1 2 3

99:45

4-5678-9012 dash 3456. Good enough. If I

99:50

need the first character within the

99:52

string, I can type the name of my string

99:55

variable followed by the indexing

99:57

operator which is a set of square

99:59

brackets. The first position has an

100:01

index of zero. Computers always start

100:03

with zero. So that's why the first index

100:06

is zero. Then I'm going to go ahead and

100:07

print this. Print credit card number at

100:11

index of

100:12

zero. That would be one. If I were to

100:15

change the index to be one, 0 1, that

100:19

should be two. Index

100:22

two would technically be

100:25

three. Then four is the dash within our

100:28

string. As you can see here with the

100:30

indexing operator, there's up to three

100:33

fields that we can fill in a start, end,

100:35

and a step. If you have just one field

100:38

listed without any colons, it's assumed

100:40

you're filling in the starting position.

100:43

So now, what if you would like the first

100:45

four digits of the

100:47

string? Well, we would type the name of

100:49

our string

100:51

variable indexing operator.

100:54

We'll need a starting

100:56

index colon then an ending index. The

101:00

first four digits would be zero colon 4.

101:06

Then I will print

101:09

this. And I'm just going to turn this

101:11

first line into a

101:13

comment. Yeah, there we go. We have the

101:15

first four digits of our credit card

101:16

number. 1 2 3 4. Just so you know, with

101:19

the ending index, this index is

101:22

exclusive. This first number would be

101:25

zero 1 2 3 4. So we did not include that

101:29

dash within the number. The starting

101:31

index is inclusive. The ending index is

101:34

exclusive. So you can omit the zero in

101:37

the beginning. You could just say colon

101:40

4. Python assumes the starting position

101:42

will be the beginning of the string. So

101:45

that would work too. Let's get the next

101:48

set of digits.

101:49

5678 credit number indexing operator.

101:54

Let's find where the starting index

101:55

would be. 0 1 2 3 4 5 5 colon 6 7 8

102:05

9. Then we will print whatever is

102:11

here. The next set of digits is 5 6 7 8.

102:15

Maybe we need the last 12 digits. Well,

102:18

what we could do in that case, we will

102:20

take our string variable credit

102:23

number. Set the starting index to be

102:26

let's see 0 1 2 3 4

102:30

5 5 colon. If you need everything up to

102:34

the end of the string, you don't need to

102:36

list an ending index. Just be sure to

102:37

add that colon. Python then assumes you

102:40

need everything up to the end of the

102:42

string. So, I will print whatever we

102:45

have. Then we should have everything

102:47

besides the first four digits. Yep. 5 6

102:50

7 8 9 0 1 2 3 4 5

102:54

6. You could also use a negative

102:58

index. Credit number. If you need the

103:01

last character in a string, you would

103:02

set the index to be -1. Then I will

103:06

print

103:07

this. Print credit number at index of

103:11

-1. That would be

103:14

six. -2 is

103:18

five. -3 is

103:21

four. -4 is three. And then5 would be

103:25

that dash right here. Yeah, you can use

103:28

negative indexes too. Let's talk about

103:31

step. Using the step field, we can

103:33

access the characters in a string by a

103:35

given step. We can count by twos or we

103:38

can count by threes. So here's an

103:41

example. So let's take our credit

103:43

number. If we're not filling in these

103:45

starting or ending fields, but we need a

103:48

step, we would need two colons. Then

103:50

Python is assuming everything from the

103:52

beginning of the string to the end. Then

103:54

our step will be

103:56

two. This will print every second

103:59

character within our

104:00

string. Yeah, here we are. We have 1 3

104:04

dash 6 8 9 1 so on and so

104:11

forth. If I were to change the step to

104:14

three, we would count every third

104:16

character beginning with 1

104:20

4 6

104:23

dash 1

104:25

36. All right, here's a practical

104:27

example. Let's create a program to get

104:30

the last four digits of a credit card

104:33

number. I'm going to assign this to a

104:36

new

104:37

variable.

104:40

Last digits equals our credit

104:46

number indexing operator. So, we need

104:49

the last four digits. Where would the

104:51

starting index begin? Well, we could use

104:54

negative indexing. This last digit is

104:56

-1, -2, -3,4. We will begin at

105:02

-4 colon. We can omit the ending index.

105:06

Python assumes we need the rest of the

105:08

string. Then really, that's all we need.

105:10

So, let's

105:12

print. I'll use an

105:15

fstring. Uh maybe some x's. Maybe we're

105:18

hiding somebody's credit card number

105:19

except the last four

105:22

digits. Okay. then variable

105:26

last

105:29

digits. All right. And here's our credit

105:31

card number where only the last four

105:34

digits are visible. Hey, you know what?

105:36

Let's add one more exercise. Let's

105:39

reverse the characters in the string.

105:41

I'm going to reassign credit

105:44

number equals credit

105:47

number. If we need the entire string, we

105:50

don't necessarily need a starting index

105:53

or an ending index. But for the step,

105:56

this will be negative. Negative -1 will

105:59

reverse a string. Then let's print

106:01

whatever our new credit card number

106:03

is. Print credit

106:06

number. And yeah, there is our credit

106:09

number backwards. To reverse a string,

106:12

you set the step to be -1. So yeah,

106:15

everybody, that is string indexing in

106:17

Python. We can access elements of a

106:20

sequence using the indexing operator

106:22

which is a set of straight brackets. You

106:24

can list a starting position, ending

106:26

position and even a step if you need to

106:28

skip over characters. But yeah, that is

106:31

string indexing in

106:34

Python. Hey everybody, in this topic I'm

106:37

going to explain format specifiers.

106:39

Format specifiers when used in the

106:41

context of an string, they allow us to

106:44

format a value based on what flags are

106:46

inserted. Following your value, you

106:49

would type a colon and then some flags.

106:52

Depending on what flags you insert, it

106:54

will format your output a certain way.

106:57

You could add decimal point precision,

106:59

allocate space, zero pad values, left

107:03

justify, right justify, center align,

107:06

all sorts of things.

107:08

Let's have some practice. I'll create

107:10

three prices. Price

107:12

one, price

107:14

two, price three. Price one will be

107:20

3.14159. These values aren't in dollars

107:23

and cents yet, but they will

107:25

be. Price two will be

107:30

987.65. As you can see, I'm just making

107:32

up numbers here. Price three is

107:37

12.34. Let's display our prices using

107:39

some

107:41

fstrings. Price one is placeholder price

107:47

1. Then we will do this for price two

107:50

and price three. Price two is price two.

107:54

Price three is price three. Within our

107:57

placeholder following the value, we can

108:00

add a colon. Then some flags. Those

108:03

flags are the format specifiers. They

108:06

will format our value a particular way

108:08

depending on what we insert after the

108:10

colon. To add decimal point precision,

108:14

you would type after the colon dot then

108:18

the amount of decimals to be displayed

108:20

maybe two then f meaning floatingoint

108:23

number. Let's do that with price two and

108:25

price three

108:29

colon.2f. Price one is now 3.14. Price 2

108:35

is987.65. Price three is

108:38

12.34. I think I'm going to add some

108:40

dollar signs before the

108:42

placeholder. Yeah, that's much better.

108:45

For less precision, maybe one decimal

108:47

place, you can change the two to a one.

108:51

So.1

108:53

F. Each number only displays one

108:56

decimal. 0.1

108:59

6.3 whereas in 3F would display three

109:02

decimal

109:05

places.142

109:07

650.340 even though price 2 and price 3

109:10

only have two decimal places in the

109:12

original numbers we will concatenate

109:14

some additional zeros to allocate space

109:17

to display a value after the colon add

109:20

some number some number for that many

109:22

spaces how about

109:29

10. Each value now has a total of 10

109:32

spaces to display the output. 1 2 3 4 5

109:36

6 7 8 9

109:39

10. If you were to preede a number with

109:42

zero, well, these numbers would be zero

109:47

padded. Each number is now zero padded.

109:50

To left justify a value, you would use a

109:53

left angle

109:58

bracket. All these numbers are now left

110:00

justified. Then we have all of the space

110:03

after. They're all uniform. Right

110:06

justify would be a right angle

110:11

bracket. And I believe that's the

110:14

default. Center align I believe is the

110:17

carrot symbol.

110:22

Yep, our numbers are now

110:24

centered. If you have any positive

110:26

values and you would like to display a

110:29

plus sign, just use

110:36

plus. Any positive number is preceded

110:39

with a plus sign. Any negative number is

110:41

preceded with the negative sign. Or you

110:43

could use a space for any positive

110:45

numbers. So, colon space

110:49

These numbers are lined up evenly even

110:51

though we have a negative number in

110:53

here. There is a thousand separator

110:55

which is a

110:58

comma. We should probably increase the

111:00

value of our

111:01

prices.

111:03

3,00

111:05

9,870

111:08

1,200. Each thousand's place is now

111:10

separated with a comma. We could also

111:13

mix and match flags. I would like a

111:15

thousand separator along with decimal

111:19

point precision of two decimal

111:23

places. And why not? I will preede each

111:26

number with a plus sign if it's

111:31

positive. Yep, here we are. So based on

111:35

what you're looking for, you can add

111:36

some combination of flags. So yeah,

111:39

those are format specifiers. everybody.

111:41

Within your

111:42

placeholder, insert your value, a colon,

111:46

then certain flags based on what you're

111:48

looking for

111:49

exactly. But yeah, those are just a few

111:51

format specifiers in

111:55

Python. Hey everybody, in this topic,

111:57

I'm going to explain while loops. A

111:59

while loop will execute some code while

112:02

some condition remains true. Here's an

112:04

example. We'll use an if statement

112:06

first. We will ask a user for their

112:08

name. name equals

112:10

input. Enter your

112:14

name. If our name is equal to an empty

112:18

string, that means the user didn't type

112:20

in anything. Let's print a

112:23

message. You did not enter your name.

112:29

Else, we will

112:31

print using an string,

112:35

hello, our user's name.

112:39

If I were to skip this

112:41

prompt, we would execute this if

112:43

statement. Then we continue with the

112:45

rest of the program. What if I would

112:47

like to continually prompt the user to

112:49

type in their name? We can't continue

112:51

until they type in something. Well, we

112:53

could replace this if statement with a

112:55

while

112:56

loop. While this condition is true,

113:00

continue to execute this code. within

113:03

the while loop. I'm going to reprompt

113:05

the user to type in a

113:07

name. Then if we were to exit the while

113:10

loop, then we will print hello. Whatever

113:13

your name is. So let's run this. Enter

113:17

your name. I'm going to hit enter. You

113:18

did not enter your name. Enter your

113:20

name. No. No. No. Okay, I give up. I'll

113:24

type in my first name. Hit enter. Hello.

113:26

Whatever your first name is. while this

113:29

condition remains true, execute this

113:32

code potentially forever until this

113:35

condition is no longer true. So that's

113:37

one of the main benefits of a while

113:38

loop. If it's not true, then you exit

113:41

out of the while loop. And that's why

113:43

we're able to continue then print our

113:44

name. Hello name. You do want some way

113:47

to escape out of the while loop.

113:49

Otherwise, you'll run into what's known

113:50

as an infinite loop. So let's say while

113:54

name is equal to an empty string, we

113:57

will print you did not enter your

113:59

name. So I'm going to hit enter. So we

114:02

are stuck in an infinite loop. We can't

114:05

actually escape this loop. We didn't

114:07

give ourselves an exit

114:09

strategy. That's why previously we

114:11

reprompted the user to type in

114:13

something. We're giving them a chance to

114:14

escape. In a way, it kind of works like

114:17

an if statement, but instead of

114:18

executing some code once, it's

114:20

potentially infinite. Here's another

114:22

example. This time, let's ask for a

114:25

user's age. Age equals, and I will

114:29

convert the input to an

114:32

integer. Enter your

114:34

age. We'll need the user to type in a

114:37

positive number. While age is less than

114:44

zero, let's print a message to let the

114:47

user know that they can't do that.

114:50

age can't be negative. Then we need some

114:55

strategy to escape. Let's reprompt the

114:58

user to enter in their

115:01

age. Once they type in something that's

115:03

valid, we can escape out of the while

115:05

loop. So let's print using an fstring

115:10

you

115:11

are age years

115:15

old. So enter your age. I'm going to say

115:18

negative one. Age can't be negative.

115:23

-21 million. Okay, I give up. How about

115:26

21? You are 21 years old. So, that was

115:29

another example. While our age variable

115:32

is less than zero, repeat this code

115:34

forever. Let's go over example

115:37

three. I'm going to introduce some

115:39

logical operators. We will have the user

115:42

type in a food they like. food equals

115:47

input enter a food you like. But in

115:51

order to escape, they need to press Q to

115:55

quit. While food is equal to the letter

116:01

Q, continue this while loop. However,

116:05

I'm going to make one change. We want to

116:07

exit the while loop when they press Q.

116:11

So you could say while not food equals

116:14

Q. So within this while loop, let's

116:17

print the food that they stated that

116:19

they like. I'll use an F string. You

116:23

like your variable food. Then we will

116:27

prompt the user to enter in another food

116:29

that they like. Enter another food you

116:31

like. Q to

116:33

quit. Then once we escape the while

116:35

loop, we will print just

116:38

buy. Okay. Okay. Enter a food you like.

116:41

Q to quit. I like pizza. You like pizza.

116:45

I like sushi. You like sushi. I like

116:49

ramen. You like ramen. Okay, this

116:51

program is kind of lame. So, I'm going

116:53

to press Q to quit. And we escape the

116:55

wild loop. We have printed by. So, you

116:59

could do something while something is

117:01

not true by using the not logical

117:03

operator. All right, last example.

117:05

Example four. We will use the or logical

117:08

operator. We'll ask a user to type in a

117:11

number between 1 and

117:13

10. Let's say num equals

117:17

input enter a number between 1 through

117:24

10. Then I will type cast the input as

117:28

an integer.

117:32

While our number is less than one or our

117:38

number is greater than 10, let's

117:41

reprompt the user. Let's print using an

117:44

fstring our variable

117:47

num is not valid. Then we will reprompt

117:52

the

117:53

user. Enter a number between 1 and

117:56

10. Once we escape the while loop, then

117:59

we will print our number using an fring.

118:03

Your number is our variable

118:07

num. Enter a number between 1 through

118:10

10. 0. Zero is not valid. Negative

118:15

1 100. Nope. Uh five. Your number is

118:20

five. That's an example of how you can

118:22

add logical operators to wild loops.

118:25

while this condition is true or this

118:28

condition is true, execute this code

118:30

forever. All right, everybody. So, those

118:32

are while loops. A while loop will

118:34

execute some code while some condition

118:38

remains true. It's fairly useful for

118:40

verifying user input. If a user types in

118:43

some input that is not valid, you can

118:44

reprompt them. And there's many other

118:46

uses that we'll discuss in the future.

118:48

But yeah, those are while loops in

118:52

Python. Why hello everybody. In today's

118:55

video, we'll be creating a compound

118:57

interest calculator in Python. For those

118:59

that don't know, interest is a charge

119:01

for the privilege of borrowing money to

119:03

some individual or organization. When

119:06

you place money in a bank account, you

119:07

typically acrue interest. We'll create a

119:10

program to tell you what your new

119:11

balance will be after acrewing interest

119:14

for so many years. But the user is going

119:16

to decide the initial principle. That's

119:18

the investment, the rate of interest,

119:20

and the time in years that this balance

119:22

has been acrewing interest. So let's

119:24

begin. Let's declare three variables. A

119:27

principle, a rate, that is rate of

119:30

interest, and time. Time will be in

119:32

years. We've recently learned about

119:34

while loops. I would like to include

119:36

those within this program just so we get

119:38

the hang of using them. We will ask the

119:39

user to type in an initial principal

119:42

investment. We will continue to prompt

119:44

the user to type in a principle that's

119:46

above zero. Our condition will be while

119:49

principal is less than or equal to zero.

119:53

We will take our principal assign it

119:56

some user

119:58

input. Enter the principal

120:04

amount. Then we would like to type cast

120:06

our input as a floatingoint number.

120:11

If our user input principle is less than

120:14

or equal to zero, we need to inform the

120:20

user

120:21

principle can't be less than or equal to

120:29

zero. So I'm going to test my program by

120:32

printing the principal at the end. Just

120:36

temporarily enter the principal amount.

120:39

I can't type a negative number and

120:41

continue. What if my investment was

120:43

negative

120:44

$1,000? Principal can't be less than or

120:46

equal to zero. How about zero? Nope.

120:49

Can't do that either. Is a,000. Okay?

120:52

Yep. A,000 works. That is for the

120:55

principal. Let's copy this while loop.

120:58

Paste it. Replace principal with rate.

121:01

This is the rate of

121:03

interest. Enter

121:05

the interest rate.

121:09

interest rate can't be less than or

121:12

equal to

121:14

zero. Then let's copy this again. Paste

121:17

it. Change rate to

121:24

time. Let's type cast our input as an

121:27

integer because we're working with whole

121:29

years. Enter the time in years.

121:35

time can be less than or equal to

121:38

zero. I'm going to print my principal,

121:42

rate, and

121:45

time. We have

121:48

principal, rate,

121:51

time. Okay, we know that principle

121:55

works. Enter the interest rate. Can my

121:58

interest rate be -1? No, it can't. Can

122:01

it be zero? Nope. How about 10? 10%. All

122:05

right, that works. Time. Can time be

122:08

zero? No, it can't. Can my time be

122:10

negative 1? No, it can't. What about 3

122:13

years? All right, so we know that our

122:16

while loops are working. Now, here's the

122:18

formula to calculate interest.

122:21

Let's say our total, that's our total

122:24

balance equals our principal

122:29

times 1 + our rate divided by 100. I'm

122:34

going to enclose this function with the

122:36

set of

122:37

parenthesis. This portion of our

122:39

function will take our interest rate,

122:41

which is a whole number, then create a

122:42

decimal. Enclose this function within

122:45

the power function.

122:48

raise this function to the power of time

122:51

and that is how to calculate compound

122:54

interest then we will print the new

122:56

balance I'll use an

123:00

fstring balance after our variable

123:05

time the word

123:08

years I'll add a placeholder we will add

123:11

our

123:12

total then I'll include a dollar sign

123:15

maybe this will be in dollars but pick

123:17

any unit of currency you would like. I

123:19

will format this variable with the

123:21

format specifier. We will display two

123:23

decimal places 2F. Okay, let's try this.

123:28

Enter the principal amount. I invest

123:31

$1,000 into maybe the stock

123:33

market. The interest rate is maybe 10%

123:37

this year. The time in years will be 1.

123:41

So, after one year at 10% interest, my

123:44

new balance is

123:47

$1,100. Let's try it one more time for

123:49

good measure. Maybe $500 with an

123:51

interest rate of 7 over 2 years. Your

123:54

new balance would be

123:57

$57245. All right. Now, there is another

124:00

way of writing this program. What if we

124:02

would like to allow the user to enter in

124:04

values that are equal to zero while

124:07

principal is less than zero? If

124:10

principal is less than zero, principal

124:13

can't be less than zero. Let's do that

124:17

for

124:19

rate. Interest can't be less than

124:24

zero.

124:26

Time can't be less than zero. Here's

124:30

what happens to our program. Remember

124:32

that we're declaring our variables at

124:33

the

124:34

top. Uh nothing happens. We go straight

124:37

to the results. So the reason that this

124:40

is happening is that when we reach the

124:42

while loops, this condition is false

124:45

from the beginning. We never end up

124:47

entering these while loops. We skip over

124:49

them because these three conditions are

124:51

all false. We can write a different

124:54

variation of this while loop where we

124:56

could say while true. True is a boolean.

125:00

That means this while loop will continue

125:02

forever unless we explicitly break out

125:05

of the while loop. We're going to add an

125:07

else

125:08

clause. Else we will break. Break will

125:12

break out of a

125:14

loop. With our second while loop, change

125:17

rate is less than zero to while true.

125:20

Then we will add an else

125:22

clause. Else break out of the

125:25

loop. While

125:29

true.

125:31

Else break out of the loop. We should be

125:35

able to enter zero values in

125:37

now. Enter the principal amount. 0 0 0.

125:41

Balance after 0 years is

125:45

$0. This should work the same as before,

125:47

but we should be allowed to enter in

125:49

zero values.

125:52

$1,000. Interest rate of zero after one

125:55

year is still

125:57

$1,000. Well, okay then everybody. I

126:00

thought that would be an interesting

126:01

project to create now that we know how

126:03

while loops work. You could write either

126:05

a standard while loop with a condition

126:06

such as principle is less than or equal

126:10

to zero or you could say while true.

126:13

This loop would continue forever. You

126:15

would need to explicitly break out of

126:17

the while loop using this break keyword

126:20

which we'll cover again in four loops.

126:22

But yeah, that is a compound interest

126:24

calculator in Python.

126:28

Hey everybody, in this topic I need to

126:30

explain for loops. A for loop will

126:33

execute a block of code a fixed number

126:36

of times. You can iterate over a range,

126:39

a string, a sequence, anything that is

126:42

considered iterable. I'll have more

126:43

examples for you in future topics. There

126:46

is a lot of overlap where you could use

126:47

either a while loop or a for loop, but

126:50

for loops tend to be better in

126:51

situations where you have to do

126:52

something only a fixed number of times.

126:55

Here's an example. Suppose we need to

126:56

count to 10. If we were to use a for

126:59

loop, we could write something like

127:00

this. We would type four, then we would

127:03

need some sort of counter. Typically,

127:05

you see people write x. 4 x in, then we

127:11

will use the range function. What number

127:14

would we like to start at? I would like

127:16

to start at 1, then count to 10. But the

127:20

second number is exclusive. So really,

127:22

we're going to write 11 if we want to

127:24

count to 10.

127:26

So then colon then hit enter. Whatever

127:29

code you would like to repeat a certain

127:30

number of times you will list underneath

127:32

the for loop and make sure the code is

127:34

indented too. I will print whatever our

127:37

counter x is. When I run this code we

127:40

will begin at 1 then stop once we reach

127:44

11. So yeah there we are. We have begun

127:47

at one and we have counted all the way

127:49

to 10. So that's the basic syntax for a

127:51

for loop for some counter. Really, you

127:54

can name this anything. Sometimes you'll

127:55

see people name this as

127:57

counter and that would work too, but

128:00

let's stick with X in some range. Where

128:04

would we like to begin? Where do we

128:07

stop? Okay, now let's count backwards.

128:10

Let's start at 10, then count down to

128:12

zero. When we escape the for loop, let's

128:15

print happy new year.

128:20

When we print happy new year, we are

128:22

outside of the for loop. To count

128:24

backwards, you can enclose your range

128:26

function within the reversed

128:28

function

128:33

reversed. So we begin at 10, count down

128:36

to one, then print happy new year. In

128:39

this case, to count backwards, you would

128:41

enclose the range function within the

128:43

reversed function. There is an

128:45

additional parameter too you could add.

128:47

That is the step. If you would like to

128:49

count by twos, you would add comma

128:52

2. So I'm going to get rid of happy new

128:55

year. Let's print the numbers 1 through

128:58

10, but we will count by

129:00

twos. And this does begin at 1, though.

129:03

So 1 3 5 7 9. If you were to change the

129:07

step to three, you would count by threes

129:10

beginning at 1 4 7 10. So the range

129:14

function isn't the only thing you can

129:15

iterate over. You can iterate over a

129:17

string. Let's say we have a credit card

129:19

number. Credit card equals I'll make up

129:23

some credit card number with

129:28

dashes. That is good enough. For x in

129:33

credit card print x will hold our

129:36

current position. At first it'll be one

129:39

then 2 3 4 dash. So on and so forth. So

129:42

here's our credit card number. 1 2 3 4

129:46

dash 5 6 7 8. I think you get the idea.

129:49

So you can iterate over a string with a

129:51

for loop as well. We'll have a few

129:53

projects involving that. There are two

129:55

useful keywords as well. These aren't

129:57

exclusive to for loops. You can use

129:59

these within while loops as well. They

130:01

are continue and break. Suppose we going

130:04

to count to 20. For x in range, we will

130:08

begin at one, stop at 21. I think this

130:12

is kind of a dumb example, but it gets

130:14

the point across. 13 is considered an

130:16

unlucky number, right? What if our

130:18

counter reaches 13? I would like to skip

130:21

over it. Well, we can do that with the

130:23

continue

130:24

keyword. If x is equal to 13, we will

130:28

continue and skip over that

130:31

iteration. Else, we will print whatever

130:34

our counter is. So, let's take a look.

130:39

Yeah, we have the numbers 1 through 20,

130:41

but we have skipped the number 13. To

130:45

skip over an iteration, you can use the

130:47

continue keyword. Whereas the break

130:49

keyword, we will break out of this loop

130:52

entirely. If x is equal to 13, then

130:57

break. So yeah, we have only counted to

131:00

12. Once we reach 13, we have escaped

131:02

the loop. So yeah, everybody, those are

131:05

four loops. You can execute a block of

131:08

code a fixed number of times. You can

131:10

iterate over a range, a string, a

131:13

sequence, anything that is considered

131:15

iterable. There is a lot of overlap

131:17

where you could use either a while loop

131:19

or a for loop. While loops tend to be

131:21

better if you need to execute something

131:23

possibly infinite amount of times, such

131:26

as when you're accepting user input, for

131:27

example. But yeah, everybody, those are

131:30

for loops in

131:33

Python. What is going on everybody? In

131:36

today's topic, we're going to be

131:37

creating a countdown timer in Python.

131:40

We'll be using what we learned in the

131:41

previous topics. Let's begin. We'll need

131:44

to import the time module. There's a

131:47

pretty cool function within the time

131:48

module. That is the sleep function. Type

131:52

time do sleep. Add a set of parenthesis.

131:55

Within the set of parenthesis, our

131:58

program will essentially sleep for a

132:00

given amount of seconds, like three.

132:03

After three seconds, let's print

132:05

something. This is just a

132:08

demonstration. Times

132:12

up. When I execute this code, nothing

132:15

happens for 3 seconds, but after 3

132:17

seconds passes, it displays our message

132:20

times up. So, you can use the sleep

132:22

function of the time module to sleep for

132:24

a given amount of time. We will ask the

132:27

user how long would they like to set the

132:29

timer for. We will create a variable.

132:32

Let's say my time my time will be in

132:37

seconds. We will create a prompt. Enter

132:41

the time in

132:44

seconds. Then we should type cast our

132:46

input as an

132:50

integer. We'll need to create a loop. We

132:53

could use either a while loop or a for

132:55

loop. There's a lot of overlap where you

132:57

could use either one. I'll use a for

132:58

loop in this case. Four. We'll need some

133:01

sort of counter X in our

133:06

range zero

133:08

through my

133:12

time. After each iteration, we will

133:15

sleep for 1 second. Let's test what we

133:18

have so far. I would like to sleep for 3

133:24

seconds. I think that's approximately

133:27

three. But now we are going to print

133:29

whatever x is. Print x. x is our

133:35

counter. 0 1 2 times up. We're getting

133:41

somewhere. But I would like to count

133:43

backwards. What we could do is enclose

133:46

our range function within the reversed

133:51

function. But another technique that we

133:53

can use is by using a step.

133:56

Let's replace zero with my

133:59

time. Then end at zero. But we will set

134:03

the step to be - 1. Then we can

134:06

increment backwards using this function.

134:09

That's another technique too to count

134:11

backwards. So let's wait for 3 seconds.

134:14

3 2 1. Times up. Now let's display a

134:20

digital clock of some sort. But we would

134:22

have to calculate how many hours,

134:24

minutes, and seconds there are. So let's

134:26

calculate seconds. Seconds equals x. X

134:31

is our counter.

134:32

Remember modulus

134:35

60. Within our print statement, we'll

134:37

use an f string. We are displaying

134:40

hours, minutes, and seconds. I'll add

134:43

some placeholders for each of these

134:45

fields. We have seconds. With our

134:48

digital clock, we can't go above 60 for

134:51

either seconds or minutes. That's why

134:53

I'm using modulus 60. The modulus

134:55

operator gives you the remainder of any

134:57

division. Let's begin at 11. So 11 10 9.

135:03

So it is counting down, but I would like

135:05

to add some zero padding and we can do

135:08

that with the format

135:10

specifier. After seconds, I will add

135:12

colon. I need to display two digits.

135:16

Then zero pad those digits. Let's try

135:18

that again. I will wait for 11 seconds.

135:21

11 10 9. Yeah. And we do have some zero

135:25

padding. So that's looking more and more

135:28

like a digital clock. Let's add minutes

135:30

then. So to calculate minutes, let's

135:34

assign variable minutes equal to x / 60

135:40

because there's 60 seconds within a

135:42

minute. But then I'm going to type cast

135:44

the result as an

135:48

integer modulus 60. We would not like

135:52

this field of minutes to go above 60. So

135:55

let's add a placeholder. We're

135:58

displaying minutes. Format specifier

136:02

02. Now I'm going to wait for 65

136:06

seconds. That is 1 minute and 5

136:08

seconds. Then I just want to be sure

136:10

that we go below a minute.

136:13

Yep, it's working. Then let's calculate

136:16

hours. Oh, by the way, to stop your

136:18

program from running, hit this red

136:20

square up in the corner. Let's calculate

136:22

hours. Hours

136:25

equals x /

136:28

3,600. There's 3,600 seconds in an

136:32

hour. Then we will type cast the result

136:35

as an integer.

136:40

within our fing we will

136:42

display ours format specifier

136:47

02. Then I will run this program. Let's

136:50

wait for

136:51

3,65 seconds. That is 1 hour and 5

136:56

seconds. And I just want to be sure that

136:58

we go below 1 hour. Yeah. All right. So

137:02

that works.

137:04

So the reason that I didn't add modulus

137:06

24, I don't have days within my fing. We

137:10

can display any amount of hours. I will

137:13

exclude modulus

137:15

24. All right, everybody. Well, I

137:17

thought that'd be some good practice

137:18

with working with loops. We should try

137:20

and do as many exercises as we can. And

137:23

yeah, that is a countdown timer program

137:25

in

137:28

Python. Hey everybody. So I guess in

137:30

today's topic, I'm going to be

137:31

explaining nested loops. It looks like

137:33

so a nested loop, think of it as a loop

137:36

found within the code of another loop.

137:38

You have a loop, right? Any code within

137:41

that loop is indented underneath that

137:43

loop. Well, you could have a looping

137:45

structure found within the code of

137:47

another looping structure. The loop on

137:49

the outside is the outer loop. The

137:51

internal loop within the outer loop is

137:53

known as the inner loop. Where you'll

137:55

encounter nested loops, it's really

137:57

situational. You could have a while loop

138:00

inside of a while loop, a for loop

138:01

inside of a for loop, a for loop inside

138:03

of a while loop, a while loop inside of

138:04

a for loop, etc. So, here's a

138:07

demonstration. Let's begin by displaying

138:09

the numbers 1 through 9, but we'll use a

138:12

loop for x. X is our counter in

138:16

range 1, 10. Remember that the second

138:20

number in this case 10, that's

138:22

exclusive.

138:24

Then I will print our counter X. This

138:29

program will print the numbers one

138:31

through nine. Now we have an exercise at

138:34

the end of this topic. I should probably

138:35

explain this feature. So with a print

138:38

statement, we end each print statement

138:40

with a new line character. If I need all

138:42

of these numbers on the same line, at

138:45

the end of my print statement, I can add

138:47

comma end equals an empty string.

138:52

Normally with a print statement, each

138:54

ends with a new line character, but we

138:56

can set that to be something

138:58

else. So when I run this again, all of

139:00

these numbers are on the same line. Or

139:03

you could add a different symbol like

139:05

dash or a

139:07

space. Each of these characters is now

139:09

separated with a space. But let's stick

139:12

with an empty

139:13

string. Okay, so we have used a loop to

139:16

count the numbers 1 through nine. What

139:18

if I would like to repeat this three

139:21

times? Well, I could create another

139:24

loop for x in range. You could say 1, 4,

139:30

or you could just say three. Either

139:32

way, whatever code is within this loop

139:35

will be executed three times. Let's cut

139:38

our original for loop, then place it

139:41

within the code of our new loop. Our

139:44

outer loop will have this code repeat

139:47

entirely three separate times. Uh but we

139:50

do have one thing we need to pay

139:51

attention to. We have two counters with

139:54

the same name. You'll want to be sure

139:56

that they're different. Let's rename the

139:59

counter of the inner loop to be y

140:01

instead of x. And be sure to change that

140:03

here as

140:05

well. Now when I run this code, we're

140:07

completing let's see 27 iterations. To

140:11

exit this for loop, we need to count the

140:13

numbers 1 through nine. Once we do so,

140:16

that is one iteration of the outer loop.

140:19

But our outer loop is saying, "Hey, we

140:21

still need three total iterations." Now,

140:23

if you would like these on separate

140:25

lines, let's make this look a little

140:26

different. Let's add each iteration of

140:29

the outer loop onto a new

140:31

line. So, within the outer loop, but not

140:34

within the inner loop, I'm going to

140:37

create just a blank print statement.

140:39

This will just print a new line. Let's

140:41

try this

140:42

again. With the inner loop, we count the

140:44

numbers 1 through nine. After we exit

140:47

the for loop, we will print a new line.

140:50

Then repeat this all over again until

140:53

our outer loop is satisfied. So that's

140:55

basically a nested loop. It's just a

140:57

loop that's inside of another looping

140:59

structure. So let's create a project.

141:01

We're going to print a rectangle made of

141:03

some symbol that we set. We'll have the

141:05

user type in how many rows and columns

141:07

this rectangle will have. We'll reuse

141:09

this code that we have already written.

141:12

So this time let's accept some user

141:13

input. Rows equals

141:18

input. Enter the number of rows. Then we

141:23

should type cast this input as an

141:25

integer. Let's copy this line. Paste it.

141:30

Change rows to columns. For the second

141:32

line, enter the number

141:34

of

141:37

columns. Then let's create a symbol.

141:39

Symbol equals

141:43

input. Enter a symbol to

141:47

use. We already have this rectangle

141:50

structure, right? Think of it as the

141:52

outer loop is in charge of the rows.

141:55

Let's change in range three to in range

141:58

rows.

142:00

The inner loop will be in charge of the

142:02

columns. For y in

142:05

range

142:07

columns, we will print our symbol

142:10

whatever the user chooses. So let's try

142:12

this again. Enter the number of rows.

142:15

How about four

142:17

rows, 10 columns? I'll use a dollar

142:21

sign. So here's our rectangle.

142:25

We have four

142:27

rows, then 10 columns. 1 2 3 4 5 6 7 8 9

142:33

10. Let's try it one more

142:35

time. Three

142:37

rows, five columns, and I'll use an

142:41

asterisk. Yep, three

142:43

rows, five

142:45

columns. So, yeah, that's a nested loop.

142:48

Really, it's just a loop that's inside

142:49

of another loop. The type of loop really

142:52

doesn't matter as well as what's within

142:54

each loop. It's just a situation where

142:56

you have a loop inside of another loop.

142:58

And yeah, those are nested loops in

143:02

Python. Well, hello everybody. Today I

143:05

will be explaining a few different types

143:06

of collections in Python. There's four

143:09

general purpose collections. Three of

143:11

them are lists, sets, and tpples. There

143:14

are also dictionaries, but I'll save

143:16

that for the next topic because they can

143:18

be kind of tricky. A collection I would

143:20

think of them as a single variable and

143:23

I'm saying that within quotes that is

143:25

used to store multiple values. That's

143:28

how I would explain a collection to a

143:29

beginner. For example, let's say we have

143:31

a variable variable fruit. Fruit equals

143:35

some value like apple. And then I can

143:38

print this fruit which is apple. I could

143:42

turn this variable into a collection by

143:45

surrounding my values with either a set

143:47

of square brackets for a list, curly

143:49

braces for a set, or parenthesis for a

143:52

tuple. Let's begin with a list. If I

143:54

would like to store more than one value

143:56

in this variable, I will surround my

143:59

values with a set of square brackets.

144:01

This variable is now a list. I can store

144:04

multiple values separated with a comma.

144:07

Not only do we have an apple in this

144:08

variable, but we have an orange

144:11

a

144:13

banana and

144:15

coconut. One naming convention that I

144:18

like to use, if I declare a collection

144:20

such as a list, set or tpple, I like to

144:23

take the variable name and make it

144:24

plural just so that it's more obvious

144:26

that this is a collection of values.

144:29

Technically, in the English language,

144:31

fruit would still be plural. English is

144:33

a weird language. We now have a list of

144:36

fruit named fruits. If I were to print

144:39

my list, this is the result. We have all

144:43

of our values enclosed with a set of

144:45

square brackets. To access one of these

144:48

elements found within your list, you can

144:50

use the index operator, much like what

144:53

we can do with strings. The first

144:55

element would have an index of zero.

144:57

That would print my value

144:59

apple. Index of one would be my orange.

145:03

Two is banana. Three coconut. What about

145:08

four? We don't have a value

145:11

there. List index out of range. Each

145:14

value in a collection is also known as

145:17

an element. If we attempt to access an

145:19

element that's not found within our

145:21

collection, you'll run into an index

145:23

error. With the index operator, you

145:26

could set a beginning index, an ending

145:29

index, and a step. I would like the

145:31

first three elements. You could say zero

145:35

colon

145:36

three. That would give me apple, orange,

145:39

banana. Technically, you don't even need

145:41

the zero. You need that colon, though.

145:42

We can even use a step. I would like

145:45

every second

145:46

element, apple, banana. It's every

145:49

second element beginning from index

145:51

zero. Maybe I would like my fruit

145:53

backwards. I'll set the step to be

145:55

negative 1. Coconut, banana, orange,

145:57

apple. You can use the index operator

145:59

with collections much like you can use

146:01

with strings. Another cool thing you can

146:04

do too with collections is that you can

146:06

iterate over them with the for loop for

146:09

x in my collection

146:12

fruits. What would we like to do? I will

146:15

print whatever x

146:17

is. So we have iterated over our list.

146:21

Apple, orange, banana, coconut. Now x

146:23

isn't really too descriptive. What

146:25

you'll see some people do is that with

146:27

their collection name, it's plural,

146:29

their counter will be the singular

146:31

version of that word. If our collection

146:33

name is fruits, let's rename x as fruit.

146:38

Singular. It's not mandatory, but that's

146:40

a common convention. It's more readable

146:42

that way. For every fruit in fruits. If

146:46

this were cars, you could say for car in

146:49

cars. Our counter is storing whatever

146:52

value is within our collection. So what

146:54

are all the different methods that we

146:56

can use with collections? To list the

146:58

different methods that are available to

147:00

a collection, you can use the dur

147:03

function. Within this function, add your

147:06

collection

147:07

fruits. But we would need to print this.

147:10

Let's surround this function with a

147:12

print

147:14

statement. These are all in alphabetical

147:16

order. We have attributes, which I have

147:18

not explained yet, but I will in a

147:20

future topic. But if we scroll to the

147:22

end, we have a bunch of different

147:25

methods that this list can perform.

147:27

Append, clear, copy, count, extend,

147:29

index, insert, pop, remove, reverse, and

147:32

sort. If you would like a description of

147:34

each of these methods, there is a help

147:36

function. Help. Add your collection to

147:39

the parenthesis. Then we would need to

147:41

print

147:46

this. Here's the description of all the

147:49

methods and attributes. For example, we

147:51

have our sort method. And here's a

147:53

description. Sort the list in ascending

147:55

order and return none. And then a bunch

147:58

of other stuff. If you ever forget what

148:00

you're capable of with a list or other

148:01

collection, you can always use the help

148:03

function to print a description of the

148:06

attributes and methods available. If you

148:08

need the length of how many elements are

148:10

within a collection, there is the length

148:14

function. Return the length of my list

148:17

fruits. Then let's print it. There's

148:21

four elements within my list. The length

148:23

function returns four. If I were to add

148:26

an extra element like a

148:29

pineapple, then that number would be

148:32

five. Let's remove that. Using the in

148:36

operator, we can find if a value is

148:38

within a

148:39

collection. Is our value apple in

148:44

fruits?

148:46

But then we would need to print this.

148:48

This operator will return a boolean. So

148:50

let's print whatever that

148:52

is. Is apple in fruits? That is true.

148:57

But is

148:59

pineapple? Pineapple is not. It's false.

149:02

You can use the in operator to find if a

149:04

value is within a list. And that applies

149:06

for your other collections,

149:08

too. With lists, they're ordered and

149:11

changeable. Duplicates are okay. We can

149:14

change one of these values after we

149:16

create our list. Let's take fruits at

149:19

index of

149:21

zero. I will set this equal to be a

149:24

pineapple. Then let's iterate over our

149:29

fruit. Using a for

149:31

loop. Okay, the first element is no

149:34

longer an apple. It's a pineapple. Then

149:36

orange, banana, coconut. Using an index,

149:39

you can reassign one of the values. If I

149:41

were to change zero to one, well, now we

149:44

have an apple, pineapple, banana,

149:47

coconut. Let's cover some of the methods

149:50

that are found within a list. We can

149:52

append an element. Type the name of the

149:55

list dot append. What would we like to

149:58

append to the end of this list? Let's

150:00

append a

150:03

pineapple. I'm going to get rid of this

150:05

for loop. I'm just going to display my

150:06

list. There we have an apple, an orange,

150:09

banana, coconut, pineapple. To add an

150:11

element to the end of a list, use the

150:13

append

150:14

method. To remove an element, you can

150:17

use the remove method.

150:19

Fruits. Let's remove our

150:22

apple. Our apple is no longer there. We

150:25

have an orange, banana, coconut. Using

150:27

the insert method, we can insert a value

150:30

at a given

150:31

index. Fruits

150:34

do.insert list an index. Zero would be

150:37

the beginning. Then a value.

150:42

pineapple. Now we have a pineapple,

150:45

apple, orange, banana, coconut. The sort

150:48

method will sort a list. Fruits

150:51

do.sort. These are all in alphabetical

150:54

order now. Apple, banana, coconut,

150:57

orange. To reverse a list, you would use

151:00

the reverse method.

151:04

Fruits.reverse coconut, banana, orange,

151:07

apple. However, these are not in reverse

151:09

alphabetical order. These elements are

151:11

reversed based on the order in which we

151:13

place them. If you would like reverse

151:15

alphabetical order, you can first sort

151:18

and then

151:20

reverse. Now we have orange, coconut,

151:22

banana,

151:23

apple. To clear a list, use the clear

151:26

method.

151:28

Fruits. All of the elements are

151:32

gone. We can return the index of a

151:35

value. Let's return the index of

151:38

apple. Fruits do index list an

151:44

element. Then we will need to print

151:47

this. Let's print the index that is

151:52

returned. The index of apple is

151:55

zero.

151:57

Coconut that would be three. What if we

152:00

don't find a value like a pineapple?

152:05

Well, we have an error. Pineapple is not

152:07

in list. You could count the amount of

152:10

times that a value is found within a

152:12

list because duplicates are okay. Fruits

152:16

doc count. Let's count how many bananas

152:18

are in this list.

152:21

Banana. Then print

152:26

it. One banana is found within this

152:29

list. How about pineapples?

152:33

There are zero. Now those are lists.

152:36

Surround your values with a set of

152:38

square brackets. These values are

152:40

ordered and changeable. Duplicates are

152:43

okay. Now let's talk about the next

152:45

collection which is a set. To create a

152:47

set, surround your values instead with a

152:50

set of curly braces. Our collection of

152:52

fruits is now a set. A set has different

152:55

benefits. The values are unordered and

152:58

immutable, meaning we can't alter these

153:00

values. However, we can add and remove

153:03

elements. A set does not include any

153:05

duplicates. I'm going to delete these

153:08

methods, then print

153:10

fruits. We have all of the same values,

153:13

but they're not in the same order as

153:15

they were originally. A set is

153:17

unordered. If I were to run this again,

153:20

they will likely be in a different

153:21

order. See, now we have a banana, apple,

153:24

coconut, orange. To display all of the

153:26

different attributes and methods of a

153:28

set, you can use the dur

153:33

function. And here's all of them. Some

153:36

of these methods are a little more

153:37

advanced, but there's a few we might

153:38

recognize, like add, clear, copy. For an

153:42

in-depth description of these methods,

153:43

you can use the help

153:46

function. Much like what we did before,

153:49

to find the length of our set, we can

153:51

use the length function, which is

153:54

four. We can use the in operator to find

153:57

if a value is found within this set.

154:00

Unfortunately, pineapples are not within

154:02

our set. Now, if I was to use the index

154:05

operator of my set, this is what would

154:10

happen. We have an error. Set object is

154:13

not subscriptable. We're not able to use

154:15

indexing on a set because they're

154:17

unordered, much like what we can do with

154:19

a list or a string. We can't change the

154:22

values of a set, but we could add or

154:24

remove

154:25

elements. Let's use the add method to

154:28

add guess what? A

154:32

pineapple. That is okay. Orange, apple,

154:35

pineapple, coconut,

154:37

banana. We can remove an element fruits.

154:42

Let's remove our

154:44

apple. Our apple is gone. Coconut,

154:47

orange,

154:49

banana. We can

154:53

pop. The pop method will remove whatever

154:56

element is first. But it's going to be

154:58

random

154:59

though. Orange, coconut, banana, apple,

155:02

coconut,

155:04

banana, apple, banana,

155:07

coconut. You can clear fruit.

155:12

The elements of our set are gone. Those

155:14

are a few of the more useful methods for

155:16

beginners. As a summary, a set is a

155:19

collection that is unordered and

155:21

immutable. You can't change the values,

155:23

but adding and removing elements is

155:25

okay. No duplicates are allowed. Let's

155:28

try that real quick. I'm going to add a

155:29

second

155:32

coconut. Yeah, see, we only still have

155:34

one coconut. Sets may work well if

155:37

you're working with constants. Maybe

155:39

colors for example. You need to find if

155:41

a color is within a set. All right. Now

155:44

lastly, let's talk about tpples. A tpple

155:46

is a collection that is surrounded with

155:48

a set of

155:49

parenthesis. Tpples are ordered and

155:52

unchangeable. Duplicates are okay. One

155:55

benefit of a tpple over a list is that

155:58

tpples are faster than lists. If you're

156:00

working with a collection, and it's okay

156:02

if the collection is ordered and

156:03

unchangeable, you might as well use a

156:05

tpple because it's faster. When I print

156:07

our tpple, all of these values are

156:09

surrounded with a set of parenthesis.

156:12

Again, we have the dur function to

156:13

display the attributes and methods.

156:16

There's not as many for a tpple. For

156:17

methods, we only have count and index.

156:20

Again, there's also

156:22

help to display a description of these

156:25

attributes and methods. You can find the

156:28

length of a tpple with the length

156:29

function. We have five elements within

156:32

here. Using the in operator, we can find

156:34

if a value is found within our

156:37

tpple. Our pineapple is not within our

156:40

fruits. So there's only two methods we

156:42

have access to. Let's find the index of

156:45

apple.

156:47

Fruits.index apple. Then I will print

156:50

whatever is

156:53

returned. Apple is found at index zero.

156:56

There is also count

156:59

fruits.ount how many coconuts are found

157:02

within our tpple

157:04

fruits. Count the coconuts. Then print

157:09

this. How many coconuts? We have two

157:13

coconuts. And then again with any of

157:15

these collections, they're iterable. So

157:17

you can iterate over them using a for

157:19

loop. Four fruit and

157:22

fruits. Yep. Apple, orange, banana,

157:24

coconut, coconut. All right, everybody.

157:27

So, those are collections. Think of them

157:29

as a single variable used to store

157:32

multiple values. There's four general

157:34

purpose collections for beginners.

157:36

Lists, sets, tpples, and then

157:39

dictionaries, which we'll talk about

157:41

next. Each of them has unique benefits.

157:43

Lists are ordered and changeable.

157:46

Duplicates are okay. A set is unordered

157:49

and immutable, but adding and removing

157:51

elements is okay. No duplicates allowed.

157:54

A tpple is ordered and unchangeable.

157:57

Duplicates are okay and they are faster

158:00

than lists. Use tpples if you can over a

158:02

list. But yeah, those are a few

158:04

collections in

158:07

Python. Hello everybody. Today we will

158:10

be creating a shopping cart program.

158:12

This program will be an exercise to

158:14

follow the previous lesson on lists,

158:17

sets, and tpples. The more that we

158:19

practice with those collections, the

158:20

better we'll be at using them. So, I

158:22

thought we'd create an exercise to get

158:24

the hang of it before moving on. In this

158:26

program, we will have two lists. Foods.

158:29

These lists will be empty. We'll declare

158:31

them, but not use them quite yet. And

158:35

prices, then a total. Total equals zero.

158:40

The reason that I'm not using tpples is

158:42

that tpples are unchangeable. We're

158:45

going to ask a user what food they would

158:47

like to buy. We can't append any

158:49

elements to a tpple. We're not using

158:51

sets because sets are unordered. I mean,

158:53

I guess technically you could, but at

158:55

the end of this program, I'm going to

158:57

print our shopping cart in order. So, I

158:59

think lists would probably be the best.

159:01

We have an empty list of foods and an

159:03

empty list of prices. We'll use a while

159:06

loop. While

159:08

true. If our condition is set to true,

159:12

we'll need some way to break out of the

159:13

while loop. We'll need a break statement

159:15

somewhere.

159:17

We'll get to that later. We will ask the

159:19

user what food would they like to buy.

159:21

Let's declare variable food equal to

159:26

input enter a food to

159:31

buy. To exit the while loop, you need to

159:34

press Q to quit.

159:40

Then let's check if food is equal to Q

159:46

lowercase Q then we will break. We're

159:50

not done with the program but let's at

159:51

least test

159:53

it.

159:55

Pizza

159:57

hamburger hot dog Q to quit. Okay, it

160:01

looks like it works. Now, what if

160:03

somebody types in uppercase

160:05

Q?

160:07

Pizza hamburger uppercase Q. Well, we

160:11

can't actually quit. After accepting our

160:14

user input, if food lower method, this

160:19

will take our input, make it lowercase

160:21

just for a

160:23

comparison. Let's try that

160:26

again. Pizza hamburger.

160:30

I'll type capital Q to quit and that is

160:33

valid. Follow food with the lower method

160:36

to temporarily make the user input

160:38

lowercase just in case they type in

160:41

capital Q. If the user doesn't want to

160:44

quit, let's add an else

160:46

statement. Else, let's take our foods,

160:49

use the append method, then add whatever

160:52

food the user typed in. We'll also need

160:55

a

160:56

price. Let's ask a user for the price.

161:00

price

161:01

equals

161:03

input enter the price of let's use an F

161:10

string

161:12

a whatever food the user types

161:15

in pick a unit of currency I'll pick

161:18

dollars we are working with numbers we

161:21

should type cast our input as a

161:23

floatingoint

161:24

number since we're working with

161:27

prices so we will accept a price. Add

161:30

our food item to our list of foods. Do

161:33

the same thing with prices.

161:36

prices.append whatever the price

161:38

was. And that is the while loop. Let's

161:42

test this program again to be sure that

161:43

everything's

161:45

working. Pizza. Pizza will be

161:50

$5.99. Enter a food to buy. Hamburger.

161:54

Hamburgers will be

161:55

350. Hot dog. Hot dogs will be 175. I

162:00

would like to quit. I will type either

162:02

capital Q or lowercase Q. Both will

162:04

work. And we have escaped the while

162:06

loop. So the while loop is now complete.

162:09

Outside of the while loop, let's display

162:11

our shopping cart. Let's print some

162:13

decorative

162:15

text. Maybe five dashes your cart. Then

162:20

another five dashes.

162:22

I will then iterate over all of the

162:24

elements found within my foods

162:27

list. For every food in my list of

162:33

foods, let's print each food item. Let's

162:38

take a look so far. Again, we have a

162:40

pizza. The price was

162:42

$5.99. Hamburger, the price was

162:46

350. Hot dog 175. Q to quit. Okay, your

162:53

cart that will display the individual

162:55

list items. If you would rather have

162:57

these list items arranged horizontally

163:00

in one

163:01

line, you can add this keyword end

163:04

equals. This end keyword will replace

163:07

the new line character at the end of a

163:09

print statement with some other

163:10

character like a space. Let's try that

163:13

again. I'll try not to take too much

163:15

time.

163:18

Pizza

163:21

5.99.

163:23

Hamburger

163:25

350. Hot

163:28

dog

163:30

175. Q to quit. Yeah, that's much

163:33

better. We are horizontally listing all

163:36

of the different items within our list.

163:38

You could revert back to the vertical

163:40

list if you'd prefer that. I'll keep my

163:41

output like this. Then we will need to

163:44

iterate and add up all the prices. For

163:47

every price in

163:49

prices, we do have a total variable that

163:52

we declared. Let's utilize that. Total

163:55

equals total plus price. Otherwise, we

163:59

could shorten this to plus equals price.

164:02

That would do the same

164:04

thing. Then we will display the

164:07

total. Print. I'll use an fstring.

164:11

Your total

164:14

is I'll add a unit of currency. I picked

164:17

the dollar sign. Whatever the total

164:20

is. Okay, let's run this program one

164:23

last

164:24

time. Enter a food to buy. Pizza, which

164:28

was

164:29

$5.99. Hamburger, which was 350. Hot

164:35

dogs, they are

164:37

175. Q to

164:39

quit. Here's your shopping cart. I'm

164:42

just going to add one new line real

164:44

quick right before we display the total.

164:47

Just an empty print

164:57

statement. Here are the results. Your

165:00

cart, pizza, hamburger, hot dog. Your

165:02

total is

165:05

$11.24. All right, everybody. Well, that

165:07

is a shopping cart program. I thought

165:09

this would be a fun exercise to follow

165:11

the previous lesson on lists, sets, and

165:14

tpples. And well, yeah, that is a

165:16

shopping cart program in

165:20

Python. Hey, what's going on everybody?

165:23

So, today I'm going to be explaining 2D

165:25

lists. 2D meaning two-dimensional. You

165:28

do also have the capability of creating

165:30

2D tpples. I thought today we would use

165:32

2D lists just because they're pretty

165:34

flexible. A two-dimensional list is just

165:37

a list made up of lists. It's really

165:40

useful if you ever need a grid or matrix

165:42

of data, kind of like an Excel

165:44

spreadsheet. Let's create three lists. A

165:47

list of

165:49

fruit,

165:51

vegetables, and

165:53

meat. I'm going to speed up this video.

165:56

Feel free to pause if you need to catch

166:00

up.

166:11

Here I have three lists. A list of

166:13

fruit, vegetables, and meat. Each of

166:16

these lists is a one-dimensional list.

166:19

To create a two-dimensional list, well,

166:21

you would begin by creating a

166:22

one-dimensional list. Let's create a

166:24

list of groceries.

166:27

All I would need to do is add my

166:29

individual lists as elements to the

166:31

outer list, the 2D list. We have fruits,

166:35

vegetables, and

166:38

meats. Normally, to print a list or your

166:41

other collections, you would print the

166:44

name of the

166:45

list. In my list, fruits, I have apple,

166:48

orange, banana, coconut. To access or

166:51

change one of the elements, you would

166:52

type the name of the list, then use the

166:54

index operator. So fruits at index of

166:57

zero is a pineapple.

167:00

Again, with a 2D list, it's a little

167:03

different. If I were to print my 2D list

167:05

of

167:07

groceries, we would lay out the entire

167:09

2D list flat. We have individual lists

167:13

separated with a comma, all enclosed

167:15

within a set of square brackets. Taking

167:17

the elements found within our 2D list,

167:20

I'm going to line these up kind of like

167:22

this. It kind of represents a grid or

167:24

matrix with rows and columns. Each

167:27

individual list resembles a row. Each

167:30

element resembles a column. If I were to

167:32

print groceries at index zero in place

167:36

of returning one element found within

167:38

one of the lists, that would return an

167:41

entire row. So groceries at index zero

167:44

is my fruits list. Groceries at index

167:47

one is my vegetables list. groceries at

167:51

index 2 is my meats list. For one of the

167:54

elements found within one of the rows,

167:56

you would need two

167:58

indices. If I need the apple from the

168:00

first row within my 2D list of

168:02

groceries, that would be row 0, column

168:06

0. It's kind of like coordinates. Row 0,

168:10

column 0. That would be my

168:13

apple. 01, which is an orange.

168:18

02 is banana, 03 is coconut. For the

168:22

next row, I would set the first index to

168:25

be

168:26

one. Row one, column zero, that would be

168:30

celery. I'm going to speedrun this real

168:32

quick just to show you all the different

168:34

elements. 1 one is carrots, one two is

168:38

potatoes. If we try to access

168:40

13, that index is out of range because

168:44

we only have three elements within this

168:46

row. So then the next row would have an

168:49

index of two. Column 0 would be

168:54

chicken. 2 1 is

168:56

fish. 2 is

168:58

turkey. 2 3 is out of bounds. To access

169:02

an element from a 2D list, you would

169:04

need two indices in place of one because

169:07

using just one would return the entire

169:09

row like so. Now, when you declare a 2D

169:13

list, you don't need to necessarily give

169:15

each inner list a name. We could do

169:17

something like

169:20

this. I'm going to replace these names

169:23

with the

169:27

rows. I'm just going to put these on a

169:29

new line to make it more

169:35

readable. There, that would work, too.

169:38

Just separate each inner list with a

169:40

comma, then enclose everything with a

169:42

set of square brackets. If you ever need

169:45

to iterate over the elements of a 2D

169:47

list, you can use nested loops. If I

169:50

were to use a single for loop, let's say

169:52

for every uh maybe

169:55

collection, for every collection

169:58

in

170:00

groceries, let's print what our

170:02

collection

170:06

is. Using a single for loop would

170:09

iterate over the rows. But to also

170:11

iterate over the elements found within

170:13

each row, we would use a nested loop.

170:17

for every food in our

170:22

collection. Let's print what our food

170:27

is. Using nested loops, we can iterate

170:30

over all of the elements found within

170:31

our 2D list. But I'm going to make this

170:33

more organized like that grid structure

170:35

we have. I'm going to replace the new

170:38

line character at the end of a print

170:39

statement with a space.

170:42

Then when we exit the nested loop, I

170:44

will print a new line by using just an

170:46

empty print

170:47

statement there. That kind of resembles

170:50

our grid structure, we have

170:52

rows and we have columns. With

170:56

two-dimensional collections, you're not

170:57

limited to just lists. You could create

171:00

a list of

171:01

tpples. So the inner rows will be

171:03

surrounded with a set of

171:07

parenthesis. You know, this is also

171:09

valid too. Or you could make a 2D tpple.

171:13

It's a tpple that's made up of tpples.

171:16

You could make a tpple made up of

171:18

sets. Sets are enclosed with a set of

171:21

curly

171:25

braces. Here we have a tpple made of

171:28

sets. Use whatever is best for your own

171:31

programs. Let's go over an exercise.

171:34

Let's create a two-dimensional keypad

171:36

that you would normally find on a phone.

171:38

We have three data types. a list, a set

171:41

or a tpple. The elements in a set are

171:44

unordered, so we can't use that. These

171:47

numbers need to be in order. If we have

171:49

the option, a tpple is faster than a

171:51

list. A tpple is ordered and

171:53

unchangeable, so we should use it if we

171:56

can, and that's perfectly fine. Let's

171:58

create a 2D tpple this time. I will name

172:01

this 2D tpple

172:03

numpad. We have an outer set of

172:05

parenthesis, then an inner set of

172:07

parenthesis for each row. We will have

172:11

four

172:12

rows. The first row will be 1 2 3. The

172:17

second row, I'm going to put this on a

172:19

new

172:20

line. 4 5

172:23

6. The next row will be 7 8 9. Then the

172:28

last row will be an asterisk character.

172:32

Then

172:33

zero. Then the pound sign. So numpad in

172:37

this case is a 2D tpple. Let's use a for

172:41

loop to iterate over every row. This

172:43

will be the outer loop. For every maybe

172:47

row for every row in

172:50

numpad, let's begin by printing our

172:55

row. So we're printing every row in our

172:58

numpad, but I'd like to remove the

173:00

parenthesis.

173:02

Let's create a nested loop for

173:06

every maybe num for num in

173:12

row. Print whatever that num

173:16

is. We have one long vertical line.

173:20

Let's replace the new line character at

173:22

the end of our print statement with a

173:26

space. Then when we escape the nested

173:28

loop, let's print a new line.

173:33

And there is our telephone number pad.

173:35

You can see it's a grid made up of rows

173:37

and columns. So yeah, that's a 2D list.

173:40

Well, a 2D collection. It's a collection

173:43

that's made up of collections. Then with

173:46

our numpad, we made a 2D tuple. If you

173:48

ever need a grid or matrix of data, a 2D

173:51

collection would work perfect. And there

173:53

you have it, everybody. Those are 2D

173:55

collections in Python.

174:00

Hello again everybody. So today we're

174:02

going to create a quiz game in Python.

174:04

Let's declare all of the different

174:06

collections and variables that we'll

174:07

need. First we will need a tuple of

174:11

questions, a 2D tuple of

174:15

options. My quiz will have five

174:17

questions, but you can add more or less

174:23

questions. Then a tuple of answers.

174:28

A list of guesses. We will be appending

174:32

guesses to our list. That's why we're

174:34

using a list rather than a

174:36

tpple. A score variable, which I will

174:39

set to be zero. Then question

174:42

number. This variable will keep track of

174:44

what number question we're on. All

174:46

right, let's begin with our questions. I

174:48

have

174:52

five.

175:14

Here are my questions. They're all

175:16

science related. Feel free to choose

175:18

your own. This is what I have. How many

175:21

elements are in the periodic table?

175:24

Which animal lays the largest eggs? What

175:26

is the most abundant gas in Earth's

175:28

atmosphere? How many bones are in the

175:30

human body? Which planet in the solar

175:32

system is the hottest? These are the

175:35

questions, but we'll need options. Let's

175:37

add four options for every question.

175:40

That's why we're using a two-dimensional

175:42

tpple. Each inner tpple will consist of

175:45

four elements.

175:54

They will be options

175:56

A,

175:58

B, C or

176:01

D. Let's copy these elements then paste

176:04

them within each

176:08

tpple. This first element corresponds to

176:11

my first question. How many elements are

176:13

in the periodic table? I'll come up with

176:15

some answers.

176:20

I'll add some answers for the rest of

176:22

these tpples, too.

176:50

We have a tuple of correct

176:53

answers. The orders are C,

176:57

D, A,

177:01

A, B. If you come up with your own

177:05

options, your answers may be different.

177:08

Now that we have all of our different

177:09

collections and variables taken care of,

177:12

let's display each question. I will

177:14

iterate over our tpple of questions.

177:17

They are iterable. For every question in

177:22

questions, I'm going to print some

177:24

decorative

177:27

text. I think that's probably

177:29

good. Then I will print each question

177:33

we're iterating over. So let's see what

177:36

we have so far.

177:39

There's all five

177:41

questions. After we display every

177:43

question, I need to display every option

177:46

for every option in

177:50

options. Our options options is a 2D

177:55

tuple. Let's add the index operator. The

177:59

index is going to be our question number

178:01

variable. It's a number. So at first

178:05

we're accessing options at index of

178:07

zero. Then 1 2 3 4

178:11

5. We will print every option in

178:16

options. Add a given row number. Let's

178:19

test this. Okay, we have some options.

178:22

But all of these options are for the

178:25

first question. We will need to

178:27

increment our question number. So let's

178:30

do that. Maybe here.

178:34

question number plus equals

178:40

1. That is much better. Before iterating

178:44

the question number, we will ask the

178:46

user for a guess. Guess equals

178:53

input

178:56

enter A B C D.

179:03

In case the user types in something

179:04

that's lowercase, I will follow this

179:06

input with the upper method to make the

179:09

user input

179:10

uppercase. We will take our list of

179:15

guesses, use the append method, add our

179:19

guess to that

179:21

list. If our guess is equal to the

179:26

answers tpple at index of question

179:30

number that means the user guessed the

179:33

right answer. Let's increase the user

179:35

score. Sc score score plus equals 1.

179:38

Then print the word

179:40

correct.

179:43

Correct. Else we will

179:47

print incorrect.

179:51

I'll use an

179:55

fstring. Our

179:57

answers at index of question

180:02

number is the

180:05

correct answer. All right, let's answer

180:08

some of these

180:12

questions. C. Correct. Which animal lays

180:16

the largest eggs? Um, definitely the

180:19

whale because the whale is the largest

180:21

creature,

180:22

right? Incorrect. D is the correct

180:25

answer. What is the most abundant gas in

180:27

Earth's atmosphere? Nitrogen. Correct.

180:30

How many bones are in the human body? D.

180:33

That is incorrect. A is the right

180:34

answer. Which planet in the solar system

180:37

is the hottest? Mercury, because it's

180:39

closest to the sun,

180:40

right? Wrong. Incorrect. B is the

180:43

correct answer. We're keeping track of

180:45

our answers successfully. Once we

180:48

complete all the questions, let's print

180:50

the

180:51

results. I'm going to add some

180:53

decorative text. Not necessary, but I

180:56

think it would look

180:59

cool. I will display the

181:05

results. We will iterate over all of the

181:08

answers and the

181:11

guesses. Print

181:17

answers. I'm going to set the ending

181:19

character to be an empty

181:23

string for every answer

181:28

in

181:30

answers.

181:32

Print each

181:34

answer. I will set the ending character

181:37

to be a space to separate each answer.

181:41

Then I'll add a new print

181:43

line. Let's do this with

181:46

guesses. Change answers to guesses for

181:50

every guess. In guesses, print each

181:56

guess. Okay, I'm going to run this

181:58

again. I'm just going to make up some

182:00

answers. A B C D A. Here are the correct

182:06

answers. Here are the guesses. I guess

182:09

none of them right. Then we will print a

182:12

score. Score equals take our score

182:17

divided by I'm going to use the length

182:20

function. Then pass in our questions.

182:23

How many elements are within our

182:26

questions tuple then I will multiply all

182:29

of this by 100 to give us a percentage.

182:32

Then type cast this whole formula as an

182:35

integer.

182:36

So, we're basically just reassigning our

182:38

score

182:40

variable. Then, let's print using an

182:43

fring, your score

182:47

is our score variable. Then add percent.

182:52

I'm going to intentionally get all the

182:54

answers

182:55

right. C D

182:59

A

183:01

B. Here are the answers. Here are your

183:03

guesses. Your score is 100%. This time

183:06

I'll try and get a few incorrect

183:08

intentionally. C

183:12

C. Your score is

183:14

20%. All right, everybody. Well, that is

183:17

a quiz game. Feel free to add more or

183:19

less questions or come up with your own

183:21

questions. And that is a quiz game

183:24

written in

183:27

Python. Hey everybody. In today's video,

183:29

I'm going to explain dictionaries. A

183:31

dictionary is one of the four basic

183:33

collection types for beginners. A

183:35

dictionary consists of key value pairs.

183:38

They are ordered and changeable. No

183:40

duplicates allowed. A few examples of

183:42

key value pairs could be an ID and a

183:46

name, an item, and a price. But in

183:48

today's example, we'll create a

183:50

dictionary of countries and capitals.

183:53

Let's name our dictionary capitals.

183:55

Capitals equals enclose your dictionary

183:58

with a set of curly braces, much like

184:00

what you do with sets. The first country

184:03

will be the USA. To add a value to this

184:06

key, type colon then some other value.

184:10

The capital of the USA will be

184:13

Washington

184:16

DC. Separate each key value pair with a

184:19

comma. Then we can add another key value

184:22

pair. So the capital of

184:25

India that will be New Delhi. We'll add

184:30

two more.

184:32

China. The capital is

184:36

Beijing.

184:39

Russia, the capital is Moscow. I think

184:43

that's good

184:44

enough. Just as a reminder, if you would

184:46

like to see all of the different

184:48

attributes and methods of a dictionary,

184:50

you can use the dur function. Pass in

184:52

your dictionary capitals. Then we'll

184:55

need to print

184:56

this.

184:58

Here's all the different attributes and

185:01

methods of a dictionary. If you would

185:03

like an in-depth description of all

185:05

these attributes and methods, you can

185:07

use the help

185:11

function. Uh, that's herp help. There we

185:17

go. So, yeah, that's just a

185:20

reminder. All right, let's go over a few

185:22

of the methods. To get one of the values

185:25

from a dictionary, you would get the

185:27

key. Type the name of the dictionary.

185:31

Capitals.get. Let's get the capital of

185:34

the

185:35

USA. Then we'll print

185:39

it. The value associated with this key,

185:42

the USA is Washington DC. If I picked a

185:46

different country like

185:49

India, well then we would get that

185:51

associated value which is New Delhi.

185:54

Another thing, if Python doesn't find a

185:56

key, this is what will be returned.

185:58

Let's get Japan which is not in our

186:01

dictionary. This method would return

186:04

none. We can use this within an if

186:08

statement. If capitals

186:12

get

186:14

Japan if a value is returned then we

186:18

will

186:19

print that capital

186:24

exists

186:25

else we will print that

186:30

capital doesn't

186:33

exist so Japan is not in our dictionary

186:36

that capital doesn't exist but Russia

186:39

is that capital does exist. That's how

186:43

to check to see if a key is within our

186:45

dictionary. You can use the get

186:47

method. All right, moving on. Let's

186:50

update our

186:51

dictionary.

186:54

Capitals.update. So within a set of

186:56

curly braces, I will add a key then a

187:00

value.

187:03

Germany followed

187:05

by Berlin. Then let's print our

187:08

dictionary. I'll use a print statement.

187:11

Print

187:14

capitals. Yeah. And there's Germany

187:16

right there. Using the update method, we

187:18

can insert a new key value pair or

187:21

update an existing key value pair. Let's

187:23

also change one of the existing values

187:25

with our key USA. Let's update the

187:29

capital to be

187:32

Detroit. Yeah, see the value has been

187:34

updated. The capital of the USA is now

187:37

Detroit,

187:38

Michigan. To remove a key value pair,

187:41

you can use the pop method. Then pass in

187:44

a key. Let's remove

187:47

China. China no longer exists within our

187:50

dictionary. It's gone. You can remove

187:52

the latest key value pair within a

187:54

dictionary by using the pop item method.

187:58

Capitals do pop item. With pop item, you

188:03

don't need to pass in a key. Pop item

188:06

will remove the latest key value pair

188:08

that was inserted. Then we have clear

188:13

capitals.clear. That will clear the

188:15

dictionary. It's pretty

188:17

self-explanatory. The next few methods

188:19

are a little tricky to explain. To get

188:22

all of the keys within the dictionary,

188:24

but not the values, there is a keys

188:27

method. Capitals.

188:31

I think I'm going to insert this within

188:32

a variable keys equals capitals keys.

188:37

Let's see what happens when we print

188:40

this. The keys method will return all of

188:43

the keys within our dictionary.

188:45

Technically, keys is an object which

188:47

resembles a list. I haven't discussed

188:49

object-oriented programming yet. This is

188:51

a little bit above our level. If you

188:53

ever need the keys in a dictionary, you

188:55

can use the keys method. One use is that

188:57

we can use that within a for loop.

188:59

They're iterable. For every key in

189:03

capitals keys

189:05

method, let's print every

189:09

key. If at any time you need to iterate

189:12

over all the keys, you can use a for

189:15

loop to iterate over every key that is

189:17

returned from the keys method of your

189:19

dictionary. There is also the values

189:22

method to get all of the values within

189:25

your dictionary. There is a values

189:28

method. Values equals capitals do values

189:34

method. Then let's print our

189:39

values. Like before with the keys

189:41

method, the values method will return an

189:44

object which resembles a list. Let's

189:46

iterate and print over every value

189:48

within our dictionary. for every value

189:52

in capitals do

189:58

values. Print every

190:02

value. Here are all the values within

190:05

our

190:06

dictionary. This next one is probably

190:08

the most tricky. It is the items method.

190:11

Capitals do items. I will assign what is

190:14

returned to a variable named items. Then

190:18

we will print items.

190:22

items returns a dictionary object which

190:24

resembles a 2D list of tpples. It's

190:28

really complicated. How might this be

190:29

useful? This time we're going to use a

190:31

for loop to print every

190:34

key, value in capitals do items

190:39

method. We have in essence two counters.

190:43

This time I will print using an fstring

190:47

every key value pair. I will print every

190:51

key as well as every value in our print

190:56

statement. So there's our dictionary

190:58

laid out. We have iterated over every

191:00

key value pair. It's kind of an advanced

191:03

topic, but I thought I would at least

191:04

bring it up now. So yeah, that's a

191:06

dictionary, everybody. It's a collection

191:08

of key value pairs. They are ordered and

191:11

changeable. No duplicates allowed. You

191:14

have a bunch of different methods such

191:15

as get, update, pop, pop item, clear.

191:19

Then you can get the keys, the values,

191:22

or both, which is the items method.

191:24

We'll be using dictionaries in a few

191:26

game programs we'll be making in the

191:27

future. And well, yeah, those are

191:29

dictionaries in

191:32

Python. Hey everybody. Today we will be

191:35

creating a program to mimic a concession

191:37

stand, much like what you would see at a

191:39

movie theater. We will be utilizing a

191:41

dictionary to keep track of a menu item

191:44

and an associated price. More or less,

191:46

this is just a program to help us get

191:48

used to working with dictionaries. Let's

191:50

begin. We'll create a dictionary named

191:53

menu. What items are on the menu? We'll

191:56

need an item and a price. I'll think of

191:58

some. I'm going to speed up this video.

192:00

Feel free to pause if you need more

192:02

time.

192:18

and here's my menu, everybody. I thought

192:21

of a few food items you might find at a

192:23

movie theater concession stand. Pizza,

192:25

nachos, popcorn, fries, chips, soft

192:28

pretzels, soda, lemonade. Movie theater

192:30

popcorn is really expensive for some

192:32

reason. Okay, we have our menu. A user

192:35

is going to select specific keys from

192:37

this menu. Depending on what the key is,

192:40

we can get the associated value to

192:42

calculate a total. To keep track of the

192:44

user selected items, I will create an

192:46

empty list named cart. I will also

192:49

declare a variable named total to keep

192:51

track of the total. We need to lay this

192:54

dictionary down flat to display it to a

192:56

user. Well, we do have the items method

192:58

of a dictionary which we covered in the

193:00

last video. for every key value in our

193:06

dictionary menu dot items method. The

193:10

items method of our dictionary will

193:12

return a key and a value during each

193:15

iteration. I'm simply going to print

193:18

every key and value. I'll use an

193:21

fstring. I will print every key colon

193:25

space then a

193:28

value. Let's take a look so far.

193:32

Here's our menu. I'll make a few

193:34

changes. The price will be in dollars

193:37

and cents, but feel free to pick your

193:38

own unit of currency. I'll preede my

193:41

value with the dollar sign. Then using a

193:44

format specifier, I will display two

193:47

decimal places

193:50

2F. That's better. I will line up all

193:54

the keys. After the key, I will add a

193:58

format specifier. then allocate 10

194:01

spaces. Yeah, look at that. It's all

194:04

lined up. Now before and after

194:05

displaying our menu with this for loop,

194:08

I will add some decorative

194:12

text. Let's say

194:19

menu. Then outside of the for loop, I'll

194:22

display a bunch of dashes.

194:29

Yeah, look at that. Let's move on to the

194:32

next

194:33

step. We will ask a user for some input.

194:36

What item would they like to buy from

194:38

the menu? While our condition will be

194:41

true. If our condition is set to true,

194:44

we'll need to break out of this loop one

194:46

way or another. We will ask for some

194:48

user input. food equals

194:53

input

194:55

select an

194:57

item Q2 to

195:02

quit. If food is equal to a lowercase Q,

195:08

then we will

195:10

break. Let's test

195:12

it. Select an item.

195:16

Pizza, nachos,

195:20

soda, Q to quit. Yeah, it works. Okay.

195:23

What if the user types in capital Q?

195:27

Well, we can't escape the while

195:29

loop. If a user types in capital Q,

195:32

we're assuming that they would like to

195:33

quit. When we accept our user input, I'm

195:36

going to add dot lower method. This will

195:39

take our user input and make it all

195:42

lowercase. So, we should be able to

195:44

acknowledge any uppercase letters. Yeah,

195:47

it works. Cool. Let's add an else- if

195:52

statement. What if a user types in an

195:54

item that's not on our menu? Well, there

195:57

is a get method of

195:59

dictionaries. If menu

196:03

get pass in our food which is user

196:06

input. If the user selection is not

196:09

within our menu as a key it will return

196:13

none. So we can use that else if

196:16

menu.get food is not

196:21

none then we would like to append that

196:24

food item to our

196:26

cart. cart.append

196:30

append our food

196:32

item. So, outside of the while loop, I'm

196:36

going to print our cart temporarily just

196:39

to test

196:41

it. Okay, select an item. Pizza,

196:46

soda, pretzel. How about a

196:50

potato? Q to quit. We have our pizza,

196:54

soda, and pretzel, but not our potato.

196:56

We don't want that in our cart because

196:58

that's not on the menu. Yeah, you can

196:59

just add that line. Else if menu item

197:03

get food is not none. That will complete

197:06

our while loop. Let's calculate a

197:09

total for every food in our cart. Let's

197:14

take our total variable. Set this equal

197:17

to total plus. Then we need a value

197:22

associated with a

197:25

key plus

197:27

menu. Get method get the food item found

197:32

within our cart. But I'm going to

197:34

shorten this to total plus

197:37

equals menu.get the value associated

197:41

with this food in our cart. I will also

197:45

display that food item. Print food. I'm

197:49

going to avoid printing our food item on

197:51

every line. I will set the ending

197:54

character in our print statement just to

197:56

be a space. Okay, let's see what we have

197:59

so

197:59

far. I would like

198:03

popcorn,

198:04

soda,

198:06

pretzel. Q to quit. Popcorn, soda,

198:10

pretzel. Then we will display the total.

198:13

I will print a new line.

198:18

print I'll use an

198:22

fstring total

198:27

is add a unit of currency total I'll add

198:31

a format

198:32

specifier 2F to display two decimal

198:35

places I'm going to add one line of

198:38

decorative

198:40

text let's copy maybe

198:51

this. All right, let's test it

198:58

out. Select an

199:00

item.

199:03

Popcorn,

199:05

pretzel,

199:07

soda,

199:09

potato. Q to quit.

199:12

All right, here's our cart. Popcorn,

199:14

pretzel, soda. We did not include the

199:16

potato. That was not found within our

199:18

dictionary. The total is

199:21

$12.50. Well, there you have it,

199:23

everybody. That is a concession stand

199:25

program. The point of this program was

199:27

to help us get used to working with

199:29

dictionaries. A dictionary is a

199:31

collection of key value pairs such as an

199:34

item and a price. And yeah, that's a

199:37

concession standard program in Python.

199:42

Well, hello again everybody. It's me. In

199:45

today's topic, I'm going to show you how

199:47

we can generate some random numbers in

199:48

Python. Then at the end of this video,

199:50

as an exercise, we're going to create a

199:52

number guessing program. Let's begin. We

199:55

will be importing the random module.

199:57

Type import random. The random module

200:01

gives us access to a lot of useful

200:03

methods involving random numbers. For a

200:05

comprehensive list, you can use the help

200:08

function. pass in the random module and

200:11

then we would want to print

200:15

this. Here's what we all have access to.

200:19

We have a shuffle method, set state,

200:22

seed, sample, random range, random,

200:26

random int, random bytes, and there's a

200:28

ton of others, but we'll discuss a few

200:30

of the more useful methods for

200:31

beginners. For a random whole integer,

200:34

maybe you're rolling a six-sided dice.

200:37

You would type the name of the random

200:38

module dot then a method. For a random

200:42

whole integer, type rand int add a set

200:45

of parenthesis. Within the set of

200:47

parenthesis, you will list a range. If

200:50

I'm rolling a six-sided dice, I would

200:52

like the numbers 1 through 6, 1, 6. Then

200:56

I will assign what is returned to maybe

200:59

a variable.

201:00

print whatever my number

201:05

is. My random number is a four, three,

201:09

one, four. All right. I tend to play a

201:12

lot of Dungeons and Dragons. We use

201:14

polyhedral dice that have more or less

201:17

than six sides. There is a 20sided dice.

201:20

For a random number between 1 and 20, I

201:23

would set the range to be 1, 20. Here I

201:27

rolled a 16 and a seven and an eight.

201:31

Within the rand int method, you can

201:33

place variables as well as long as they

201:35

contain numbers. I will create a

201:37

variable named low. I'll set that equal

201:39

to

201:40

one. And a variable named high. I will

201:43

set that to be 100. I will replace the

201:46

numbers with my variables that behave as

201:50

numbers. Give me a random integer

201:52

between my low variable and high

201:54

variable. So between 1 and 100 in this

201:57

example, I have rolled a

201:59

75. Now in 88, if you need a random

202:02

floatingoint number, you can use the

202:04

random method.

202:07

Random.random. Then let's assign this to

202:09

a

202:10

variable. Number equals the random

202:13

method of the random module. That would

202:16

return a random floatingoint number

202:18

between 0 and 1.

202:21

You can pick a random choice from a

202:23

sequence. In the future, we're going to

202:25

create a game of rock paper scissors.

202:28

Let's say we have a tpple of

202:31

options. Options

202:34

equals

202:36

rock

202:38

paper

202:40

scissors. We are accessing the random

202:43

module. Dot. Then use the choice method.

202:46

Place your sequence within the choice

202:48

method. give me a random choice from

202:52

options. I will store this within a

202:54

variable. Let's say option equals random

202:58

choice from my options. Then I will

203:01

print the

203:03

option. Our computer has generated

203:05

scissors,

203:07

paper, rock. So the choice method is a

203:10

great use for games if you ever need a

203:13

random element. Now there's also

203:15

shuffle. This time maybe we have a deck

203:18

of cards.

203:19

cards equals I guess I'll use a list

203:22

this

203:32

time. I have a list of cards that you

203:34

would normally find within a deck of

203:36

playing cards. Well, besides the suit 2

203:39

through 10, Jack, Queen, King, Ace.

203:42

Using the shuffle method, I can shuffle

203:44

this

203:45

sequence. Access the random module.

203:49

Shuffle. Pass in your

203:51

sequence. In my case, it's cards. Then I

203:54

will print

203:56

cards. Yeah, look at that. My cards are

203:59

now shuffled. In the future, we'll be

204:01

creating a game of blackjack. The

204:03

shuffle method will be used then to

204:05

shuffle our deck of cards. Those are a

204:07

few methods found within the random

204:09

module. For some practice, let's create

204:11

a number guessing game as an

204:15

exercise. Hey everybody. So today we're

204:18

going to create a number guessing game

204:19

using Python. This is a project meant

204:22

for beginners. By completing this

204:23

project, it will help us reinforce our

204:25

understanding of previous topics. Let's

204:27

begin. We will import the random module.

204:32

We'll need to pick a random number. The

204:34

random module is going to handle that

204:35

for us. What is the range of random

204:38

numbers for our number guessing game?

204:40

We'll store those as variables.

204:43

We will have one variable named lowest

204:46

number. I'll set that to be one as well

204:49

as a variable for highest number which I

204:52

will set to be 100. Feel free to pick a

204:55

different range if you would like. I'll

204:57

set the range to be 1 through 100. A

205:00

random number will be selected between

205:01

this range which will be stored within a

205:05

variable named answer. What is the

205:07

correct answer? So to choose a random

205:10

number between these two values, we will

205:13

access the random

205:14

module called the rand int method. We

205:19

will choose a random integer between

205:20

these two

205:22

values. The two arguments will be lowest

205:26

num, highest num. For the second

205:31

argument, let's perform a test run. I

205:34

will print my answer.

205:38

the number is going to be between 1 and

205:43

100. Okay, we know that that

205:46

works. Here's a few more

205:49

variables. We need to keep track of the

205:51

number of wrong guesses which I will

205:53

store as a variable named

205:55

guesses. We want the user to keep

205:57

guessing as long as our application is

206:00

running. We will create a boolean

206:02

variable of is running which we will set

206:05

to be true. Once the user wins the game,

206:09

we will set is running to be

206:13

false. We will print a welcome

206:17

message. Let's say

206:19

Python

206:21

number guessing

206:25

game. We will prompt the user. I'll use

206:28

an

206:30

fstring. Select a number between. I'll

206:35

add two

206:39

placeholders. Select a number between

206:41

our lowest number and our highest

206:46

number. Python number guessing game.

206:48

Select a number between 1 and 100. Now,

206:52

if I was to change the range of these

206:54

variables, that should be

206:57

reflected temporarily. I changed the

206:59

lowest number to be 10 and the highest

207:01

number to be 1,00. But let's set that

207:06

back. Between one and 100 is

207:09

good. We'll need a while loop to

207:12

continue the game each

207:13

round. We will say while is

207:18

running. Since is running is a boolean,

207:21

we don't need to say while is running

207:23

equals true. We can just say while is

207:26

running while this value remains true.

207:29

Continue playing the game.

207:31

We will ask the user for some input. We

207:34

will create a local variable of guess.

207:37

Guess

207:39

equals use the input function. Then

207:42

enter a prompt. Enter your

207:47

guess. There's one thing we want to

207:50

check. Python number guessing game.

207:52

Select a number between 1 and 100. Enter

207:55

your guess. What if somebody doesn't

207:57

type in a number like they type in the

207:58

word pizza?

208:00

We should let the user know that that's

208:02

an invalid

208:04

guess. We'll write the following if

208:07

statement. If our guess use the is digit

208:13

method. If our guess is a digit a

208:16

number, then we will execute any code

208:19

underneath this if statement. For the

208:21

time being, I'll write pass. We'll get

208:22

back to that later. Else we will do

208:25

something

208:26

else. Let's print the following. print

208:31

invalid

208:34

guess. Let's copy this print statement

208:37

because I'm lazy and I don't feel like

208:38

typing it

208:40

out. Please

208:43

select a number between our lowest

208:46

number and our highest number. Let's try

208:49

that

208:51

again. I will guess pizza, which isn't a

208:54

number. And we get the message invalid

208:57

guess. Please select a number between 1

209:00

and 100. All right, that works.

209:04

Underneath our if statement, we'll write

209:05

the

209:06

following. Once we get a guess that is a

209:09

digit, we need to convert it to a number

209:11

because when you accept user input, it's

209:13

a string. We will reassign our guess

209:17

equal to type cast our guess as an

209:20

integer.

209:24

Then increase the number of guesses by

209:26

one. Guesses plus equals 1 because we

209:30

have already made one

209:32

guess. Here's another

209:34

scenario. What if somebody guesses a

209:36

number outside of this range like one

209:41

cajillion? Well, we should give a

209:43

warning that that guess isn't valid.

209:47

If our guess is lower than the lowest

209:53

number or our guess is greater than the

209:58

highest

209:59

number, we will print the

210:03

following. That number is out of

210:08

range and I will reprompt the user.

210:14

Please select a number between the

210:16

lowest number and the highest

210:20

number. Let's perform a test run. I will

210:23

guess one

210:25

cajillion. That number is out of range.

210:28

Please select a number between 1 and

210:31

100. We'll add an else if statement.

210:34

Else if our

210:36

guess is less than our answer, we will

210:40

print the following.

210:43

too low. Try

210:48

again. Else if our guess is greater than

210:53

our

210:55

answer, we will

210:57

print to high. Try again. If our guess

211:03

isn't less than our answer and our guess

211:06

isn't greater than our answer, that

211:08

means we must have the correct answer.

211:10

within an else statement we will

211:14

print. I'll use an F

211:16

string.

211:18

Correct. The answer was insert our

211:23

answer, our answer

211:25

variable. Then print the number of

211:27

guesses it

211:29

took. Number of

211:32

guesses. Add a

211:34

placeholder. Place in our guesses within

211:37

the placeholder. Now to escape the while

211:39

loop, we will take our boolean variable

211:42

of is running, which is normally true,

211:45

and set that to be false to

211:47

escape. And that should be all we need.

211:50

Let's run this one last

211:51

time. Python number guessing game.

211:54

Select a number between 1 and 100. Let's

211:57

select a number right in the middle. 50.

212:00

Too low. Try again. So the number is

212:02

between 50 and 100.

212:05

75. Too high.

212:08

It's between 50 and 75.

212:10

Then

212:13

62. Too

212:14

high.

212:18

56.

212:21

53.

212:22

55. Correct. The answer was 55. Number

212:26

of guesses. It took me

212:28

six. All right, everybody. That is a

212:30

Python number guessing game you yourself

212:33

can create as a mini project.

212:37

Hey everybody. In today's topic, I

212:39

thought we would create a game of rock

212:41

paper scissors. Now that we know how the

212:43

random module works, let's begin by

212:46

importing the random module. We will

212:48

create some options. We will use a

212:51

tpple. We're not going to be changing

212:53

the options. So a tpple would be better

212:55

than a list. We have three options.

212:59

Rock,

213:01

paper, or scissors.

213:05

I'll create a variable named player to

213:07

store the player's choice. For now, I'm

213:10

going to set this to be none as well as

213:12

a computer. Our computer is going to

213:15

pick a random choice from these options.

213:18

Rock, paper, or scissors. In order to do

213:20

so, we can use the choice method of the

213:23

random module.

213:26

Random.choice. Pick a random choice from

213:29

options.

213:32

Let's have the player enter in some

213:37

input. Enter

213:40

a

213:43

choice.

213:45

Rock,

213:47

paper,

213:50

scissors. Then we will display the

213:52

player's choice and the computer's

213:54

choice. I'll use an

213:58

fstring player colon

214:01

space the variable

214:04

player. Let's copy that. Paste it. Then

214:08

change player to

214:12

computer. Let's see what we have so

214:15

far. Enter a choice. Rock, paper,

214:18

scissors. So, I pick rock. The computer

214:21

picks scissors. Let's try it again just

214:24

for good measure. I pick paper. This

214:26

time the computer picks

214:29

scissors. I pick scissors. The computer

214:31

picks paper. Okay, we know that the

214:33

computer is successfully picking a

214:35

random choice from our options. Now,

214:38

what if the player picks something

214:39

that's not within this tpple such as the

214:43

gun? Well, we would want to stop that,

214:45

right? We need the user to pick a valid

214:48

option. Only rock, paper, or scissors. I

214:50

think what we'll do is that when we

214:52

accept the user input, let's place it

214:54

within a while loop. So indent this

214:57

line while this condition is going to be

215:01

kind of weird. While our player variable

215:04

is not in our tpple options. Let's try

215:10

this again to see what happens. I pick

215:12

the gun. Enter a choice. All right.

215:15

Well, if I can't pick a gun, how about a

215:17

sponge?

215:19

Well, I can't pick that either. Rock.

215:21

That works. Our condition is while the

215:25

player variable is not found within our

215:28

options. If the player doesn't pick one

215:31

of these options, this while loop will

215:33

continue forever. Once we pick something

215:36

that's within our options, we then

215:38

escape the while loop. Let's check some

215:40

win conditions. Now if the player is

215:44

equal to computer that means it's a tie.

215:48

I will

215:50

print it's a

215:52

tie. I'll add a few else if statements.

215:56

Else if the player is equal to rock I'll

216:01

use the and logical

216:03

operator and the

216:05

computer is equal to

216:08

scissors. That means you win.

216:11

Let's print you win. Let's add another

216:16

condition. Else if the player picks

216:21

paper and the

216:25

computer picks

216:29

rock, then you also win. You

216:34

win. L if the

216:37

player picks

216:40

scissors and the

216:44

computer and the computer picks

216:48

paper then we will

216:51

print you win.

216:55

else. If the player's choice is not the

216:58

same as the computers and we don't meet

217:01

any win conditions, that must mean we

217:04

lose. Print, you

217:08

lose. Let's see if this works. Enter a

217:11

choice. Rock, paper, scissors. I pick

217:13

the gun. Nope, I can't pick that. I pick

217:15

rock. I pick rock. The computer picks

217:18

scissors. You

217:19

win. Let me see if I can lose. I'll pick

217:22

paper.

217:24

You win

217:25

again.

217:27

Scissors. I need to stop winning. I need

217:29

to see if the lose condition

217:31

works. Okay, it's a tie at least. But I

217:34

need to

217:35

lose. All right, there we go. I pick

217:38

rock. The computer picks paper. You

217:40

lose. What if the user would like to

217:42

play again? Let's place all of this code

217:45

within a while loop. Let's do so right

217:48

about here. Now I'm not going to write

217:51

while true like I normally do. This time

217:54

I'm going to create a variable. Let's

217:56

say running. Is our game running? I will

217:59

set that to be

218:02

true. While running equals true or we

218:07

could shorten this to just while

218:09

running. That's

218:11

simpler. I will place all of this code

218:14

within the while loop. To mass indent

218:16

some code, just highlight all of the

218:18

code, then press tab. Hey everybody,

218:21

this is Bro from the future. I forgot to

218:23

explain something. The reason I'm not

218:25

setting the condition of my while loop

218:27

to be true is that if you have a lot of

218:29

code within a while loop, it can be

218:31

really difficult to find where the break

218:33

statement is. If I set my condition to

218:35

be a boolean variable such as running,

218:38

it's a lot easier to find any instance

218:40

where I use this variable. If I were to

218:42

highlight it, we can see that running is

218:44

found down here. If I need to change any

218:47

instance of this variable and rename it

218:48

to something, you can refactor. Let's

218:51

rename running as maybe playing. Then I

218:55

will refactor. So my variable running is

218:58

now playing. And that change was made

219:01

down here too. So it's a coding

219:03

preference. Every time we start a new

219:05

game, I will reset the player as well as

219:08

the computer. Let's move these two lines

219:10

into the while loop at the

219:12

beginning. So when we start a new game,

219:15

we will reset the player. The computer

219:17

will pick a new random choice. So let's

219:20

see what we have so

219:21

far. Rock. I pick rock. The computer

219:25

picks rock. It's a tie. Then we have to

219:27

play again. So paper, you lose.

219:32

Scissors. It's a tie. Now what if we

219:34

would like to escape the while loop

219:36

after our win conditions? I'm going to

219:39

create a temporary variable. Let's name

219:41

this play again. Then we will ask for

219:44

some user

219:46

input. Play

219:51

again. Y

219:53

slashn meaning yes or no. If the user

219:56

types in something that's capital, I'm

219:58

going to use the lower method to make it

220:00

lowerase. So if our play again variable

220:05

is equal to

220:07

Y, we would like to escape. What I would

220:11

like to do is I would like to see if the

220:13

player types in something that's not Y.

220:16

I will preede this condition with the

220:20

not logical operator. If the user does

220:23

not want to play

220:25

again, then let's take our boolean

220:28

variable running. Normally it's true.

220:31

and set that to be false. Running equals

220:35

false. That means we will escape the

220:37

while loop. Once we escape the while

220:40

loop, I will

220:42

print. Thanks for

220:45

playing. Now, I'm going to change this

220:47

momentarily. I just want to test it.

220:50

Rock. Play again. Yes. Paper. Play

220:54

again.

220:55

Yes.

220:57

Scissors. You lose. Play again. Nope.

221:00

Thanks for playing. This is entirely

221:02

optional. I try and create as few

221:04

variables as possible. I would

221:06

personally rather avoid creating a

221:08

variable here. Another way in which I

221:10

could write this is that I can get rid

221:13

of this

221:18

variable. Let's move if not in front of

221:21

the

221:23

input and follow our input here. Then

221:28

use the comparison operator.

221:31

Then add a colon. If the user's input

221:34

after making it

221:36

lowercase does not equal a Y for yes,

221:41

set running to be false. So that should

221:43

work the

221:45

same. Rock play again. Yes. Enter a

221:49

choice. Paper. Play again. No. Thanks

221:52

for playing. This line would work the

221:55

same, but it's a little more complex for

221:57

beginners to read. or you can use the

221:59

other method that I showed you. All

222:01

right, everybody. Well, that's a game of

222:03

rock, paper,

222:05

scissors. Hello everybody. Today, we

222:08

will be creating a dice roller program

222:10

in Python. We will be utilizing some ASI

222:13

art. I'll post all of the ASI art that

222:15

we'll need in the description of this

222:17

video. You can copy and paste it to save

222:19

time if you'd like. All right, let's get

222:21

started, everybody. We will begin by

222:24

importing the random module because we

222:26

will be rolling some random numbers

222:27

between 1 through six. If we're going to

222:30

create some ASI art, we'll be utilizing

222:32

Unicode characters. To enter in a

222:34

Unicode character, it really varies

222:36

depending on your operating system. I

222:38

think the easiest way would just be to

222:40

use Python. To enter a Unicode

222:42

character, type a forward slash, then a

222:44

given code for each character. Here are

222:47

all of the codes that we'll need.

222:58

After writing these seven unic code

223:00

characters, let's run this program.

223:03

These symbols that are output, let's

223:04

copy them. I'll add them to a comment.

223:08

Then we can delete this line. These are

223:11

the unic code characters we'll need to

223:13

build some ASI art, some dice. Each die

223:16

will be made out of five lines.

223:21

Let's begin with the first. We'll need a

223:23

left

223:24

corner, nine

223:27

dashes, then the right

223:30

corner. For the second

223:32

line, copy this vertical bar. Add nine

223:38

spaces. Then a vertical bar. We can copy

223:42

this whole line. Paste it two times.

223:46

Let's use the left bottom corner. Add a

223:49

nine of these

223:52

dashes. Then the bottom right

223:55

corner. And here's a basic box shape.

223:58

Depending on what the number die is, we

224:00

can add one of these bullet points. For

224:02

a one, we can add that right to the

224:03

middle. So that's good for now. We'll

224:06

delete this later. Let's create a

224:07

dictionary. I will name this dictionary

224:11

dice art. Our dictionary is made out of

224:15

key value pairs. So the keys will be the

224:18

numbers 1 through six beginning with

224:21

one. The value will be a tpple. It's a

224:25

dictionary made out of key value pairs

224:28

where the value is a tpple. Within the

224:31

tpple, let's add these lines each

224:34

separated with a comma.

224:47

I'm going to format these so they form a

224:49

box

224:52

shape. Let's take our bullet point,

224:55

place it right in the middle, then add a

224:58

comma to the end of this key value pair.

225:00

That is the first key value pair. Let's

225:03

copy all of

225:04

this. Paste it again. Change one to two.

225:08

Let's move this bullet point. We need

225:10

two bullet points about right here and

225:14

here. Let's repeat this process for keys

225:17

three through six.

225:43

Be sure to get rid of the comma at the

225:45

end. And here is our dictionary of dice

225:48

art. Each key is a number. Each value is

225:52

a tuple made of

225:54

strings. Let's create a list of dice.

225:58

Our dice will be numbers randomly

226:00

generated between 1 and six.

226:04

a total to calculate the total. I'll set

226:06

that to be

226:07

zero. Then we will ask a user for a

226:10

number of

226:13

dice. This will be some

226:16

input. How many

226:20

dice? Then type cast the input as an

226:23

integer. We don't want somebody to

226:25

write, you know, 2.5 dice. You can't

226:28

roll half a dice. To generate a random

226:30

number, you can use the rand int method

226:32

of the random

226:34

module. We need a random number between

226:37

one and six. Then we need to append this

226:40

number to our list of dice.

226:45

dice.append. Then we can move this line

226:47

to within the append

226:50

method. We need to do this a number of

226:52

times depending on how many dice the

226:54

user enters in.

226:56

We can place this line within a for loop

226:59

for

227:01

every die in our

227:05

range number of dice. This will be a

227:08

number. Let's print our list of dice to

227:11

see what numbers we have in here. How

227:14

many dice? I would like five dice. 5 3 3

227:17

4

227:18

6. Okay, we know that that works. Let's

227:20

calculate a total. We'll need to iterate

227:24

and sum all of the elements within our

227:26

list. We can do that with the for

227:29

loop. For every die in our list dice,

227:35

take our total variable plus equals the

227:40

current value within our

227:42

dice. Then we will print a total. I'll

227:46

use an fstring total colon

227:49

space. Our total

227:52

variable. Let's see what we have so

227:56

far. How many dice? I would like five

227:58

dice. Our total is 19. Now between these

228:02

two for loops, we will display our ASI

228:05

art. The easiest way would be to create

228:07

some nested for loops. The outer for

228:10

loop will be in charge of the number of

228:13

dice for every

228:16

die in our

228:18

range number of dice.

228:24

The inner for loop will be in charge of

228:27

printing every

228:30

tpple. For every line in then to get a

228:36

value in our dictionary, we would type

228:37

the name of the dictionary dice art then

228:41

use the get

228:42

method. What are we getting? We're

228:45

getting a value at a given key. Let's

228:48

take our list of numbers dice at

228:52

index of die our

228:55

counter. Depending on what the user

228:57

types in for the number of dice, die

228:59

will begin at one then

229:01

increment within the inner for loop. We

229:05

will print the line. So let's take a

229:09

look. How many dice I would like? Three

229:12

dice. And here's our asky art. 6 + 2 + 4

229:16

that equals

229:17

12. If you would prefer, we can display

229:21

all of these dice on a single horizontal

229:24

line instead of one vertical line. It's

229:26

a little more tricky though. If you

229:28

would prefer that approach, let's turn

229:30

this chunk of code into

229:33

comments. We will write this nested loop

229:36

a little

229:37

different. So each tpple is made up of

229:40

five elements, right?

229:43

So, if we're printing a horizontal

229:45

line, let's say we roll the numbers 1

229:48

through three, we would first need to

229:50

display this line of the first dice,

229:54

then the first line of the second dice,

229:56

then the first line of the third dice.

229:59

During the next iteration of the outer

230:01

loop, we would display the second line

230:03

of the first dice, the second line of

230:06

the second dice, the second line of the

230:08

third dice. So, it's a little more

230:11

complex.

230:12

Let's create an outer loop that will

230:14

iterate five times. For every line in

230:18

range

230:21

five, then the nested loop will be for

230:23

every die in

230:28

dice. How many dice do we have within

230:30

our

230:33

list? We will print. We're going to get

230:36

one of the values found at one of the

230:38

numbers that we roll.

230:42

take our dictionary of dice

230:45

art. Get then a number 1 through

230:49

six. That will be the value found within

230:52

our list of dice. Get the current die.

230:56

Remember that this is a number 1 through

230:58

six. We would then need one of the

231:00

elements found within our tpple. So get

231:03

the first line, then the second line,

231:06

third, fourth, fifth.

231:11

So let's add the index

231:13

operator. Place our counter of line

231:16

within the index operator. Let's see

231:18

what we have so

231:19

far. We need to add one more thing. How

231:22

many dice?

231:24

Three. This is an abomination. There's

231:27

one more change we need to

231:30

make. At the end of our print statement,

231:32

let's set the ending character to be an

231:35

empty

231:36

string. And that should fix that. How

231:39

many dice? Three. Okay, we're getting

231:41

better results. Then when we escape the

231:44

inner loop, we will print a new

231:47

line. How many dice?

231:49

Three. And there we are. 3 + 6 + 1 is

231:54

10. All right, everybody. So, that is a

231:57

dice roller program. It is kind of

231:59

complex, but I thought this might be a

232:01

good exercise. If you would like a copy

232:03

of this code, I will post all of this in

232:04

the comment section down below. And

232:06

well, yeah, that's a dice roller program

232:08

in

232:11

Python. Hey everybody, today I need to

232:14

explain functions. Think of a function

232:16

as a block of reusable code. To invoke a

232:19

function, you place a set of parenthesis

232:21

after the function name. To invoke it,

232:24

here's a scenario. I need to sing happy

232:26

birthday three times. I know it's a

232:28

weird example, but it makes a lot of

232:30

sense. Just trust me on this. If I need

232:32

to sing happy birthday three times, I

232:34

would write something like this. I'm

232:36

going to create my own version of the

232:38

happy birthday

232:45

song. This is one verse. If I need to

232:48

repeat this code three times without

232:50

using functions, I could either repeat

232:52

this code or maybe place it within a

232:56

loop. So, here's my happy birthday song

232:58

three times. But there's a better way of

233:00

handling this that doesn't involve

233:02

repeating our code or using loops. What

233:05

if I could write this code once then

233:08

reuse it whenever I need to? That's

233:10

where functions come in. To define a

233:12

function, you would type def then a

233:15

unique function name. Let's name this

233:17

function the happy birthday function.

233:20

Add a set of parenthesis a colon. Any

233:23

code that belongs to the function you'll

233:25

want to indent underneath. Then to

233:28

invoke this function, I would type the

233:31

name of the function, happy birthday,

233:33

add a set of

233:34

parenthesis, and that's

233:36

it. When you invoke this function, you

233:39

will execute this code once. If I need

233:42

to execute this code three times, I

233:44

would just call it two more

233:46

times. Happy birthday. Happy birthday.

233:48

Happy birthday. To invoke a function,

233:50

you type the function name, then add a

233:52

set of parenthesis. I like to think of

233:54

the parenthesis as a pair of telephones

233:56

talking to each other. You call a

233:58

function to invoke it. Hey, happy

234:00

birthday function. Execute your code.

234:02

With functions, you are able to send

234:04

data directly to a function using what

234:07

are known as arguments. You can send

234:09

values or variables directly to a

234:11

function. Place any data within the set

234:13

of parenthesis. I'll send my function a

234:15

first name. Any data you send a function

234:18

are known as arguments, but you need a

234:21

matching set of parameters that are in

234:23

order. What exactly is the data we're

234:25

sending in? Well, it's a name. I will

234:27

add one parameter to my happy birthday

234:29

function. I will name this data name. A

234:33

parameter is kind of like a temporary

234:35

variable that's used within a function.

234:37

I'm going to replace this instance of u

234:40

with a name. I will use an

234:43

fstring. Replace U with a placeholder. I

234:46

will add my parameter name. So, happy

234:50

birthday to bro. We could pass in some

234:53

other names. What about

234:57

Steve

234:58

and

235:01

Joe? Here we are. Happy birthday to bro.

235:04

Happy birthday to Steve. Happy birthday

235:06

to Joe. When you invoke a function, you

235:09

can send more than one argument. Let's

235:11

send an age this time. I'll send 20,

235:16

30, and 40. But when I run this, we have

235:21

an error. We're passing in two

235:23

arguments, but our function is set up

235:26

only to take one. I would need a

235:28

matching number of arguments. To invoke

235:30

this function, we will need two

235:32

parameters. We have a name and we have

235:35

an

235:36

age. Then let's use this age. You are.

235:40

Let's make this line an F string.

235:44

age years old. Let's try that

235:49

again. Happy birthday to bro, you are 20

235:53

years old. Happy birthday to Steve, you

235:55

are 30 years old. Happy birthday to Joe,

235:57

you are 40 years old. When you invoke a

236:00

function, you can pass in some data.

236:02

Those are known as arguments, but you'll

236:04

need a matching set of parameters. The

236:06

order does matter. Let's see what

236:08

happens when I switch these two

236:10

parameters. age then

236:14

name. Happy birthday 220, you are bro

236:17

years old. Happy birthday 230, you are

236:20

Steve years old. Happy birthday 240, you

236:23

are Joe years old. So the position of

236:26

the parameters does matter. Same thing

236:28

goes with the arguments. You also could

236:31

name these parameters something unique.

236:33

Maybe X and Y. Happy birthday to X. You

236:37

are Years old.

236:39

That's also valid. Let's try another

236:42

example. I'm going to create a function

236:44

to display an

236:48

invoice. There will be three parameters,

236:50

a

236:51

username, an amount, and a due

236:57

date. Let's print hello. I should make

237:02

this an F string.

237:08

username. We'll use another

237:12

fing your bill

237:16

of

237:18

amount. Let's precede this placeholder

237:21

with the unit of currency. I will also

237:24

add a format

237:25

specifier

237:27

2F is

237:30

due on our due date. whatever that

237:33

parameter is. To invoke this function,

237:36

we will type the function's name, add a

237:38

set of parenthesis, a username, an

237:41

amount, and a due

237:43

date. Let's make up some username, an

237:46

amount, I guess

237:48

$42.50. I'm just making up a number

237:51

here. Then a due date, the 1st of

237:55

January, I guess. Here's my invoice.

237:57

Hello, bro code. Your bill of $42.50 50

238:00

cents is due on January 1st. Let's

238:03

change these arguments. Joe Schmo is the

238:06

username. He owes $100 and one penny.

238:11

Due on the 1st of February or January

238:14

2nd, depending on how you read dates in

238:16

your region. Hello, Joe Mo. Your bill of

238:20

$1001 is due on 1/2. That's another

238:24

example. Now, we need to explain the

238:26

return statement. Return is a statement

238:28

that is used to end a function and send

238:31

a result back to the caller. Here's an

238:34

example. We have a variable Z. Z will

238:37

equal we'll invoke a function to add two

238:40

numbers together such as the numbers 1

238:43

and two. When we invoke a function, we

238:46

can send some data back. After adding 1

238:49

and two, we will send the result which

238:52

would be three. Then this value can be

238:54

assigned to a variable. then we can

238:57

print whatever Z is. So let's create

238:59

some functions. Let's create a function

239:01

to add two numbers together. The

239:04

parameters will be X and

239:07

Y. Let's say Z

239:10

equals X + Y. Then we will

239:15

return our value Z. So I'm not going to

239:18

print Z directly right

239:20

now. Let's subtract X and Y.

239:25

Subtract Z = X - Y. Return

239:30

Z.

239:33

Multiply X *

239:38

Y then

239:44

divide. X / Y return Z. Let's invoke our

239:48

add function. Pass in two numbers, one

239:51

and two. Then I'm going to print the

239:55

result. After adding these two numbers

239:58

together, the result is

240:00

three. What about

240:03

subtract? Subtract 1 and two. The result

240:07

is

240:08

-1.

240:12

Multiply. The result is

240:15

two. Then

240:18

divide. 1 / 2 is 0.5. After we resolve

240:23

this function, a value is returned. Just

240:26

imagine that after we finish this

240:27

function, this function becomes whatever

240:29

is returned three. This function becomes

240:33

-1. This function becomes two. This

240:36

function becomes

240:39

0.5. Let's write something a little more

240:42

complex. We will create a function to

240:45

create a full name.

240:47

Create name. We'll need two parameters

240:51

for a first name and a last name. I'll

240:53

name these first and

240:55

last. What do we want to do within this

240:57

function? Let's capitalize the user's

241:00

first name. First equals first dot

241:04

capitalize

241:05

method. Then do the same thing with the

241:08

last

241:09

name. Last equals last. capitalize.

241:15

Then I'm going to return the user's

241:17

first name plus their last name. Then

241:20

I'll add a space in between their first

241:21

and last

241:23

name. This is also valid. Outside of the

241:26

function, let's create a full name

241:29

variable. Then invoke the create name

241:32

function. So this function is going to

241:34

capitalize the first and last name for

241:36

us. I'll type in my first name all

241:39

lowercase. Same thing with my last name.

241:43

Then let's print our full

241:47

name. And here is my full name variable.

241:50

We sent our function some arguments. We

241:53

have some parameters set up. We took

241:55

those values, made them uppercase, then

241:57

concatenated these strings together,

241:59

then returned them as a single string.

242:01

Let's try this with a different name.

242:05

Spongebob

242:09

Squarepants. Spongebob now has a full

242:11

name. The first and last names are now

242:13

capitalized. Using the return statement,

242:16

you can return some data back to the

242:18

place in which you call a function.

242:20

Well, everybody, that's a function. It's

242:23

a section of reusable code. To call a

242:26

function, you type the function's name,

242:28

add a set of parenthesis. You can send a

242:30

function some data, which are known as

242:32

arguments, but you'll need a matching

242:35

set of parameters. You also do have the

242:37

option of returning some data back to

242:39

the place in which you invoke a

242:41

function. We'll be using functions a lot

242:43

in the future, but we will get more

242:44

practice with them. And those are

242:46

functions in

242:49

Python. Hey everybody, today I'm going

242:51

to explain default arguments. Default

242:54

arguments are a default value for

242:57

certain parameters. The default is used

242:59

when that argument is omitted when you

243:01

invoke a function. In the last topic, we

243:04

discussed positional arguments. Today,

243:06

we will be examining default arguments.

243:09

Then in future topics, we'll examine

243:11

keyword and arbitrary arguments. Let's

243:13

begin. Let's define a function to

243:16

calculate net

243:17

price. There will be three parameters.

243:20

An original list

243:22

price, a discount if there is one, and

243:26

sales tax.

243:30

We will return a net price. And here's

243:33

the

243:34

formula. List price

243:37

times 1 minus our discount

243:42

percentage times 1 + our sales tax.

243:48

Maybe I'm buying a PlayStation 5 for

243:51

$500. I will pass in 500 for the list

243:54

price. Well, I can't actually execute

243:57

this function without also passing in an

243:59

argument for discount and tax. Perhaps

244:02

the discount is zero and the sales tax

244:04

is 5%.

244:07

0.05. Well, this would work. And I

244:09

should probably put this within a print

244:11

statement so you can see

244:13

it. There we are. My total is

244:16

$525. The list price of $500, no

244:19

discount, and 5% sales tax. Now suppose

244:22

that maybe 90% of the time when we're

244:26

executing this function, most of the

244:27

time discount is zero and our sales tax

244:30

is almost always the same. What we could

244:33

do to make this function a little more

244:35

flexible is to set these two parameters

244:37

to have a default value. In place of

244:39

sending in three arguments, we can pass

244:42

in one. Then set our discount and our

244:44

tax to have a default value. So I will

244:47

set discount to be zero and tax to be

244:51

0.05 meaning 5%. So this function would

244:55

work. Our total is

244:57

525 and that's assuming that our

245:00

discount is zero and our tax is 5%. The

245:03

nice thing about using default arguments

245:05

is that let's say that somebody has a

245:07

discount. Well, this function would also

245:09

accept up to two additional

245:12

arguments. So, let's

245:14

print our net

245:17

price 500 and our customer has a coupon

245:21

for 10% off. I'll add a second argument

245:23

of

245:26

0.1. If we're passing in an argument for

245:29

our discount, we'll use whatever is

245:31

passed in rather than the default. Our

245:33

total now is

245:36

$472.50. Or maybe this

245:38

time they are not paying sales tax. I

245:42

will set the sales tax to be

245:44

zero. Now the customer's total is

245:47

$450. So that's kind of the nice thing

245:49

about default arguments. It makes your

245:51

functions more flexible and it can

245:53

reduce the number of arguments,

245:55

especially if the arguments that you're

245:56

passing in tend to be consistent. Most

245:58

of the time people don't have a discount

246:00

and almost everybody is paying 5% sales

246:03

tax. Why pass in arguments we don't have

246:05

to? Let's cover an exercise. We'll

246:08

create a count up timer. We will import

246:11

the time module. We will define this

246:14

function. Define count. There will be

246:18

two arguments start and

246:23

end. For X in

246:27

range,

246:29

start comma end. Within the range

246:33

function, the second argument is

246:35

exclusive. So I'm going to add one to

246:38

the end of our

246:39

time. Then I will print x. To make this

246:44

thread that's running the program sleep,

246:45

you can access the time modules sleep

246:48

method. Pass in one for 1 second. Then

246:52

outside of the for loop, let's print the

246:54

word

246:56

done. To invoke this function, I need to

246:59

pass in two arguments, a start time and

247:02

an end time. I'll set the start time to

247:05

be zero. the end time to be 10. 10

247:08

seconds. So, we start at zero, then we

247:11

will increment by one every second. I'll

247:14

speed up the video. I think you get the

247:15

idea, but we'll stop at

247:20

10. Let's assume that most of the time a

247:23

user would like to begin at zero. Well,

247:25

we don't necessarily need to pass that

247:27

in as an argument. Let's set our start

247:29

parameter to have a default value of

247:31

zero.

247:33

We only need to pass in one argument.

247:36

But we do have a problem. Non-default

247:38

arguments should follow default

247:41

arguments. So if you use any default

247:44

arguments, you'll want to be sure that

247:46

they're after any positional arguments.

247:49

So let's reverse

247:50

these. And that should

247:52

work. So now when I run this program,

247:55

it's assuming we'd like to start at

247:58

zero, but we'll need to pass in an

248:00

ending amount of seconds. When do we

248:02

want to

248:04

stop? That works the same, but now we do

248:07

have the option of starting at a

248:09

different number. This time let's end at

248:12

30, but we will begin at

248:16

15. We're beginning at 15. Then we will

248:19

count to 30. I'll speed up the

248:26

video. There we are. All right,

248:28

everybody. So in conclusion, default

248:30

arguments they are default values for

248:33

certain parameters. The default value is

248:35

used when an argument is omitted. They

248:38

can make your functions more flexible

248:40

and reduce the number of arguments you

248:41

have to pass in especially if those

248:43

arguments are consistent most of the

248:45

time. So those are default arguments and

248:47

in the next topic we will discuss

248:49

keyword arguments and well yeah those

248:52

are default arguments in Python.

248:56

Hey friends, it's me again. Today I'm

248:58

going to explain keyword arguments. A

249:01

keyword argument is an argument preceded

249:03

by an identifier. It has a few benefits.

249:06

It helps with readability and the order

249:08

of the arguments doesn't matter if

249:10

they're keywords. Keyword arguments are

249:12

one of four basic styles of arguments.

249:15

We discussed positional, default, then

249:17

next we'll discuss arbitrary, but today

249:19

we'll be focusing on keyword. Suppose I

249:22

have a function to display a message

249:24

like a greeting. I will name this

249:26

function the hello function. We will

249:29

need a

249:30

greeting, a title, Mr., Mrs., doctor, a

249:36

first name, then a last name.

249:39

All I'm going to do within this function

249:41

is print anstring. I will

249:44

print my

249:47

greeting the user's

249:51

title, first

249:54

name, last

249:55

name. Then to invoke the hello function,

249:59

I will need to pass in four arguments. A

250:02

greeting, a title, a first name, and a

250:04

last name. So for my greeting, let's

250:08

say hello. The title will be

250:13

mister. The first name will be

250:16

Spongebob. Last name

250:20

Squarepants. So you know this does work.

250:23

We're currently using positional

250:24

arguments. The position of these

250:26

arguments does matter. So what if I were

250:29

to switch these around? We have hello

250:32

Spongebob Squarepants followed by

250:34

mister. Hello Spongebob Squarepants

250:37

mister. An optional feature when sending

250:40

arguments to a function is that we could

250:42

turn these into keyword arguments.

250:45

Prefix any arguments with the name of

250:46

the parameter followed by equals. Title

250:50

equals

250:51

mister first equals

250:54

Spongebob. Last equals Squarepants. Then

250:57

with these keyword arguments, the order

250:59

really doesn't matter. Maybe we move the

251:02

first name to the

251:04

end. And the still would print out is

251:07

the same thing. We have title, first

251:09

name, last name. If you're mixing and

251:11

matching positional arguments and

251:13

keyword arguments, you want to be sure

251:15

that the positional arguments are first.

251:17

So if I was to move the string, our

251:19

greeting to the

251:22

end, well, this technically wouldn't

251:24

work. We have a syntax error. Positional

251:27

arguments follow keyword arguments. So,

251:29

make sure any positional arguments are

251:31

first before using any keyword

251:33

arguments. Two helpful benefits of using

251:36

keyword arguments is that it helps with

251:38

readability and the order of the

251:40

arguments doesn't matter. We know what

251:41

this argument is as well as these two

251:44

title, last name, first

251:46

name. Let's say we have a first name and

251:50

a last name. John James.

251:56

These two names kind of sound like first

251:58

names. Is our first name John or is it

252:00

James? We could use keyword arguments to

252:03

clarify which is which. You thought John

252:06

was the first name, but it's actually

252:07

the last name and the first name is

252:11

James. Then our title is still the

252:13

same. Hello, Mr. James John. Let's cover

252:17

another example.

252:19

I'm going to print the numbers 1 through

252:21

10 using a for loop for x in range 1, 11

252:28

because the second argument is

252:30

exclusive. Then I will print

252:33

x. After each print statement, we print

252:36

a new line. Do you remember in previous

252:38

topics how we would follow our print

252:40

statement with comma and then a new

252:44

character such as a space? While end is

252:48

a keyword argument found within the

252:50

built-in print statement, in place of

252:53

ending each print statement with a new

252:55

line, we are using this keyword argument

252:57

of end and sending it to be a

253:00

space. Another one is separate that's

253:02

found within the print

253:04

statement. Maybe we have some

253:07

numbers. They're all separate

253:12

strings. The numbers 1 through 5. I can

253:15

use the separate keyword argument then

253:18

separate each of these strings with a

253:20

given character or characters. I will

253:22

separate each of these strings with a

253:25

dash. A lot of built-in functions such

253:28

as the print function. They have some

253:30

keyword arguments you can use. Let's go

253:33

over an exercise

253:34

now. We're going to create a function to

253:37

generate a phone number, but we'll need

253:39

to pass in a country code, area code,

253:42

the first three digits, and the last

253:43

four digits. Let's define this function

253:45

as define get phone to get a phone

253:50

number. We have a country

253:53

code area

253:56

code first meaning first few digits then

254:00

last meaning last few digits. We will

254:03

return an

254:05

fstring. We will place our country code

254:09

first dash then our area

254:13

code dash the first few digits dash the

254:19

last few

254:21

digits my phone number phone num equals

254:25

I will invoke the get phone number

254:27

function we just created but we'll need

254:30

a country

254:32

code an area

254:35

code. First few digits, then last few

254:39

digits. And remember, the order doesn't

254:41

necessarily matter. Usually, I try and

254:44

be consistent with the order of the

254:46

parameters. Make up a phone number. I'm

254:48

in the United States. My country code is

254:51

1. Area code 1 2

254:54

3. The next few digits will be 456. The

254:57

last few will be

254:59

7890. Then let's print this phone

255:01

number. print phone

255:05

num and here is my phone number.

255:08

Although you can change it up based on

255:10

how you do phone numbers in your

255:11

country. This is typically how you would

255:13

see a phone number in the United States.

255:15

All right, everybody. So those are

255:17

keyword arguments. They are just

255:19

arguments preceded by an identifier that

255:22

matches the name of a function's

255:24

parameters. It does help with

255:26

readability and the order of the

255:27

arguments doesn't matter. When invoking

255:30

a function, it could be helpful to

255:32

identify some of these arguments. And

255:34

well everybody, those are keyword

255:35

arguments in

255:39

Python. Hello friends, it's me again.

255:41

Today I need to explain arbitrary

255:43

arguments. Arbitrary meaning a varying

255:46

amount of arguments. We don't know how

255:48

many arguments the user is going to pass

255:50

in when they invoke a function. To

255:51

accept a varying amount of arguments,

255:54

developers tend to use these parameters

255:55

of args and quarks. Args means

255:59

arguments. Quarks means keyword

256:01

arguments. You would want to prefix each

256:04

of these parameters with the unpacking

256:06

operator, which is an asterisk. When you

256:08

invoke a function that has args or

256:10

quarks as parameters, you will pack all

256:13

of those arguments into a tpple if it's

256:16

args or a dictionary if the parameter is

256:18

quarks. Let's go over an example. I will

256:21

create a function to add two numbers

256:24

together.

256:25

define add function there will be two

256:29

parameters a comma b all I'm going to do

256:33

is return a +

256:37

b I will invoke this function pass in

256:40

two arguments because we have two

256:41

parameters set up one 2 then I'm going

256:45

to print the

256:48

result big surprise there my function

256:50

return three all right well what if I

256:53

would like to pass in three parameters

256:55

this time. Well, I can no longer use

256:58

this function. The add function takes

257:00

two positional arguments, but three were

257:03

given. I could modify this function so

257:05

that it could accept a varying amount of

257:07

arguments, any amount. I'm going to

257:10

replace the parameters with asterisk

257:13

then the word args meaning arguments. So

257:16

when we use the unpacking operator,

257:18

what's going to happen now is that with

257:20

the arguments that we pass into this

257:22

function, we will pack them all into a

257:24

tpple. And if you don't believe me,

257:26

let's test it. I'm going to print the

257:30

type of args. Then I'm going to remove

257:33

this print statement for

257:35

now. My parameter args is a tpple that I

257:38

could work with. We can use the built-in

257:40

methods of this tpple or we could

257:42

iterate over it.

257:44

I'm going to iterate over this tpple for

257:47

every arg in args for every argument in

257:53

arguments. What we'll do is create a

257:55

variable named total to keep track of

257:57

the

257:58

total. Total plus equals the current arg

258:02

that we're iterating over. Then at the

258:05

end I will return the

258:07

total. Let's print the result. Print.

258:11

Add these three numbers together. There

258:13

we are. My total is six. Then we can

258:16

pass in any amount of arguments. Four

258:18

this time, maybe

258:21

five or even

258:24

one. With my parameter args, you can

258:27

change this name to something else like

258:29

nums meaning numbers for every num in

258:35

nums. Total plus equals num. This would

258:39

work too. The name of the parameter

258:41

isn't as important as the unpacking

258:43

operator. Just by typical naming

258:45

conventions, people tend to stick with

258:47

args. But the parameter name can vary.

258:51

Let's try a different example. Let's

258:53

create a function to display somebody's

258:55

name. Display

258:58

name. We will accept a varying amount of

259:01

arguments. Use the unpacking operator.

259:04

Then follow the unpacking operator with

259:06

the unique parameter name. For every arg

259:10

in

259:12

args, let's print each

259:15

argument. Then replace the ending

259:17

character of my print statement with a

259:19

space. Now sometimes people can have a

259:23

varying number of names in their full

259:25

name. There can be a first name, middle

259:27

name, last name, maiden name, a title,

259:29

etc. So, I'm going to pass in just a

259:33

first name and a last

259:35

name.

259:38

Spongebob

259:41

Squarepants. If I need to add a middle

259:43

name, I can do that. Spongebob Herald

259:48

Squarepants or a

259:50

title Dr. Spongebob Herald

259:56

Squarepants. The third

260:00

Yeah, as I was saying with the unpacking

260:03

operator followed by a unique parameter

260:05

name, you can pack all of these

260:08

arguments into a tuple which you can use

260:11

within this function. Now let's discuss

260:14

quarks. You use two unpacking operators.

260:17

Then typically people follow this with

260:19

the word quarks meaning keyword

260:22

arguments. It allows you to pass

260:24

multiple keyword arguments which we

260:26

discussed in the last topic. I think

260:28

this would be great for an address.

260:31

Define print address

260:36

function. Use double asterisks. Then we

260:40

can add a parameter name, but people

260:41

usually stick with quarks, meaning

260:44

keyword arguments. Just as a

260:46

placeholder, I'm going to type pass.

260:48

Pass doesn't do anything. I want this

260:50

program to be able to run. We'll get

260:52

back to this function momentarily. I'm

260:54

going to invoke this function. print

260:58

address. Then pass in multiple keyword

261:01

arguments. With an address, you would

261:03

typically have a

261:06

street, a

261:09

city, state. Depending on what country

261:13

you live in, you may have more or less

261:14

of these keyword arguments. I live in

261:16

the United States. We have a state. Then

261:20

a zip

261:21

code. Okay. My street will be I'm just

261:24

making something up here. One, two,

261:26

three. Fake

261:28

street. City will be

261:32

Detroit, state,

261:35

Michigan. Zip

261:37

code 5 43 2 1. Just to make this look

261:41

better, I'm going to place each of these

261:42

keyword arguments on a new line. For me,

261:45

that's just more readable, but you do

261:47

you. When I pass in these keyword

261:49

arguments, we will pack them into a

261:52

dictionary. Just to prove it, let's

261:54

print the type of

261:58

quarks. Look at that class

262:02

dictionary. Within this function, you

262:04

can treat quarks as if it's a

262:06

dictionary. There's a lot of built-in

262:08

methods. Or we could iterate over the

262:10

keys, the values, or both. to iterate

262:13

over the values. Let's say for every

262:15

value in our dictionary quarks dot

262:20

values

262:22

method print every

262:26

value. Here's all the values for the

262:30

keys. Let's change this for loop to be

262:32

for every key in quarks keys method

262:38

print every

262:40

key. Here are the keys for both. You

262:43

could say for every key, value in quarks

262:48

do items method print every key.

262:52

Actually, let me turn this into an F

262:54

string. Print every

262:57

key

262:59

colon

263:03

value. The items method will return key

263:06

value pairs. We can pass in a varying

263:09

amount of keyword

263:11

arguments. I'm going to add an apartment

263:14

number. Apartment equals

263:21

100. Our keyword argument of apartment

263:24

was packed into a dictionary along with

263:26

all these other keyword arguments. So

263:28

that's kind of nice. We can pass in a

263:30

varying amount of keyword arguments.

263:32

Let's cover an exercise. We're going to

263:34

use both args and quarks together.

263:38

We will print a shipping label. Define

263:42

shipping label function. The parameters

263:45

will be both

263:47

args, quarks. Then just for now, I'm

263:50

going to write pass just so that this

263:53

program will work for now. We'll fill in

263:55

the shipping label function momentarily.

263:57

When we invoke the shipping label

263:59

function, we will first pass in any

264:02

positional arguments followed by keyword

264:04

arguments. and it won't work the other

264:06

way around. I'll prove that in a little

264:09

bit. So, let's say we have

264:13

Dr.

264:16

Spongebob

264:19

Squarepants the

264:22

third. Then I'll add my keyword

264:24

arguments. I'm going to put this on a

264:26

new line. Street equals 1 2 3 fake

264:30

street.

264:34

Apartment equals

264:38

100. City equals

264:44

Detroit. State equals

264:49

Michigan. Zip equals 543 2

264:54

1. When we invoke this function, we have

264:57

a mix of arbitrary positional arguments

265:00

and arbitrary keyword arguments. This

265:03

shipping label function is designed to

265:06

accept both. You do need args first

265:08

followed by quarks. This program will

265:11

run. But if we have it the other way

265:13

around, quarks followed by

265:16

args, it's not going to function

265:18

properly. You can see that we have a

265:20

syntax

265:22

error. With your parameters, make sure

265:24

that your keyword arguments follow your

265:27

positional arguments. Let's iterate over

265:29

the positional arguments first. For

265:32

every arg in

265:35

args, let's print each

265:38

arg. Then I will change the ending

265:41

character of my print statement to be a

265:43

space. Here's the name of the user who

265:46

we're shipping something to with the

265:48

shipping label

265:50

function. I will print a new line. Then

265:53

we will iterate over all the keyword

265:55

arguments. For every value in my

266:00

dictionary quarks dot values

266:04

method, I will print each

266:08

value. Then I will change the ending

266:10

character of my print statement to be a

266:14

space. All right, it's not looking too

266:16

bad so far.

266:18

If you were to remove some keyword

266:20

arguments or some positional

266:22

arguments, this should work still, which

266:25

it does. I'm going to change the format

266:28

of this address slightly. Let's add our

266:30

street on one line, then the city,

266:34

state, and zip code on the next line.

266:36

Let's get rid of this for

266:39

loop. To print the street, I'm going to

266:41

print use an F string. add a

266:46

placeholder

266:48

quarks.get method. I'm going to get the

266:51

street key. With this get method, you'll

266:54

probably need to place them within

266:56

single quotes because if you use double

266:58

quotes, Python gets confused as to where

267:00

this fring ends. We will use single

267:03

quotes. Let's test it. All right, we

267:06

have a street. On the next line, we will

267:09

print the city, state, and zip.

267:13

print ft string placeholder

267:19

quarks.get within single quotes the

267:24

city I'll add another

267:27

placeholder

267:31

quarks.get

267:33

state then

267:38

quarks.getzip. Let's see what we have.

267:41

All right, not too bad.

267:44

What if the user has an apartment

267:45

keyword? Apartment equals number

267:51

100. Well, we should probably add that

267:53

too. Within this top print statement, I

267:56

will add another

267:58

placeholder. Invoke the get method of

268:01

the dictionary. The key we are looking

268:03

for is

268:05

apartment Dr. Spongebob Squarepants 23

268:08

Fake Street, apartment number 100,

268:10

Detroit, Michigan

268:12

54321. What if our print statement is

268:14

set up to display a street and an

268:16

apartment, but the user doesn't have an

268:20

apartment? This would display none, and

268:22

we don't want that. I'm thinking what

268:25

we'll do is we'll place this print

268:27

statement within an if

268:29

statement. What we'll check is

268:34

if apartment

268:36

in

268:40

quarks. If there's an apartment key in

268:43

quarks, our dictionary, then print this

268:48

line. Else we will

268:52

print just the

268:57

street. The person doesn't have an

269:00

apartment. We won't print the apartment

269:01

then. But if they do have an apartment,

269:04

apartment equals number

269:08

100, then we will 123 Fake Street,

269:11

apartment number

269:12

100. Here's a challenge round. What if a

269:15

user has a PO box? Let's change

269:18

apartment to PO

269:21

box. The string will be PO box number

269:26

100,1. I suppose I'll add an else- if

269:30

statement. else

269:33

if PO

269:36

box in our dictionary

269:40

quarks. Let's print the street. I'll

269:43

copy this line, paste

269:46

it, followed by a second print

269:51

statement.

269:53

Quarks.getp

269:57

box. There we are. Dr. for Spongebob

270:00

Squarepants 123 Fake Street PO Box 10001

270:04

Detroit Michigan

270:06

54321. All right, everybody. Those are

270:08

arbitrary arguments. When you invoke a

270:10

function, you can pass in a varying

270:12

amount of arguments. Set up your

270:14

parameter to be args for a varying

270:17

amount of non-keyword arguments or

270:19

quarks for a varying amount of keyword

270:22

arguments. You can set up both in your

270:24

parameters, which we did for this

270:26

exercise. And well everybody those are

270:28

arbitrary arguments in

270:32

Python. Hey everybody. So today I got to

270:35

talk about iterables in Python. An

270:38

iterable it's a category. Any object or

270:41

collection that can return its elements

270:43

one at a time is considered an iterable.

270:46

If an object or a collection is

270:48

considered an iterable, then it can be

270:50

iterated over in a loop. For example,

270:53

let's create a list of numbers.

270:55

numbers equals a list. I'll add the

270:58

numbers 1 through 5 to keep it simple.

271:00

Lists are considered iterable. We can

271:03

use them within a for loop. In the

271:06

context of a for loop, we're going to be

271:08

given each element one at a

271:11

time. Each element that we're working

271:13

with, we can give a temporary nickname.

271:16

Let's say number. For every number in my

271:20

iterable of numbers, let's just print

271:23

each

271:26

number. This will give us 1 through

271:29

5. The name of the current element in

271:32

our iterable should be descriptive of

271:34

what we're iterating over. For example,

271:36

I don't want to rename the current

271:38

number that we're working with as

271:39

something like blah blah blah.

271:43

You know, this would work, but other

271:44

people looking over your code might not

271:46

understand what a blah blah blah is, and

271:48

I don't blame them. Each element that

271:51

we're given from our iterable, the name

271:53

should be descriptive of what we're

271:55

given. Or you might see item. For every

271:59

item in numbers, print each

272:01

item. That's also a good

272:04

choice. Now, you could even iterate

272:06

backwards by enclosing our iterable

272:09

within the reversed function.

272:12

So take our iterable of numbers and

272:15

reverse it. Then we get the numbers 5 4

272:18

3 2 1. If you would rather not print

272:22

each element on a new line, we can

272:24

replace the new line character at the

272:25

end of print statements with something

272:27

else. Print is a function. We can pass

272:30

in a keyword argument of end. Rather

272:32

than end each line with a new line

272:34

character, let's end with a

272:37

space. This will space out each of the

272:39

elements. Or we could replace it with

272:41

something else. Or what about a

272:44

dash? After each element, append a dash

272:48

character. We could even add multiple

272:50

characters such as a space, a dash, and

272:53

a space if we so

272:55

choose. It's up to

272:57

you. Tpples are also

273:00

iterable. Let's convert our list to a

273:02

tpple by enclosing our numbers within a

273:04

set of

273:06

parenthesis. And I no longer want this

273:08

reversed.

273:10

For every number in my iterable of

273:13

numbers, print each number. Then again,

273:16

we get the numbers 1 through

273:18

5. Let's cover

273:21

sets. I will create a set of fruit,

273:24

which I will name

273:25

fruits. For a set, enclose any values

273:28

within a set of curly braces. Let's add

273:30

a string of apple, a string of orange, a

273:36

string of

273:37

banana, and a string of

273:40

coconut. So with our for loop, let's say

273:43

for every fruit in my iterable of

273:47

fruits, I will print each

273:50

fruit. That would give me apple, banana,

273:53

orange,

273:54

coconut. Now sets, they're actually not

273:57

reversible. I will attempt to enclose

274:00

our iterable of fruits within the

274:02

reversed

274:03

function. Here's what happens. We have a

274:06

type error. Set object is not

274:09

reversible. Sets you can't

274:12

reverse. Let's cover strings. I will

274:15

create a string of name. Type in your

274:18

full name. I'll use my YouTube channel

274:21

name. For every character in my iterable

274:25

of name, I would like to print each

274:32

character. Maybe I would rather not have

274:35

each character end with a new line. I

274:37

will set the keyword argument of end to

274:40

be a

274:43

space. Last, we have dictionaries, which

274:45

are the most complicated. Let's name

274:48

this dictionary my dictionary.

274:51

Dictionaries you enclose with a set of

274:53

curly braces, kind of like a set, but

274:56

each element is a key value pair. I will

274:59

add a key of A with an associated value

275:02

of 1, a key of B which has a value of

275:07

two, a key of C which has a value of

275:12

three. If you iterate over a dictionary,

275:15

the dictionary is going to return all

275:17

the keys but not the values. We'll test

275:20

that. For every key in my iterable of my

275:25

dictionary, let's print each

275:28

key. This would give me the keys of A,

275:31

B, and C, but none of the values 1 2 or

275:36

three. If you need the values, we're

275:39

going to follow this iterable of my

275:41

dictionary, use the built-in values

275:44

method.

275:46

This will return all the values of your

275:48

dictionary as an iterable. But let's

275:51

rename a key as value because now we're

275:54

working with the

275:56

values. Then we're given all the values

275:59

1 2 and three. If you need both the keys

276:03

and the values, you're going to use the

276:05

items

276:07

method. We'll be given both a key and a

276:11

value. Make sure that the value and the

276:13

key is separated with a comma.

276:16

Let's print each key followed by the

276:19

value. We get the key of A with its

276:23

value of 1 B 2 C 3. We can reformat the

276:29

output however we want. Let's use an F

276:32

string. I will add two placeholders.

276:35

Let's print each key equals then the

276:40

value A equals 1, B= 2, C= 3. Okay,

276:46

everybody. So those are iterables. An

276:48

object or a collection that can return

276:50

its elements one at a time is considered

276:52

an iterable. Meaning that object or

276:55

collection can be iterated over using a

276:58

loop. And well everybody, those are

277:00

iterables in Python.

277:05

Hello again. So today I got to talk

277:07

about membership operators in Python.

277:09

They are the operators in and not in.

277:12

They're used to test whether a value or

277:14

a variable is found within a sequence

277:17

which include but are not limited to

277:19

strings, lists, tpples, sets, or

277:22

dictionaries. Here's an example. I'm

277:25

going to create a word, a secret word.

277:28

Let's say

277:29

apple. I'm going to turn this into a

277:32

game. I will have a user guess a letter.

277:35

I will accept some user

277:38

input. Guess a

277:40

letter in the

277:43

secret

277:46

word. What I would like to do is check

277:48

to see if my letter is found in my word.

277:52

I can write the following statement. if

277:56

our letter in our

277:59

word in is going to return a boolean

278:02

value of true if that letter is found or

278:05

false if it's not. So if our letter is

278:08

found I'm going to print the following

278:10

statement. I'll use an f string. There

278:14

is a add a placeholder insert our

278:20

letter else. Let's

278:23

print. I'll use an F

278:25

string. Our

278:27

letter was not

278:31

found. Let's test this. Guess a letter

278:34

in the secret word. I will guess a

278:36

capital A. So all these letters are

278:39

uppercase. Do take note of that. Is

278:42

there an A?

278:43

There is an A. Let's guess a letter

278:46

that's not within this word, such as Z.

278:50

Z was not found. The in membership

278:53

operator will test to see if a value or

278:56

a variable is found within a sequence.

278:59

If it is, it returns true. If not, it

279:02

returns false. Or for the inverse, you

279:04

could say not in. If letter is not in

279:08

Word, we would have to flip these

279:10

statements around.

279:19

If this value or variable is not found

279:22

in this sequence, it returns true,

279:25

otherwise false. So, it does the

279:27

opposite of in. Guess a letter in the

279:29

secret word. Is there an E? There is an

279:33

E. Is there a Q? Q was not found.

279:38

Depending on the statement you're trying

279:39

to write, you can use either in or not

279:41

in, whichever makes more sense in that

279:44

context. Let's go over another example.

279:47

We were searching for a value or a

279:49

variable found within a string. Let's

279:52

try a set. List tpples and sets are

279:54

going to behave similarly. I will create

279:57

a set of

279:59

students. For a set, you need a set of

280:01

curly braces. Let's add a few student

280:04

names such as

280:06

Spongebob,

280:08

Patrick, and

280:12

Sandy. I will have a user. Type in a

280:15

student to search

280:17

for. We will accept some user

280:20

input. Enter the name of a student.

280:26

We're going to check if our student is

280:31

in our sequence of

280:34

students. If in returns true, let's

280:37

print the following. I'll use an f

280:40

string. Insert our

280:42

student is a

280:47

student. Else we will print. I'll use an

280:51

fstring.

280:53

Insert that

280:56

student was not

280:59

found. Enter the name of a

281:02

student. Let's search for Spongebob.

281:04

Spongebob is a student. Enter the name

281:07

of a student. Let's attempt Squidward.

281:10

Squidward was not

281:12

found. And much like the first example,

281:16

we can do the opposite. See if a value

281:18

or a variable is not in a sequence.

281:22

We would have to switch these statements

281:28

around. Enter the name of a student. Is

281:31

Sandy a student? Sandy is a student.

281:35

Enter the name of a student. Is Larry a

281:37

student? Larry was not

281:40

found. Now we'll cover dictionaries. I

281:43

will create a dictionary of grades.

281:46

Student grades like a grade book.

281:49

Let's say that the student of

281:51

Sandy, she will be a key has a value of

281:57

A.

282:00

Squidward, the key of Squidward has a

282:03

value of

282:05

B. Spongebob, he is also a

282:09

key. Spongebob has a grade of

282:13

C. Then Patrick.

282:16

Patrick has a grade of

282:22

D. Here is my dictionary of

282:26

grades. Then we'll search for a student.

282:30

Student equals

282:33

input. Enter the name of a student.

282:38

We'll check if let me close this. If our

282:43

student is found within

282:45

grades, then I will print the

282:48

following. We're looking for keys. Is

282:51

there a matching key? If we find that

282:53

student, I'll make this an F

282:55

string. Let's display the associated

282:58

value of that key.

283:03

student

283:05

students grade is I'll add a

283:09

placeholder. Once we find a student, we

283:12

have to get that value at the given

283:15

key. To do that, we'll take our

283:17

dictionary of grades at index of

283:21

student. This will retrieve the value at

283:24

a given

283:25

key. If we don't find a student, we'll

283:28

output the following. Again, I'll use an

283:33

fstring.

283:34

Student was not

283:37

found. So now, if I search for a student

283:40

such as Spongebob, we're given a grade.

283:43

We're given the value at that key that

283:46

we're searching

283:48

for. Let's test Sandy. Sy's grade is A.

283:54

Squidward. Squidward's grade is B. And

283:58

Patrick.

283:59

Patrick's grade is D. But Larry is not a

284:02

student. If I search for him, well,

284:05

Larry was not

284:07

found. Let's go over one last

284:11

example. We're going to create a

284:13

variable of email. It's going to be a

284:15

string. Type in whatever your email is.

284:21

Brocodegmail.com. I would like to see if

284:23

this email is valid. Does it contain at

284:26

and a period? I will write if our value

284:31

of at that character is in our

284:37

email and a period is an

284:41

email. We have two conditions. Check if

284:44

at is an email and check if a period is

284:47

an email. If so, it's a valid email.

284:51

Then we'll

284:52

print valid email.

284:57

else we will

284:59

print invalid

285:03

email is my email valid that email is

285:08

valid I'll get rid of the

285:11

at invalid email I'll get rid of the

285:15

period following

285:18

Gmail that email is also

285:21

invalid in this example we're checking

285:24

two

285:25

conditions If this value is found within

285:28

this sequence and this value is found

285:30

within this sequence. All right

285:33

everybody. So those are membership

285:35

operators in and not in. They will

285:38

return a boolean based on whether a

285:41

value or a variable is found within a

285:43

sequence which include but are not

285:45

limited to strings, lists, tpples, sets

285:48

or dictionaries. And well everybody

285:51

those are membership operators in

285:53

Python.

285:56

Hey, what's going on everybody? So, in

285:58

today's video, I got to explain list

285:59

comprehensions in Python. A list

286:01

comprehension is a concise way to create

286:04

lists in Python. They're compact and

286:07

easier to read than traditional loops.

286:09

Basically, you have to follow this

286:11

formula. For every value in something

286:14

that's iterable, meaning you can loop

286:16

through it, check some condition, then

286:18

do this expression. So, let me give you

286:20

an example with using a traditional

286:22

loop. then you'll be able to see why a

286:24

list comprehension is useful. We're

286:26

going to create a list and double the

286:28

numbers 1 through

286:30

10. Doubles equals an empty list. Using

286:34

a traditional for loop, we will say for

286:38

every value, let's say x in range 1

286:43

through 11. Remember that in the range

286:45

function, the second number is

286:47

exclusive. This will give you the

286:49

numbers 1 through 10. For the first

286:51

iteration, x is going to be 1, then two,

286:54

3, all the way up until 10. So, we'll

286:57

iterate 10 times. During each iteration,

287:00

I'm going to take my list of doubles,

287:03

use the built-in append method, we will

287:06

append x. During each iteration, that's

287:10

going to be the value times two. So, if

287:13

I were to print my list of doubles,

287:17

here's the result.

287:19

We have the numbers 1 through 10 all

287:21

doubled. 2 4 6 8 10 12 14 16 18 20. So

287:26

this is a lot to write. We can use a

287:29

list comprehension to make this code

287:31

more compact and easier to read. Here's

287:34

how. We need a name for this list. Let's

287:37

say doubles equals an empty list. Within

287:40

our list, we'll follow this formula.

287:45

We have an expression for value in

287:49

iterable and optionally we can check a

287:51

condition. We'll do this in exercises

287:53

later on in this topic. We'll begin with

287:56

for every value let's say x in our

288:00

iterable. Our iterable is going to be a

288:04

range 1 through 10. Again for the first

288:08

iteration x will be 1. Then the second

288:11

iteration x will be two all the way up

288:13

until 10. During each iteration, what

288:16

would we like to do with x, our value?

288:19

Let's take x, multiply it by two, and

288:22

return

288:23

it. Then, if I was to print my list of

288:27

doubles, we have the numbers 2 4 6 8 10

288:30

12 14 16 18 20. For every value in this

288:34

iterable, do this. Multiply it by two.

288:38

This is a list comprehension. It's a

288:40

concise way to create lists in Python.

288:42

We'll go over a few

288:44

exercises. So this time we will triple

288:47

each number. We'll create a list of

288:50

triples equals let's say this time for

288:53

every y in

288:56

range 1 through 10. So we have to write

289:00

11 take y and multiply it by three. Then

289:06

we will print our list of triples 3 6 9

289:10

12 15 18 so on and so forth. Let's

289:12

square each

289:14

number. We'll create a list of squares

289:17

for every Z in range 1 through

289:23

10. To square a number, we take that

289:25

number, multiply it by itself.

289:30

So the numbers 1 through 10

289:33

squared is 1 4 9 16 15 36 49 64 81 100.

289:40

So 10 * 10 is 100. Now we're going to

289:43

work with

289:44

strings. We'll create a list of fruits.

289:48

Equals. Let's think of some fruit. These

289:50

are all going to be strings. Apple,

289:54

orange,

289:56

banana, coconut.

289:58

I'm going to take each string in this

290:00

list and make it

290:02

uppercase. We could assign this to a new

290:04

list such as uppercase

290:07

fruits or we can simply just reassign

290:10

it. Just to keep it simple, I'll

290:12

reassign

290:13

it. So again, we're following this

290:15

formula. I like to begin with the four

290:18

value in iterable portion. For every

290:21

fruit in our iterable of fruits, what do

290:26

we want to do?

290:28

Well, let's take each fruit. Take each

290:30

fruit. Use the built-in upper method to

290:32

make it

290:34

uppercase. Then I'm going to

290:36

print my list of

290:40

fruits. Each string in this list is now

290:42

all uppercase. You could even cut down

290:45

on one of the steps. With our iterable

290:48

of fruits, I will place this

290:54

list. And this does work too. Although I

290:57

do find this a little more difficult to

290:59

read, but you can take either option.

291:02

How about instead of making each string

291:04

uppercase, we'll take the first letter

291:07

of each string, then put it within a new

291:09

list. So let's take each fruit at index

291:13

of zero. That will give us the first

291:15

letter. We'll place it within a new list

291:19

of fruit chars, meaning

291:23

characters. Here's the result. A O B C.

291:27

For every fruit in our list of fruits,

291:30

return the first character of each

291:33

string. A O B C. Now we'll work with

291:40

conditions. We'll create a list of

291:42

numbers both negative and positive.

291:45

numbers equals let's say 1 -2 3 -4 5

291:53

-6. We'll create a list comprehension to

291:56

create a new list where all of the

291:58

numbers are positive. Our new list will

292:01

be positive nums equals we'll write a

292:05

list

292:06

comprehension for every let's say num in

292:12

numbers we'll write a

292:15

condition return this number if our

292:19

num is greater than or equal to zero. We

292:23

do need an expression if we're not

292:25

modifying each value. we can just return

292:29

the value of

292:31

num. During this exercise, we're more

292:33

focused on the if condition rather than

292:36

the expression. If our value of num

292:39

meets this condition, simply return it

292:41

and place it within this new

292:43

list. Let's print our list of positive

292:47

numbers. And we have

292:51

135. Let's do this with negative

292:53

numbers. I'll just copy what we have and

292:55

change a few things around. This list

292:57

will be negative numbers. Negative

293:00

nums. For every num in numbers, check

293:04

this condition. Check to see if num is

293:07

less than zero. If so, return that

293:09

number. Let's print our list of negative

293:12

numbers. -2, -4,

293:16

-6. Let's check to see if there's any

293:18

even numbers.

293:21

Even nums equals for every num in

293:26

numbers check to see if our num is

293:31

divisible by two. And we can do that

293:33

with the modulus operator followed by

293:35

two. The modulus operator will give you

293:38

the remainder of any division. If our

293:40

number is even, number modulus 2 will

293:43

equal zero. If it's even, this is going

293:46

to equal zero. If it's odd, it's going

293:48

to be one. We're not modifying our

293:51

value. We're just going to return our

293:55

number. Our list of even numbers should

293:58

be -2, -4,

294:00

-6. Let me add one more value. Let's add

294:05

positive

294:06

8 -24 -6 pos 8. Maybe we'll add one

294:12

more.

294:14

-7. Okay, let's find any odd numbers.

294:18

Let's copy this line of code. Replace

294:20

even numbers with odd

294:23

numbers. If num modulus 2 is equal to

294:27

1, that means that number doesn't divide

294:30

by two evenly, then we'll print our odd

294:34

numbers. 1 3 5 - 7. All these numbers

294:39

are odd. Here's the last

294:43

exercise. We'll create a list of grades.

294:48

We'll create a new list of any grades

294:50

that are considered passing, meaning

294:52

they scored 60 or above. So, let's say

294:55

one student has a grade of 85, another

294:58

with a

295:00

42,

295:01

79,

295:03

90,

295:06

56,

295:09

61, let's say

295:11

30. I will create a new list of passing

295:15

grades.

295:17

Equals again follow this

295:19

formula for every grade in

295:24

grades. Check our condition. If our

295:27

grade is greater than or equal to 60, we

295:32

will return the current

295:36

grade. Then let's print our list of

295:39

passing grades. That will give us 85,

295:43

79, 90, and 61. All of these grades are

295:48

greater than or equal to 60. All right,

295:51

everybody. So, that is a list

295:52

comprehension. It's a concise way to

295:55

create lists in Python. They're compact

295:57

and easier to read than traditional

295:59

loops. Remember, for every value in your

296:03

iterable, optionally, you can check a

296:05

condition. You can write an expression

296:07

to modify that value if you choose and

296:10

return something. All right everybody.

296:12

So those are list comprehensions in

296:16

Python. Hey everybody. So today I'm

296:18

going to explain match case statements

296:20

in Python. If you're familiar with other

296:23

programming languages, this is also

296:25

known as a switch. Match case statements

296:27

are alternatives to using many else if

296:30

statements.

296:32

We execute some code if a value matches

296:36

a case. The benefits of using a match

296:38

case statement is that they're cleaner

296:40

and the syntax is more readable. In this

296:43

sample program, I have a function. There

296:45

is one parameter, a day. Day will be a

296:48

number, ideally a number 1 through 7.

296:51

Depending on this number, we'll return a

296:53

string corresponding to the day of the

296:55

week. If day equals 1, then it is

296:59

Sunday.

297:02

two, it is Monday all the way up to

297:06

7 where it will be Saturday. I do have

297:10

an else clause if we pass in something

297:12

that's not valid like

297:15

pizza. Pizza is not a day, but it really

297:18

should be not a valid day. A cleaner and

297:21

more readable alternative is to use a

297:24

match case statement instead of many

297:26

else if statements. Here's how. I'm

297:29

going to take my if and many else if

297:31

statements and enclose them within a

297:34

match

297:36

case. Match case. The case is going to

297:40

be the value we're examining. The case

297:43

will be day

297:45

colon. We're going to examine our value

297:48

of day against matching

297:51

cases. We're going to replace if day

297:55

equals with the following. just simply

297:59

case. So let's do that with each of

298:01

these

298:12

statements. If you have an else clause,

298:15

you're instead going to have a case of

298:18

underscore. An underscore in a match

298:20

case statement is a wild card. We will

298:23

perform this case if there are no

298:25

matching cases.

298:27

This case would function as the else

298:29

statement. Here's what we're working

298:31

with. Now, if I pass in one and return

298:34

the day of the week, we would get

298:38

Sunday. 2 would be Monday. 3 Tuesday.

298:45

7 is Saturday. And then let's try that

298:48

day of

298:50

pizza. That is not a valid day. A match

298:53

case statement is an alternative to

298:56

using many else if statements. I find

298:58

this much easier to read than the many

299:00

else if statements. Both would

299:02

technically function. Let's go over a

299:04

second example. We will create a

299:06

function of is

299:09

weekend. We have to pass in a day. This

299:13

time our day is going to be a string

299:15

such as

299:16

Monday. The value for each case instead

299:19

of a number is going to be a string.

299:23

If our day matches a case of

299:25

Sunday, let's return how about a boolean

299:29

of true. We're checking to see if it's

299:32

the weekend. If our day is equal to a

299:36

case of Monday, then we will return

299:40

false. Let's do this with the other

299:42

days. I'm going to fast forward the

299:44

video.

300:03

We will call the function of is weekend

300:06

then pass in a day of the week such as

300:08

Monday. So is Sunday the weekend? That

300:13

is true.

300:15

Monday that is false.

300:20

Saturday. That is true. And we do have a

300:23

wild card case. If there are no

300:25

matches, is pizza a day of the weekend?

300:29

That is false. There is a way we can

300:31

modify this match case, too. We tend to

300:34

be repeating ourselves a lot. The days

300:36

Monday through Friday all return false.

300:39

We're going to use the or logical

300:40

operator, which is represented with a

300:43

vertical bar. If the case of

300:48

Saturday or Sunday return

300:51

true. If the case is

300:54

Monday or

300:57

Tuesday, we can get rid of that.

301:01

or

301:05

Wednesday or

301:12

Thursday or

301:17

Friday then we will return

301:20

false. We can keep our wild card

301:23

case. So is

301:26

Saturday part of the weekend that is

301:29

true. is

301:32

Monday false

301:35

Sunday true

301:40

Friday

301:41

false and

301:44

pizza we have our wild card case that

301:47

gives us false. All right everybody so

301:49

those are match case statements. They're

301:52

similar to switches in other programming

301:53

languages. They're an alternative to

301:56

using many else if statements. We

301:58

execute some code if a value matches a

302:01

case. The benefits is that the code is

302:04

cleaner and the syntax is more readable.

302:07

And well everybody, those are match case

302:09

statements in

302:12

Python. Hello friends, it's me again.

302:14

Today I'm going to explain modules. A

302:17

module is just a Python file containing

302:19

code you want to include in your

302:21

program. You use the import keyword to

302:23

include a module. You can use built-in

302:26

modules or create your own. Sometimes

302:28

it's useful to break up a large program

302:30

into reusable separate files. For a list

302:33

of all the modules found within the

302:34

standard Python library, you can use the

302:36

help function, pass in the word modules,

302:39

and then we would need to print

302:44

this. Here are many of the different

302:46

modules available to you. A few you may

302:49

recognize would be math, string, time.

302:52

One of my favorite names of a module is

302:54

the pickle module. Unfortunately, it

302:56

doesn't have anything to do with

302:57

pickles. It's used for serialization. To

302:59

list all of the different variables and

303:01

functions found within a module, you can

303:03

place that name of the module within the

303:05

help

303:06

function. For example, with the math

303:08

module, here are a few different

303:10

variables we would have access to and a

303:12

few different

303:14

functions. To include a module, we would

303:16

type import the name of the module, for

303:19

example, math. I now have access to

303:21

everything found within the math module,

303:24

including those variables and functions.

303:26

To access those variables and functions,

303:28

I would normally type the name of the

303:30

module dot the name of the variable or

303:32

function such as pi. Then let's print

303:35

this. Pi from the math module is 3.14

303:41

and some change. Another way to import

303:43

is to type import the name of the module

303:47

as. You can give your module a nickname,

303:50

an alias, whatever you think of such as

303:53

M. M short for math. We would no longer

303:55

refer to this module as math. We would

303:58

refer to it as our alias

304:02

M. Using an alias would reduce some of

304:05

the typing you have to use. If you have

304:06

a very long module name, another way to

304:09

import is to use from the name of the

304:12

module. Import something specific. PI

304:15

for instance, you would no longer need

304:17

the module

304:20

name. From math import pi, pi would be

304:23

included within our name space. However,

304:25

I tend to not use from import as much

304:28

just because it's possible there could

304:29

be name conflicts. Here's an example.

304:32

Let's say from math import E. E is an

304:35

exponential

304:38

constant. E is

304:40

2.71. What if I was to create a program

304:43

where we have four variables named A, B,

304:46

C, D. A = 1, B = 2, C = 3, D= 4. Then

304:53

I'm going to print E from the math

304:56

module to the power of

304:59

A. That would give me 2.71.

305:03

Then let's do this with B, C, and

305:06

D. E to the power of B, E to the power

305:09

of C, E to the power of D. Here are the

305:12

results. Let's say we have a different

305:14

variable E. E will be

305:18

five. Then I will

305:20

print E to the power of E. We have

305:24

imported E from the math module. When we

305:27

have declared all of these variables,

305:29

technically what we've done is we have

305:31

created another version of E. We will

305:33

end up using the second version rather

305:35

than the version that we have imported

305:37

from the math module. All my results are

305:40

now different and it's possible you may

305:42

not realize it. I like to be more

305:44

explicit. I'm going to import math. If

305:47

I'm using a variable or function from a

305:49

module, I much prefer to prefix that

305:52

variable name or function with the name

305:54

of the module in which it's from. math.

305:57

E to the power of A to the power of B to

306:00

the power of C to the power of D. Math E

306:03

to the power of our variable

306:06

E. And these results are to be expected.

306:10

Now to create a module, what we're going

306:12

to do is right click on our project

306:14

folder, go to new Python file, think of

306:18

a module name, maybe example, then click

306:21

Python

306:22

file. We now have two tabs. main and

306:26

example. Declare whatever you would like

306:28

within this module. Let's create our own

306:30

variable pi. pi=

306:34

3.14159. Then a few functions. Let's

306:36

create a function to square an argument

306:39

that's passed in. Define square. We will

306:42

accept an argument which we will name x.

306:46

Then return x to the power of two. Let's

306:51

define a cube function. We will accept

306:53

one argument. Then return x to the^ of

306:58

3. Maybe a circumference function.

307:01

Define

307:02

circumference. We will accept a

307:05

radius. Then return 2 * * radius.

307:11

Then an area function to calculate the

307:14

area of a circle. We will accept a

307:16

radius as an argument. Then return pi *

307:21

radius to the power of 2.

307:25

All right, here is our example module

307:28

within our main Python program. Let's

307:30

import the name of our module which we

307:32

named example. We now have access to

307:35

everything within this

307:37

module. I'm going to declare a variable

307:39

result and set it to the name of my

307:44

module.py. Then I will print the

307:47

result which is

307:50

3.14159. Let's utilize the square

307:53

function. result equals example

307:57

dosquare. Let's square

308:00

three which is

308:02

9. Let's use the cube

308:06

function that would be

308:08

27.

308:13

Circumference that would give me

308:17

18.8. Then

308:19

area that would be 28.2.

308:23

That's how to create your own module. It

308:25

can be useful at times to separate your

308:27

program into individual files. All

308:29

right, everybody. In conclusion, a

308:31

module is just a file containing code

308:33

you want to include in your program. You

308:35

use import to include a module. You can

308:38

use built-in modules or create your own.

308:40

If you do need a list of the modules

308:42

available to you, again, you can use the

308:43

help function, then pass in the word

308:45

modules. And well everybody, that's how

308:47

to get started with modules in Python.

308:51

Hey friends, it's me again. Today I'm

308:53

going to explain both variable scope and

308:55

scope resolution. Variable scope is

308:57

where a variable is both visible and

309:00

accessible. With scope resolution, when

309:02

we're using a variable, there is a

309:04

certain order known as the LEGB rule in

309:07

which we locate that variable. Local,

309:10

enclosed, global, built-in. We'll get to

309:12

this momentarily. Let's begin with

309:14

variable scope. I have two functions,

309:17

function one, function two. within

309:20

function one a equals 1 then we print a

309:23

within function two b equals 2 then we

309:26

print b. If I were to invoke these

309:28

functions let's invoke function one then

309:32

function

309:33

two. We would print 1 then two.

309:36

Variables declared within a function

309:38

have a local scope. Variable a is local

309:41

to function one. Variable b is local to

309:44

function two. within function one. If I

309:46

were to print B and function two, if I

309:49

were to print A, we would run into a

309:52

name error. Name B is not defined. And

309:55

the same thing would apply with A.

309:57

Functions can't see inside of other

309:59

functions. Imagine that we're function

310:01

one. This is our house. We can see

310:04

everything that's going on inside of our

310:05

house, but function two is our

310:07

neighbor's house. We can't see what's

310:09

going on inside of our neighbor's house.

310:11

We have no idea what B is with function

310:14

2. Function 2 has no idea what A is.

310:17

That's where variable scope comes in.

310:19

It's where a variable is visible and

310:21

accessible. Functions can't see inside

310:23

of other functions, but they can see

310:25

inside of their own function. That's why

310:27

we sometimes pass arguments to functions

310:30

so that our functions are aware of them.

310:33

Using this concept, we could create

310:35

different versions of the same variable.

310:37

Let's rename a to be X and B to be X as

310:40

well.

310:41

Then I will print

310:44

x. We have two different versions of x.

310:48

A local version of x found within

310:50

function one and a local version of x

310:52

found within function two. Whenever we

310:54

utilize a variable, we will first look

310:56

to see if there's any local instance of

310:59

that variable. If there isn't, we would

311:01

move to the enclosed scope. With an

311:03

enclosed scope, one example is when you

311:06

have a function declared within another

311:08

function. I'm going to place function

311:10

two within function one. This is allowed

311:13

in Python. This is a more advanced

311:15

concept. We'll cover this more in the

311:17

future. So, I'm going to eliminate this

311:19

print statement. Let's get rid of

311:21

function

311:22

two. At the end of function one, we will

311:25

invoke function two. Like I said, it's

311:28

pretty complex. We won't be using this

311:30

until much later. Within function two,

311:33

if I was to print x, we would use the

311:35

local version where x equals 2.

311:39

If I was to eliminate this variable

311:42

declaration, we would use the enclosed

311:44

version instead where x equals 1.

311:47

There's an order of operations. Use any

311:49

local variables first, then enclosed

311:52

variables. We're printing x within

311:54

function 2. Since x wasn't found within

311:57

the local scope, we would use x within

311:59

the enclosed scope. But like I said,

312:02

that's a more advanced topic. You should

312:04

at least be aware of it. Let's move on

312:06

to the global scope. global meaning

312:08

outside of any functions. I will

312:10

eliminate these variable

312:13

declarations. Within function one, we're

312:15

printing X and within function two,

312:17

we're also printing X. I will declare a

312:20

global version of X where X equals 3. X

312:24

is outside of any functions. When I run

312:27

this program, we're printing three

312:29

twice. Once for function one and once

312:32

for function two. There's no longer a

312:35

local version of X for both of these

312:36

functions. If there were, we would end

312:39

up using these local versions instead.

312:41

Function one prints one, function two

312:43

prints 2. If there's no local version as

312:46

well as no enclosed version, we would

312:49

move on to the global version where X

312:51

equals 3. Last in our order is built in.

312:54

I think what we'll do though is from

312:57

math import E. E is an exponential

313:00

constant. I'm going to print what E is.

313:04

E is

313:06

2.71. E is built in. I will create a

313:09

function to print E. Define function

313:13

one. All I'm doing is printing E. Then

313:16

we should invoke it. Invoke function

313:20

one. If I was to set E to be a different

313:23

value like three, what we're doing

313:26

technically is creating two different

313:28

versions of E. Variables can share the

313:30

same name as long as they're within a

313:32

different scope. We have a built-in

313:34

version of E and a global version of E.

313:37

If I was to print E now, it would print

313:40

my global version because using the

313:42

leggb order, we would first look for any

313:45

local version of E, then enclosed

313:48

version, then global, which we do have

313:50

one of, then lastly builtin. All right,

313:53

everybody. So in conclusion, variable

313:55

scope is just where a variable is both

313:58

visible and accessible. Python has a

314:00

scope resolution order levb. If we're

314:03

using a variable, we will first look in

314:05

the local scope for that variable. If we

314:08

don't find that variable in the local

314:09

scope, we will move over to an enclosed

314:11

scope, then global, then built-in. We

314:15

will have more practice with this in the

314:16

future. And well everybody, that is both

314:18

variable scope and scope resolution in

314:21

Python. Hey everybody. So today I got to

314:24

talk about this if statement. If dunder

314:27

name is equal to a string of dunder

314:30

main. When you see this if statement,

314:32

it's usually followed by a call to a

314:34

function named main or something

314:36

similar. A majority of the driving code

314:38

behind a program is usually found within

314:41

some sort of main method. When you see

314:43

this if statement, basically speaking,

314:45

it means that this script can be

314:47

imported or it can run standalone.

314:50

Functions and classes in this module can

314:52

be reused in other programs without the

314:55

main block of code running. Sometimes

314:56

you would like the functionality of a

314:58

program without executing the main body

315:00

of code. A good example could be a

315:02

library. In a Python library, we would

315:05

like to import some of the useful

315:06

functions such as the math module. But

315:09

if we were to run that library directly

315:11

instead of importing it, we could

315:13

instead display a help page. But if

315:16

we're importing that library, we don't

315:17

necessarily want to display that help

315:19

page only if we're running it directly.

315:21

In many Python scripts, you'll see the

315:23

statement of if done name is equal to

315:26

main. If we're not running this program

315:28

directly, don't do it. In this example,

315:31

we're going to delete our main Python

315:32

script. Be sure to recreate it at the

315:34

end of this topic in case I forget to

315:36

mention that. We will create two new

315:39

scripts. Go to file, new, Python

315:42

file, script one.

315:46

file new Python

315:49

file script

315:52

2. We have to add new run configurations

315:55

for script one and script two. So if you

315:58

go to the top, go to run, edit

316:01

configurations. We will add a new run

316:03

configuration. Select Python. Select a

316:06

new script path to script one. Okay.

316:11

Apply. Again, we have to do this with

316:13

script two. Add

316:16

Python. Select a script path of script

316:19

2. Okay. Apply. Then okay. Using this

316:24

drop-own menu, we can select which run

316:27

configuration we would like. Would we

316:29

like to run our main Python file, but we

316:31

have deleted it. Do we want to run

316:34

script one or script two? For the time

316:37

being, we'll select script one. Within

316:40

script one, if I was to

316:42

print, then call the dur function dur

316:46

meaning directory. Python has all of

316:48

these built-in attributes. If you're not

316:51

familiar with object-oriented

316:52

programming, for now, think of an

316:54

attribute as a variable. Dunder name is

316:57

a special type of variable. Dunder

316:59

meaning double underscore. If I was to

317:02

print what's contained within dunder

317:05

name, we would receive a string of

317:08

dunder main. That's why in a script you

317:11

may see the statement if dunder name is

317:15

equal to a string of dunder

317:19

main. If so, then you usually call a

317:22

function named main to start your

317:24

program. I'm going to undo that. So

317:27

let's import script

317:29

two. From script two,

317:33

import everything. Asterisk means

317:37

everything. Within script two, I will

317:40

print dunder name. And we'll see what's

317:43

within

317:44

it. Again, I'm running script one.

317:49

Within script 2, dunder name is equal to

317:52

a string of script 2, the name of the

317:55

Python script. However, within script

317:58

one, dunder name is equal to a string of

318:02

dunder main. This means I am running

318:04

script one directly. Let's delete this

318:07

import. Then go to script 2. Import

318:10

script one. From script one, import

318:15

asterisk meaning all. We're now going to

318:17

change our run configuration from script

318:19

one to script two. We are running script

318:22

two

318:23

directly. Now dunder name within script

318:26

one is the name of the Python script

318:28

script

318:29

one. Dunder name within script 2 is now

318:33

dunder

318:35

main. So by adding this if statement of

318:38

dunder

318:39

name is equal to dunder

318:43

main we can check to see which file is

318:46

being run directly. If dunder name

318:49

equals dunder main we will call a

318:51

function of main to contain the main

318:54

body of our program. But we need to

318:56

define this function define

318:59

main. Our main function will contain the

319:02

majority of our Python code. anything

319:04

that's not already within a

319:06

function. So let's

319:10

print this is script

319:14

one. Then we'll define another

319:17

function of favorite food. We will have

319:21

one parameter of

319:23

food. Let's print the following message.

319:27

I'll use an

319:28

fstring. Your favorite food is add a

319:33

placeholder. add our parameter of food.

319:36

Within our main function, let's call the

319:38

favorite food function. Pass in your

319:41

favorite food as a string. I'll type in

319:44

pizza. Then let's print the word

319:49

goodbye. We're going to run script

319:52

one. Run it. Here's the

319:55

result. From the top down, all of our

319:58

code is within functions. We skip over

320:00

it because we're not calling it quite

320:02

yet. The first thing we do in this

320:04

program is check this if statement. If

320:06

dunder name is equal to dunder main. Are

320:10

we running this program directly? Which

320:12

we are. We're running script one. If so,

320:14

call the main method to start the

320:16

program. We print this is script one.

320:19

Your favorite food is pizza. Goodbye.

320:22

Now I'm going to go to script two.

320:24

Delete our print

320:26

statement. Change the run configuration

320:28

to script two and run it. Nothing should

320:31

happen. That's good. Now, if we were

320:34

missing this if statement of if dunder

320:36

name is equal to main, then we delete

320:39

our main

320:40

function. Here's what would happen.

320:43

We're importing script one, but we're

320:45

running script two. This is script one.

320:48

Your favorite food is pizza. Goodbye. I

320:51

don't want this code to execute. We're

320:53

not running it directly. That's why we

320:55

have that if

320:57

statement. If under name is equal to

320:59

main. I only want to run this code if

321:02

we're running it

321:04

directly. So what we'll do within script

321:06

2 now is define a

321:08

function of

321:11

favorite drink. There's one parameter of

321:15

drink. I will print use an

321:19

fring your favorite drink is I'll add a

321:24

placeholder. We'll add our parameter of

321:26

drink. Let's print the

321:29

message. This is script

321:33

two. We will call from script one the

321:37

favorite food function. Pass in your

321:40

favorite

321:41

food. This time I'll say

321:43

sushi. Let's call our favorite drink

321:46

function. Favorite drink. I'll pass in

321:51

coffee. Then we will print goodbye.

321:57

Okay, we are running script

321:59

two. This is script two. Your favorite

322:01

food is sushi. Your favorite drink is

322:03

coffee.

322:04

Goodbye. We're running script 2, but

322:07

we're importing the functionality of the

322:10

favorite food function from script one.

322:13

Sometimes from another Python script,

322:14

you want to borrow something, but you

322:16

don't want to run the main body of code

322:18

directly. I just want to borrow this

322:20

function from script one, and that's it.

322:23

Script 2 can be run as a standalone

322:25

program, but I can't import it without

322:27

this body of code running. I can add

322:30

that if statement. If dunder

322:32

name is equal to a string of dunder

322:37

main. If we're running this program

322:39

directly, execute this code. So let's

322:42

call a function of

322:44

main. Define

322:47

main. Then place our main body of code

322:50

within it.

322:52

If I run script 2, we have the same

322:55

message. So by adding this if statement

322:57

of if name is equal to main. This script

323:01

can be run as a standalone program or it

323:03

can be imported. A more practical

323:05

example of this could be a Python

323:07

library. You can import the library for

323:10

functionality. But if you run the

323:11

library directly, you could instead

323:14

display a help page. It is good practice

323:16

to include if dunder name equals dunder

323:19

main. It makes your code more modular,

323:22

helps with readability, leaves no global

323:24

variables, and avoid unintended

323:27

execution. And well everybody, that is

323:29

the purpose of if dunder name equals

323:32

dunder main in Python. Hey, what's going

323:35

on everybody? So in this video, we're

323:37

going to create a very simple banking

323:39

program using Python. This is meant to

323:41

be more of an exercise to get us used to

323:43

working with functions. When creating a

323:45

project, I like to divide that project

323:46

into smaller sections, then handle them

323:48

one at a time. So, we'll do that by

323:50

declaring all the functions we'll need

323:52

first. With a banking program, we'll

323:54

need to show a user their balance. We'll

323:56

define a function to show

324:00

balance. For the time being, I'll write

324:02

pass just as a

324:04

placeholder. We'll need to make a

324:06

deposit.

324:07

Define

324:10

deposit. Make a withdrawal.

324:14

define

324:17

withdraw. Near the end of this project,

324:19

we will be creating a main function and

324:21

placing the main body of our code within

324:23

it. We'll handle that near the end just

324:26

to contain everything. We have our three

324:28

functions with our banking program.

324:29

We'll need to show a balance, make a

324:32

deposit, or make a withdrawal. What are

324:34

some variables we'll need? Well, we'll

324:36

need a balance, which I will set to be

324:39

zero initially. I will also create a

324:42

boolean of is running. This will be

324:45

true. If at any time we set is running

324:48

to be false, we'll exit the

324:51

program. So with the majority of our

324:53

code, we'll place it within a while

324:55

loop. While is running. You can check to

324:59

see if this is equal to true, but since

325:01

this is a boolean, that's not

325:03

necessary. We will just say while is

325:06

running. If is running becomes false,

325:08

we'll exit the while loop. Within our

325:11

while loop, we'll print some sort of

325:12

welcome

325:14

message. Let's print

325:17

banking

325:20

program. Then list some

325:23

options. Let's print

325:26

one,

325:27

show balance.

325:33

Two,

325:39

deposit.

325:40

Three will be

325:46

withdraw. Four will

325:48

be

325:52

exit. Afterwards, we will set a choice

325:55

variable to equal some user input.

326:01

input. Enter your

326:04

choice 1 through 4. We're encouraging a

326:07

user to type in a number 1 through 4 to

326:10

select an option. Do they want to show

326:12

their balance, make a deposit, make a

326:14

withdrawal, or exit? We'll add a few if

326:17

and else if statements. Let's check to

326:20

see if the user's

326:22

choice is equal to one, and that is a

326:25

string of one. Our user input is a

326:28

string data type unless we were to type

326:30

cast it to something else. If our choice

326:32

is equal to one, we will call the

326:34

function to show

326:37

balance. Else if our choice is equal to

326:43

two, we will make a deposit by calling

326:46

the deposit

326:49

function. Else if choice is equal to

326:54

three, we will call the withdraw

327:01

function. Else if choice is equal to

327:04

four, that means we would like to exit.

327:07

So we need to exit this while loop. We

327:09

can do that by setting our variable of

327:11

is running is this program running equal

327:14

to be false to exit. If somebody types

327:18

in some input that's not valid, we can

327:20

handle that with an else

327:22

statement. Else, let's

327:26

print that is not a valid

327:31

choice. Okay, let's see what we're

327:33

working with currently to test

327:34

everything. We haven't written anything

327:36

within these functions yet. Show

327:37

balance, deposit, or withdraw. So, we

327:40

can type one,

327:42

two, three, and four to exit.

327:47

processed finished with exit code zero.

327:50

So we can exit the program. We just have

327:52

to select option

327:53

four. With this else statement, this

327:55

will execute if we type in something

327:57

besides the numbers 1 through 4 because

328:00

there's no other options left. So to

328:02

test that, enter your choice 1 through

328:05

4. Uh I'm just going to type the word

328:07

poo. That is not a valid

328:10

choice. So we know that the else

328:12

statement is working. Once we exit the

328:15

while loop, let's print a

328:19

message that

328:21

says, "Thank you. Have a nice

328:30

day." If I was to type four to exit, we

328:33

should exit the program. Thank you. Have

328:36

a nice day. Let's make that h

328:39

capital. Now, we'll work on our

328:41

functions beginning with show balance.

328:43

Currently, these two variables are

328:45

global. We don't need to pass them as a

328:47

parameter to these functions quite yet.

328:49

We will be enclosing all of this code

328:51

within a main function. We'll handle

328:53

that later, though. So, with show

328:56

balance, all we're going to do is print.

328:58

I'll use an

329:00

fring. Your balance is add a dollar sign

329:06

or other unit of currency of your

329:08

choosing. Add a

329:10

placeholder. our balance

329:12

variable and let's see what we

329:16

have. I will type one to show balance.

329:20

Your balance is

329:21

$0. I'll display our balance with two

329:24

decimal places. After I will add a

329:27

format specifier after balance colon 2f

329:31

will add two decimal places. We covered

329:34

format specifiers in a previous topic.

329:38

So if I were to run this again, type

329:40

one, we show $0 and 0. We're displaying

329:44

two floatingoint decimal

329:46

places. Now we need to make a deposit.

329:48

That will be the next

329:51

function. We will define a local

329:53

variable of amount equals accept some

329:56

user

329:58

input. Enter an amount to be

330:04

deposited.

330:07

Again, when we accept user input, it's a

330:10

string. We'll type cast it to a number,

330:13

a floatingoint number, because we have

330:15

to include dollars and

330:18

cents. We'll add some checks, though,

330:20

after accepting some user input. If our

330:23

amount is greater than zero, we don't

330:26

want anybody to make a negative deposit.

330:31

Let's

330:32

print that's not a valid

330:39

amount. Else we are going to

330:43

return our amount. So this function is

330:46

going to return

330:49

something. So within our else if

330:52

statement, we will take our

330:56

balance plus equals the deposit we're

330:59

being returned with. This will add our

331:01

deposit to our balance. balance plus

331:04

equals

331:05

deposit. Let's try

331:09

it. Let's show our balance. Our balance

331:12

is

331:13

$0. We'll make a deposit of $100.

331:18

Exactly.

331:20

Again, we'll show our balance after

331:22

making the deposit. Your balance is

331:26

$100. Let's attempt to deposit negative

331:29

money. We'll select two to make a

331:31

deposit. We'll deposit

331:36

42069. That's not a valid

331:39

amount. So, we have a problem. We have a

331:42

type error. Unsupported operand for

331:45

float and non type. So within this

331:49

statement, within if within our deposit

331:52

function, we're not returning

331:54

anything. Let's just return zero. We

331:57

have to return something. And within

331:59

this if statement, we didn't return

332:01

anything previously. We'll either return

332:04

zero or return a valid

332:07

amount. Let's try this

332:09

again. Let's make a deposit. I will

332:12

attempt to deposit 42069.

332:17

That's not a valid amount. Our program's

332:20

not crashing. That's good. Now we'll

332:23

attempt to make a valid deposit.

332:27

$501. Then show my balance. Your balance

332:30

is

332:31

$501. Okay, that is the deposit

332:34

function. We'll work on the withdraw

332:36

function.

332:40

Next, we will create a local variable of

332:43

amount. accept some user

332:47

input. Enter amount to

332:51

be

332:54

withdrawn. Our user input is going to be

332:57

a string. We will type cast it to be a

332:59

floatingoint

333:01

number. We need to check to see if our

333:05

amount we're trying to

333:06

withdraw is greater than our balance.

333:10

Users shouldn't be able to withdraw more

333:12

money than what they have in their bank

333:14

account. If the amount is greater than

333:16

our balance that we have, we will

333:21

print

333:23

insufficient

333:27

funds. Else if the amount somebody's

333:30

trying to withdraw is less than

333:33

zero, we will print a different message.

333:39

amount must be

333:41

greater than

333:45

zero else we will return our valid

333:50

amount. So with our if and else if

333:53

statements we do need to return

333:54

something if we take one of these

333:56

routes we will return

334:02

zero. We're not making any

334:06

changes within our else if statement

334:08

where we select choice three. We're

334:10

going to take our balance minus equals

334:14

the withdraw

334:16

amount. Let's test

334:19

this banking program. Let's show our

334:23

balance. Our balance is

334:26

zero. We'll make a deposit of

334:29

$100. Show my balance again. Your

334:32

balance is

334:33

$100. Let's press three to withdraw

334:36

money. Enter amount to be

334:38

withdrawn. One cajillion

334:41

dollar. Insufficient funds. Yeah, no

334:45

kidding. Let's attempt to withdraw money

334:48

again. We shouldn't be able to select a

334:50

negative amount.

334:54

42069. Amount must be greater than

334:57

zero. Let's enter in a valid number.

335:00

This time I would like to withdraw

335:03

$49.99. That has appeared to work. We'll

335:06

show our balance again. Your balance is

335:08

now

335:09

$501. Then we can exit by pressing four

335:12

to

335:13

exit. Thank you and have a nice

335:16

day. The last few changes I'm going to

335:18

make is that I'm going to enclose all of

335:21

this code, our main portion of code

335:23

within a main function just to

335:25

encapsulate all of our variables and

335:27

help with readability.

335:29

We will define a function of main. Take

335:33

all of our code within the main body of

335:35

our program and place it within the

335:37

function. I'm just going to select all

335:39

of it and indent it. At the end of our

335:42

program, we need to call a main function

335:45

to run it. If you're familiar with the

335:48

statement of if dunder name is equal to

335:52

a string of dunder main that means this

335:57

program can be imported or run

335:59

standalone. It is good practice to

336:01

include this if statement. We discussed

336:03

this in the previous video. If we're

336:05

running this program directly execute

336:08

the main function. However, our

336:10

variables of balance and is running

336:13

they're now enclosed within this local

336:14

scope. These other functions have no

336:17

idea what these variables are of

336:19

balance. So we need to pass in our

336:21

balance to those functions of withdraw

336:24

and show

336:27

balance. When we show our balance, we

336:29

have to pass in our variable of balance.

336:32

Same thing with

336:33

withdraw. Then set up those

336:36

parameters. Within show balance, we will

336:38

have one parameter of balance. The same

336:41

thing with withdraw. The last thing I'm

336:43

going to do is add a little bit of text

336:45

decoration around my program just to

336:47

make it look

336:49

nice. So, I will print a bunch of

336:53

asterisks. It's not necessary, but I

336:56

think it'll look nice.

337:05

Let's add some text decoration before

337:07

and after the title of banking program.

337:10

Also before our

337:13

choice. Basically whenever we print

337:15

anything we'll add some text

337:23

decoration. Let's do that with show

337:27

balance our

337:35

deposit and within

337:46

withdraw. Okay, let's run this one last

337:48

time.

337:53

banking program. Let's show our

337:58

balance. Your balance is $0. We'll make

338:01

a deposit.

338:04

$1001. Show our balance again. Your

338:07

balance is

338:09

$1001. We will withdraw money. Enter an

338:13

amount to be withdrawn.

338:16

$1,000. Insufficient funds. Let's try

338:18

that again. Let's withdraw

338:21

$50. Show our balance again.

338:24

$501. Then press four to exit. Thank you

338:27

and have a nice day. All right,

338:30

everybody. That is a simple banking

338:32

program you can write using

338:34

Python. Hey everybody. In today's video,

338:36

we're going to create a beginner's slot

338:38

machine program using Python. This

338:40

project's meant for beginners. So, let's

338:42

get started. When creating a project, I

338:45

like to break up that project into

338:47

different sections, then tackle them one

338:48

at a time. So, with the slot machine,

338:50

what are some of the different functions

338:52

we'll need? Well, we'll need to spin a

338:54

row. We'll define a function to spin row

338:59

as a placeholder. I'll write pass. We'll

339:01

return to this function later. We need

339:03

to display or print the

339:06

row. Print row.

339:12

If somebody gets matching symbols on the

339:14

slot machine, we need to give them a

339:16

payout, we'll create a function to get

339:20

payout. In this function, we'll

339:22

calculate what that payout is going to

339:24

be, but again, we'll get to that later.

339:27

We'll write the majority of our code

339:29

within a main

339:33

function. At the end of this program, I

339:35

will add the if statement of if dunder

339:38

name is equal to a string of dunder

339:43

main. Then we will call the main

339:46

function which drives our code. This

339:48

program can be imported or standalone.

339:50

It is good practice to have this if

339:52

statement. A majority of the code we're

339:54

going to write is going to be within our

339:55

main function. So within our main

339:58

function, let's declare the variables

339:59

we'll need throughout this program. We

340:02

will need a starting balance which I

340:04

will just name balance. We will start

340:06

with 100 as in

340:09

$100. We'll need to display some sort of

340:11

welcome message. Let's print something.

340:15

We will print welcome to let's name our

340:18

game

340:19

Python

340:22

slots. Just for some flavor, I'm going

340:24

to add some text decoration. Just a

340:26

bunch of asterisks.

340:28

I think it'll look cool, but you don't

340:30

have

340:32

to. Let's display our symbols. We're

340:34

going to

340:37

use symbols. I'll add some emojis. We'll

340:41

use emojis in this program in place of

340:43

images. If you're on Windows, you can

340:45

hold down the window key plus semicolon.

340:48

Let's add a cherry. You typically see a

340:51

lot of fruit in slot machines. A

340:56

watermelon. a

341:01

lemon. There's also a lot of bells for

341:04

some reason, but we'll add those. And a

341:10

star. Let me just align

341:19

everything. Let's do a test

341:22

run. Welcome to Python slots.

341:26

Let me make one

341:28

adjustment. Okay, I'm happy with

341:32

that. So, after our welcome message,

341:35

we'll continue playing this game while

341:38

our balance is greater than zero. While

341:41

we still have money, we can continue

341:43

playing. We will print I'll use an

341:47

fstring current

341:50

balance colon space. I'll add a

341:53

placeholder. Pick a unit of currency.

341:55

I'll pick American dollars. Then we will

341:58

display the user's balance. We will

342:01

prompt the user to enter in their bet

342:03

which we will assign to a variable of

342:06

bet. So

342:11

input place your bet

342:15

amount. Let's do a test

342:18

run. Welcome to Python slots. Current

342:21

balance $100. Place your bet amount. We

342:25

won't deduce the bed amount from the

342:27

balance quite yet. I just want to be

342:28

sure that we can enter in something.

342:31

$1. Good. $10.

342:35

$100. What if somebody types in a word

342:38

like pizza? We need to prevent that

342:41

input and correct

342:45

it. We'll check if take our bet. use the

342:50

is digit method. Is our bet a digit? If

342:54

somebody types in a word like pizza, we

342:56

need to tell them that's not valid. So,

342:59

this will return true if our bet is a

343:02

digit. But we're going to use the not

343:05

logical operator. If our bet is not a

343:09

digit, then do this.

343:12

We will

343:14

print please enter a valid

343:19

number followed by the continue keyword.

343:23

The continue keyword will skip the

343:25

current iteration of this loop and start

343:28

from the

343:29

beginning. Let's test

343:33

it. Place your bet amount.

343:36

Pizza. Please enter a valid number. We

343:39

have our current balance again. Place

343:41

your bet amount. I'll type in

343:43

one. Okay, we did not get that message

343:46

of please enter a valid number. This bet

343:49

of $1 is

343:51

valid. So if our bet is a digit, we'll

343:54

convert it to be an integer using type

343:57

casting because when you accept user

343:58

input, it's a string. It has the string

344:01

data type. Let's reassign our bet. Type

344:05

cast our bet as an integer.

344:10

Then we will check to see if our bet is

344:12

greater than our balance. People can't

344:15

bet money that they don't

344:17

have. If the bet is greater than the

344:21

current balance, if bet is greater than

344:23

balance, we will print this message

344:27

instead.

344:29

Insufficient

344:31

funds. Then

344:36

continue. If somebody tries to bet

344:39

negative money or no money, we'll add

344:42

this statement. If bet is less than or

344:45

equal to

344:47

zero, we will

344:50

print bet must be greater than zero and

344:56

continue.

345:01

If all these checks pass, if our bet is

345:03

not a digit, if our bet is greater than

345:06

our balance, or if our bet is greater

345:08

than zero, we will take our original

345:14

balance minus equals our bet to subtract

345:18

it. Let's do a test

345:21

run. Place your bet amount. Pizza.

345:25

Please enter a valid number. I will

345:28

bet one cajillion dollars. Insufficient

345:32

funds. Yeah, no kidding.

345:36

0. Bet must be greater than zero. What

345:40

about $1? Our bet should be subtracted

345:43

from our balance. Let's try 10. We are

345:46

now down to

345:48

89. Let's bet

345:51

$90. Insufficient

345:53

funds. 89. And that has appeared to

345:57

work. Once we subtract our bet from our

346:00

balance, we will call the function to

346:03

spin

346:06

row. This function is going to return a

346:09

list which we will assign to be row. Row

346:13

will be a list. Using the spin row

346:16

function, we have to generate three

346:18

random symbols then return them within a

346:20

list. We'll work on the spin row

346:22

function

346:23

next. Within our spin row function, we

346:26

will declare a list of

346:29

symbols. Add your

346:33

symbols, but these need to be

346:38

strings. Make sure they're all comma

346:40

separated.

346:54

There we go. This is where list

346:56

comprehensions can come in. If you don't

346:59

know what a list comprehension is,

347:01

here's an alternative. We will declare

347:04

an empty list of results. This is an

347:06

empty list. We need a for loop to

347:09

generate three random symbols. We could

347:12

say

347:13

for

347:15

symbol in range three.

347:20

This for loop will iterate three times.

347:23

During each iteration, let's take our

347:25

empty list of results. Use the append

347:29

method. We will append a random

347:34

choice among our

347:37

symbols. So we need to import the random

347:42

module. We'll do so at the

347:45

top. Import random.

347:48

We're telling the random module to pick

347:50

a random choice from this list of

347:53

symbols. Then we will append them to our

347:56

empty list of results. After we escape

347:59

the for loop, we will return our

348:03

results. It's a list. Now, a much better

348:06

option is to use a list comprehension.

348:09

Here's how. It's going to be a lot more

348:12

concise. We will return a list. Within

348:16

the list we will write a list

348:18

comprehension for every let's say

348:22

symbol in range

348:26

three. There is no condition. What do we

348:29

want to return during each

348:32

iteration? Access the random module. Use

348:35

the choice

348:37

method. Then pass in our

348:40

symbols. Symbol isn't used in this

348:42

example. What you may see people do is

348:45

use an underscore as a placeholder.

348:48

Basically, what we're saying is for

348:50

every iteration in range three, return a

348:54

random symbol. That's all we need for

348:56

the spin row

348:58

function. Going back, we have our list

349:00

of row. Afterwards, I am going to print

349:04

it to test it. Print

349:06

row. And we should have three random

349:10

symbols after making a bet. All right,

349:13

it looks like it's

349:16

working. We'll make a few changes

349:20

though. Instead of printing our row, I'm

349:23

going to print the word

349:28

spinning, I will add a new line

349:31

character just to give us some space

349:33

like after this word of spinning. Then

349:35

we will call the print row

349:40

function. We'll pass in one argument,

349:43

our row, that's returned to us after we

349:46

spin the row. So going to our print row

349:49

function, we need to set up one

349:52

parameter, our row that we receive. It's

349:54

going to be a list. One easy way to

349:56

print the elements of a list is that we

349:59

can print pick some sort of separator

350:01

for each item in the list. For example,

350:03

I'll just print a space. With strings,

350:06

there are built-in methods. we will use

350:08

the join method then pass in our list or

350:12

other iterable. Basically what we're

350:14

saying using the join method we're going

350:16

to take our iterable in this case our

350:18

list join each element by a space a

350:21

space character. Here's the

350:25

result. We have three symbols. You could

350:28

join them by a different character. I'll

350:31

add a vertical

350:33

bar. Enter your bet amount $1. Now we

350:36

have a vertical bar between each of

350:38

these symbols. We could include more

350:40

than one character. I'll add a space

350:42

before and after this vertical bar just

350:44

to space things

350:46

out. I think that looks a lot better.

350:50

And you don't have to, but I'm going to

350:51

add some text decoration before and

350:53

after. I'll add a bunch of

350:59

asterisks. Let's see what we're working

351:03

with. Not bad.

351:07

So every time we make a bet, we get a

351:10

new set of

351:12

symbols. Now what if all three symbols

351:14

match? We need to calculate a payout and

351:17

give it to the user cuz well they

351:20

won. So after we print our row, we will

351:23

call the

351:25

get payout function, but we will pass in

351:29

our row. It's a list. And our bet. How

351:33

much did we bet? We will be returned

351:35

with a payout which we will add to our

351:39

balance. Let's go to the get payout

351:45

function. We're sending two arguments to

351:47

our get payout function. A row and a

351:51

bet. We have to check to see if each

351:54

element in our row is all the same. Is

351:57

it all the same character? We can do

351:59

that with an if statement. If our row at

352:03

index of zero, that's going to be the

352:04

first symbol, is equal to

352:08

row at index one, that's the second

352:11

symbol, is equal to

352:14

row at the second index, and that's the

352:17

third symbol. If all three symbols

352:19

match, we have to return the bet

352:22

multiplied. Within our if statement, we

352:25

will add another if statement. I will

352:28

check to see if our row at index

352:31

zero is equal to our first symbol of

352:35

cherry. Be sure to place it within

352:38

quotes because it's a

352:40

string. Now, the reason I'm only

352:42

checking if row at index zero is a

352:44

cherry emoji, all these symbols are

352:46

going to be the same. If we're within

352:48

this if statement, all of these symbols

352:51

are going to match. We only need to

352:53

check one of them. It could be zero,

352:55

one, or two. But I'll just add zero.

352:58

They're all going to be the same

352:59

regardless. If somebody has all

353:01

cherries, we will return their bet times

353:06

three or some other amount. You can make

353:09

the payouts higher or

353:11

lower. Else if row at index zero is

353:15

equal to a

353:19

watermelon, then we will return their

353:22

bet times four. So watermelons are worth

353:26

more than

353:29

cherries. Else if row at index

353:33

zero is equal to a

353:37

lemon, we will return their bet time

353:43

5. Else if row at index zero is equal to

353:49

a

353:52

bell, let's give them time 10. Return

353:56

bet* 10.

354:02

else if row at index zero is equal to a

354:07

star that's worth the

354:10

most. We will return their bet time 20.

354:15

Make sure we're not within our if

354:17

statement anymore. If all three symbols

354:19

don't match within our list, we don't

354:21

want to give the user anything. They

354:23

lost that spin. We will return zero.

354:27

That's all we need for the get payout

354:28

function. Scrolling back down after

354:32

receiving a payout, it's returned to us

354:35

from this function. We'll check to see

354:37

if our payout is greater than zero. That

354:41

means they want to spin. I will

354:45

print. I'll use an F

354:48

string.

354:49

U1 I'll add a placeholder. Proceed this

354:52

with a unit of currency. I'll use

354:54

dollars. will display the

354:58

payout. Else if they did not receive a

355:01

payout, that means they lost that spin.

355:04

We will

355:05

print sorry you lost this

355:11

round. Then take our

355:14

balance. This is our original balance.

355:17

Plus equals our payout. In most cases,

355:20

the payout is going to be zero. But if

355:23

the user wins something, we will add

355:24

that to the balance. Okay, let's do a

355:27

test

355:29

run. I will bet $1. Sorry, you lost this

355:33

round. And my current balance is

355:35

99. Let's bet

355:38

again. I'll just keep on doing this

355:40

until I

355:42

win. We're going to lose more times than

355:45

what we win.

355:52

Okay, see I got all bells. It says you

355:55

won $10. Once somebody runs out of

355:58

money, we want to stop them from playing

356:00

or if they would like to exit. We'll

356:02

create a variable of play

356:05

again. We will accept some user

356:09

input. Do you want to spin again?

356:17

We'll add y for yes slashn for

356:23

no. If our variable of play again does

356:26

not equal a character of capital y, then

356:31

we will break to break out of this loop.

356:34

Let's do a test run. Enter your bet

356:37

amount. I'll just bet a dollar. Do you

356:39

want to spin again? If I type in

356:41

anything besides a capital Y, we will

356:43

exit. I will type in no. Then we

356:49

exit. Enter your bet amount. I'll bet a

356:52

dollar. If somebody were to type in a

356:55

lowercase Y, that doesn't register.

356:57

We'll make it uppercase by following our

356:59

input with the upper method to make it

357:02

uppercase. Place your bet. A dollar.

357:05

Hey, I won. I won $3. Do you want to

357:08

play again? I'll type in a lowercase Y.

357:11

Yes, I would like to play again, but I

357:13

did not hold shift in order to make this

357:15

a capital Y. That will still register.

357:19

And our current balance is

357:21

$12. We're ahead currently. Place your

357:24

bet amount. I'll bet

357:25

$10. We lost this round. I will press N

357:30

because I don't want to play again. Then

357:32

we exit. So at the end of our

357:36

program, I will print I'll use an

357:40

fstring game over your final balance is

357:47

I'll add a placeholder. Pick a unit of

357:49

currency. I'll pick dollars. Display our

357:52

balance. Then I'll just add some text

357:55

decoration before and after to make it

357:57

all look nice.

358:03

Okay, let's play this one last

358:05

time. Enter your bet amount. I'll bet a

358:07

dollar. Sorry, you lost this round. Do

358:09

you want to spin again? Yes, I do. I

358:12

will bet

358:13

$5. You lost. Spin again. Yes, I will

358:16

bet

358:18

10.

358:20

20 again. I'll bet 20. I keep losing.

358:28

I'm running out of money, guys. Hey, I

358:30

won $10, though. Do you want to spin

358:32

again? No. Game over. Your final balance

358:35

is $13. That's why you shouldn't gamble.

358:38

You tend to lose more money than what

358:40

you gain. All right, everybody. So, that

358:42

is a slot machine program you can write

358:44

using

358:45

Python. Hello everybody. Today, I'm

358:47

going to show you how we can write a

358:49

substitution cipher encryption program.

358:52

Basically speaking, what we're going to

358:53

do is that we have a message. To hide

358:56

the message, we can encrypt it by

358:58

replacing every instance of one

359:00

character with another chosen at random

359:03

using the same key. We can then decrypt

359:06

the message. When I was at my

359:08

university, I took an intro to cyber

359:10

security course. I turned this program

359:12

in as a final assignment, and I did get

359:14

an A on it. I don't know, maybe it'll

359:16

help you. At the very least, it's a good

359:19

exercise. All right, let's get started,

359:21

everybody. We will begin by importing

359:23

the random module as well as the string

359:27

module. Let's create a string of

359:29

characters named chars. Whatever

359:32

characters you would like to use for

359:34

your encryption program, list them here

359:36

as a string. However, this can be a lot

359:38

to write. I think a better solution

359:41

would be to import some constants from

359:43

the string module. I'm going to include

359:46

some punctuation. I will import the

359:48

punctuation constant of the string

359:51

module. How the heck do you spell

359:53

punctuation? Okay, that's right. Plus, I

359:57

will add some digits. String dot digits

360:01

constant plus string

360:07

dot asy

360:10

letters. Let's take a look at our

360:12

character so far.

360:17

We have one long string of

360:19

characters. What if I would like to

360:21

include a space, a white space? Well,

360:24

there is a constant for that, but that

360:26

includes things like carriage return.

360:29

That's going to warp our results. Let me

360:32

show you just for a demonstration.

360:34

String dot whitespace plus all the other

360:39

stuff. We have a carriage return and

360:42

some other characters. I would like to

360:44

avoid that. So in place of importing the

360:46

whites space constant from the string

360:48

module, I'm going to add a space

360:50

character. That's good

360:53

enough. Here are all the characters I

360:55

will be using this program. Feel free to

360:57

add more or less. This is all one long

361:01

string. I'm going to turn the string

361:03

into a list where each character is an

361:06

individual element. To do that, I'm

361:09

going to take our string of chars,

361:12

reassign it, then type cast my string of

361:16

characters as a list. Then let's print

361:19

it again. print

361:22

chars. Instead of one long string, we

361:25

have a list. A list of all the

361:27

characters we'll need. I am then going

361:29

to create a key, which we will shuffle

361:32

eventually. Key. Then to create a copy

361:35

of a list, you can type the original

361:37

list dotcopy

361:40

method. Then I will print my

361:44

key. I'm going to place these lists

361:47

within an F string.

361:59

chars then

362:03

key. Let's see what we

362:05

have. We have two identical lists. One

362:09

for the original characters and the

362:10

other for the key. We're going to

362:13

shuffle this

362:16

key. random.shuffle

362:19

shuffle pass in our list of

362:23

key. Look at that. All of the characters

362:25

are now shuffled in a random order. What

362:28

we'll be doing when somebody types in

362:30

some text to be encrypted, we will

362:33

replace every instance of one character

362:35

within that string. Let's say an O, then

362:38

replace it with another one. Every time

362:41

we run this program, this key will be

362:42

reshuffled. Let's ask for some user

362:45

input.

362:47

This part of our program we will do some

362:51

encryption. Plain text is the original

362:54

message. Plain text equals we will

362:58

accept some user

362:59

input. Enter a message

363:03

to

363:05

encrypt. Cipher text is the name of the

363:09

encrypted

363:10

message. That will be an empty

363:13

string. Okay. Let's say a user types in

363:16

a message. Enter message to encrypt. I

363:19

like pizza. It's a very important

363:23

message. Every instance of a character

363:25

within my plain text, I will refer to

363:28

the key and replace that letter with a

363:30

different one. For example, any Z's, I

363:33

have two Z's in this

363:34

program, will be replaced with, let's

363:39

see, capital B. Every time we run this

363:42

program though, it's going to shuffle

363:44

the key. So, it's not going to be

363:46

consistent. What we're going to be doing

363:48

is iterating over every letter in our

363:50

plain text. For every letter in plain

363:54

text, strings are

363:57

iterable. Find the index of every letter

364:00

from our plain text within our list of

364:04

characters. Let's assign a variable

364:06

index. index

364:09

equals take our list of chars, use the

364:12

index method. We are looking for that

364:16

letter, whatever letter we're currently

364:17

on, then return an

364:20

index, then refer to our key, get

364:23

whatever letter is at that same index.

364:26

So, we will append that to our cipher

364:28

text. It's currently an empty string.

364:30

cyper text plus

364:34

equals our key at the given

364:41

index. Our cipher text should be the

364:43

encrypted message. Now let's print it

364:46

out. Print I'll use an

364:49

fstring original

364:52

message. Let's print our plain

364:56

text. Then our encrypted

365:04

message. Print our cipher text

365:08

string. Let's take a look so far. Enter

365:12

a message to encrypt. I like

365:16

pizza. Then here's the new encrypted

365:19

message. Every instance of a character

365:21

within my plain text was replaced with

365:23

another. So, for example, any Z's were

365:26

replaced with E. I have two E's within

365:28

this encrypted message. If I were to run

365:31

this program again, it would likely be

365:32

different. I like

365:35

pizza. And here's my new encrypted

365:38

message. My Z's were replaced with

365:40

semicolons this time. For every ladder

365:43

in our plain text, get the index of each

365:45

letter. Then refer to the key. Add the

365:48

new character to our encrypted message.

365:51

It's probably best for us not to display

365:52

the characters and the key. So, let's

365:54

hide

365:56

those. We will be reusing this key for

365:59

decryption. Now, to decrypt the message,

366:02

let's copy this section of

366:04

code. Paste it. We are now

366:08

decryptting. We will ask for some cipher

366:11

text. Then reset our plain text.

366:15

For every letter in our cipher

366:18

text, refer to our

366:22

key, append a character to our plain

366:27

text within our list chars at a given

366:31

index. We will display our encrypted

366:34

message followed by the original

366:37

message. Let's try it one last time.

366:40

Enter a message to

366:42

encrypt. I like

366:47

tacos. Here's my original message. Then

366:49

the encrypted message. If I were to

366:52

decrypt the encrypted message, it should

366:55

give me my original message. I will type

366:57

in these characters

367:00

exactly. Hit enter. And here is my

367:03

message decrypted. I like

367:06

tacos. All right, everybody. So, that is

367:08

a substitution cipher encryption program

367:11

for beginners. When I was at university,

367:13

I did turn this program in for a final

367:15

assignment for a cyber security class.

367:17

And I did get an A on it, so maybe it'll

367:19

help you. And well, yeah, that's an

367:21

encryption program for beginners in

367:25

Python. What's up everybody? So, in

367:28

today's video, we're going to create a

367:30

game of Hangman using Python. I thought

367:32

that this would be a good mini project

367:34

for us. While learning to code, it is

367:36

important to create small projects as

367:38

you go along. Here's one that we can

367:39

make together. When creating a project,

367:42

I like to declare the various variables

367:44

and data structures I'll need first,

367:45

followed by the functions I'll need for

367:48

this game. We will need a set of words.

367:52

One of these words is going to be chosen

367:54

at random. So, let's create a few words.

367:57

I'll add some

367:58

fruit. Apple,

368:02

orange,

368:04

banana, coconut, and one more pineapple.

368:11

Using the random module, let's import

368:13

that. Import

368:15

random. Using the random module, we will

368:18

pick one of these words at

368:21

random. We won't be able to see what it

368:23

is, but we can guess what the word is

368:26

one letter at a time. Once we reach six

368:28

incorrect guesses, we lose the game.

368:31

Before each guess, we will display some

368:33

ASI art, which I will name as hangman

368:37

art.

368:38

This will be a dictionary. A dictionary

368:40

where each key value pair contains a

368:43

tuple. So this is a

368:48

dictionary of we'll have a key which

368:52

will be a number and a tpple. The key is

368:55

going to represent the incorrect number

368:57

of guesses. So we'll start at zero. We

369:00

will display a tpple which will contain

369:02

some asy art. Then let me just copy

369:05

this.

369:07

For one incorrect guess, we'll display

369:10

some different ASI

369:12

art. I'll just put each on a new line

369:15

for

369:19

readability. So, we're going to go all

369:21

the way up to

369:22

six. Once we hit six incorrect guesses,

369:25

we lose the

369:30

game. Each key corresponds to the number

369:33

of incorrect guesses. Once we reach six,

369:36

we lose the game. Each tpple that

369:39

corresponds to the incorrect number of

369:41

guesses, we will display a certain

369:43

image. If you would like, feel free to

369:45

look in the description of this video if

369:47

you would like to copy this to save you

369:48

some time. Each tpple will consist of

369:51

three rows, three

369:54

strings. For no incorrect guesses, where

369:57

incorrect guess is a zero, we will

370:00

display nothing. We can't see our

370:02

hangman person.

370:05

For one incorrect guess, we will display

370:07

their

370:09

head. For two incorrect guesses, we will

370:11

display their head and the main torso of

370:14

their body, which will represent with a

370:16

vertical

370:17

bar. Let me copy this

370:21

one. For three incorrect guesses, we

370:23

will display their left arm represented

370:27

with the forward slash.

370:30

with four incorrect guesses, we will

370:31

display their right arm. However, if you

370:35

use a backslash, that's an escape

370:37

sequence within a string. You have to

370:39

use double

370:40

backslashes to literally print a

370:43

backslash. So, with five incorrect

370:45

guesses, we will display their left leg

370:48

of the

370:50

person. Then, once we reach six

370:52

incorrect guesses, we display the full

370:54

person. That's when we lose the game.

370:57

when we see the entire person. That's

370:59

some asy art that we can use. So, let's

371:02

test it just to be sure that everything

371:04

is working

371:06

fine. I will

371:08

print my hangman

371:10

art at the key of zero to represent no

371:14

incorrect

371:16

guesses. Okay. So when we display this

371:18

person, we're going to have to use some

371:20

sort of

371:21

loop for every let's say line in hangman

371:27

art at index of zero for zero incorrect

371:31

guesses. I will print each

371:37

line with no incorrect guesses. We don't

371:40

display anything. That's

371:42

correct. We can't see the person and

371:44

that's okay.

371:47

So with one incorrect guess display the

371:50

dictionary where the key is one that

371:53

displays the person's

371:57

head. Two two would be the main torso of

372:01

their

372:01

body.

372:03

Three, their left

372:05

arm. Four, their right arm. Five, their

372:11

left

372:12

leg. And six, their right leg. Once we

372:16

see the entire person, we lose the game.

372:19

So, we can delete these two lines of

372:21

code. We no longer need them. We know

372:23

that our dictionary is working. I'm

372:26

going to zoom out a little bit.

372:28

Following our dictionary, we'll declare

372:29

the various functions we'll need

372:31

throughout this program. We will define

372:33

a function to

372:35

display man, our hangman. There will be

372:39

one parameter wrong

372:43

guesses. And then for the time being

372:45

I'll write pass. We'll fill in this

372:47

function later. When we display our man,

372:51

we need to know the number of incorrect

372:53

guesses to display the right

372:57

image. We have a display man function

373:00

and a

373:03

display hint

373:06

function. We will have a string of

373:10

hint. Then I'll write pass for now. Our

373:14

hint is going to be a list, a list of

373:17

underscore characters. For each letter

373:19

that we guess, right, we'll flip one of

373:21

those underscores to be a letter if that

373:24

letter is correct. I'll create a

373:26

function of display

373:29

answer. Within this function, we will

373:32

display the correct answer either when

373:34

we lose the game or win the game. And I

373:38

will write pass. We will create a

373:40

function of main to contain the main

373:43

body of code of our

373:44

program. Again, I'll write pass for

373:48

now. I'll add the following if

373:51

statement. If dunder name is equal to a

373:55

string of dunder main. If we are running

373:59

this file directly, I would like to call

374:01

the main function to start the program.

374:04

All right, let me zoom out. This will be

374:07

the main skeletal structure of our

374:09

program. Import the random module. We

374:12

have our set of words. We'll be

374:13

importing more from a separate file near

374:15

the end of this video. We have a

374:17

dictionary where the key is a number to

374:19

represent the number of incorrect

374:21

guesses. And a tpple to display some asy

374:24

art. We have four functions. Display our

374:27

man, display the hint, display the

374:29

answer, and the main function to contain

374:31

the main body of code. All right, let's

374:34

work within our main

374:36

function. Within our main function, we

374:38

will create a variable of answer. What

374:41

is the correct answer that we have to

374:43

guess? I will access the random module,

374:46

call the method of choice, then pass in

374:49

our set of words. One of these words

374:53

will be chosen at

374:54

random. Let's test that. I will print

374:58

our answer just temporarily.

375:01

We should get a random word. Apple.

375:04

Apple. Pineapple. Apple. I guess it

375:08

really likes apple for some reason.

375:10

There we go. We have orange. We are

375:11

choosing a word at

375:13

random. We no longer need this print

375:16

statement. Looks like everything is

375:18

working fine. Now we'll display our

375:21

hint. Our hint is going to be a list of

375:25

underscore characters. I need the number

375:27

of underscore characters to equal the

375:30

number of characters in one of these

375:32

words that is chosen at

375:35

random. So I could multiply my list by

375:40

the length using the length function of

375:43

my

375:44

answer. So let's print our

375:47

hint to see what we're working

375:51

with. With my selected word, we have how

375:54

many underscores? 1 2 3 4 5 6 7. Okay,

375:59

we have a different word. 1 2 3 4

376:03

5. That is probably apple. It has five

376:07

characters. All right, so that's our

376:09

hint. It's a list of underscore

376:12

characters. When we guess a letter, if

376:14

it's correct, we'll fill in one of the

376:16

underscores with that correct

376:19

character. We need to keep track of the

376:21

number of wrong guesses. We'll create a

376:24

variable of wrong guesses. Set that

376:26

equal to be zero. When we start the

376:28

game, we're going to keep track of all

376:30

of the incorrect guesses that we've

376:32

made. We will create a set of

376:35

guested

376:37

letters. For an empty set, we'll call

376:40

the set function. Normally in Python,

376:43

you can't create an empty set with just

376:44

a set of parenthesis. We have to use the

376:46

set function. Then I will create a

376:49

boolean variable of is running.

376:52

Set that to be true. While our game is

376:55

running, continue playing. Once we lose

376:58

or win the game, we will switch this to

377:00

be false to exit the game. We will keep

377:03

this as true when we initially run this

377:05

program. After we declare the variables

377:08

we'll need within the main

377:10

function, we'll create a loop, a while

377:13

loop. While is running, we don't need to

377:16

say while is running is equal to true.

377:19

We don't necessarily need to create that

377:21

comparison. We can just say while is

377:24

running while this is true continue

377:26

doing some code. So what would we like

377:29

to do? Let's call the function of

377:32

display man. But we have to pass in the

377:34

wrong number of

377:38

guesses. Call our function of display

377:40

man. Pass in our variable of wrong

377:43

guesses. When we begin the game, we

377:46

would like to display one of these

377:47

images.

377:49

Then we will display our hint. Then

377:51

we'll call the function to display our

377:55

hint. Pass in our hint. That was the

377:58

list of underscore characters to

378:00

represent the answer we have to guess.

378:03

We will create a variable of guess and

378:06

accept some user

378:08

input. We'll prompt the user to enter a

378:12

letter.

378:14

Just in case a user types in a character

378:16

that's

378:17

uppercase, let's add the lower method to

378:20

make it

378:21

lowerase. So, let's fill in our display

378:24

man function. There's not a lot to write

378:26

here. When we call this function, we

378:30

need to display one of these images

378:32

based on the wrong number of guesses,

378:34

one of these keys.

378:37

Within the display man function, we'll

378:40

create a for loop for every line in my

378:45

hangman art this

378:48

dictionary at the key of wrong guesses.

378:52

This will be a number 0 through

378:55

six. Depending on what this number is, I

378:59

will print each

379:01

line. Print each line of that tpple.

379:06

Let's see what we're working with. We'll

379:08

do a test

379:10

run. So, we are displaying no person. We

379:14

can't see them. For testing purposes,

379:16

I'm going to change wrong guesses to be

379:18

one, we're displaying their head.

379:21

Two, displays their body.

379:25

Three displays left arm.

379:29

Four is their right

379:31

arm. Five their left leg. and

379:37

six is their full body. That's when we

379:40

lose. Now, you don't necessarily need to

379:43

do this, but I'll add some text

379:45

decoration before and

379:47

after. I'll add just a bunch of

379:50

asterisks before and

379:54

after. I think that looks better, but

379:56

you do you. Let's be sure to set wrong

379:59

guesses back to

380:00

zero. After we display our hangman, we

380:03

have to display the hint. what's the

380:05

clue we're trying to solve. So we will

380:08

call our display hint function and pass

380:11

in our list of

380:13

hint. So within the display hint

380:15

function, let me zoom out. I will print

380:18

the

380:18

following. Between each character within

380:21

our hint, each underscore, we will

380:23

display a space

380:26

character. Strings have a built-in join

380:29

method. We'll call that then pass in our

380:32

hint. For each character within our

380:35

hint, join it by an empty

380:38

space. So now when we do a test

380:42

run, we are displaying an underscore to

380:44

represent each

380:46

character. Each is separated with the

380:49

space. While we're here, we'll fill in

380:52

the display answer function. We just

380:54

have to copy this line of code from

380:55

display hint. Replace hint with answer.

380:59

And that's all we need for the display

381:00

answer function. So let me test that

381:02

real quick. After displaying our hint

381:05

temporarily, I will display our answer

381:08

just to be sure that it's

381:11

working. Yep, there's our hint. And

381:14

there's our answer that we have to

381:16

guess. Okay, let's delete this line of

381:19

code. We don't want to display the

381:21

answer. I was just testing it. So the

381:24

user is going to be able to type in a

381:25

letter to guess such as a for example.

381:30

Once we guess a letter, if that letter

381:32

is found within the hint, if it's one of

381:34

these characters, we need to switch that

381:37

underscore to be one of those

381:39

characters. So we'll write the following

381:41

if statement. If our guess is in our

381:48

answer, in is a membership operator. If

381:51

this letter is found within our string

381:53

of answer, we're going to create a loop.

381:56

We will create a loop that will iterate

381:58

once for each character within the

382:00

answer. But we don't know the length of

382:02

the answer because Python will choose it

382:05

at random. So let's say for every index,

382:09

we can shorten this to i. for I in

382:14

range the length of my

382:19

answer. Let's say the word is apple. The

382:22

length of the word apple has five

382:24

characters. This would return five for i

382:28

in range five. Then we will iterate five

382:30

times. We'll iterate this loop once for

382:34

the number of characters within my

382:35

answer. We'll check during each

382:38

iteration if our answer at index of I

382:44

during the first iteration that will be

382:45

zero then the second iteration it will

382:48

be 1 then two so on and so forth strings

382:51

are iterable if our answer at index of i

382:55

is equal to our guess if there's a match

382:58

if we guess the correct letter then

383:01

we're going to take our hint

383:06

at that given index of I and set that

383:10

equal to be our guess. Looks like this

383:13

if statement is outside of the while

383:14

loop. I'm just going to indent it by one

383:17

somewhere within

383:18

it. Okay, let's do a test

383:22

run. I'm going to guess the letter

383:25

A. Yes, we have one A. Let's do

383:29

something that's probably not in here.

383:33

Q. Okay. So, there were no matches. We

383:36

don't end up doing

383:37

anything. So, what is this word?

383:40

Probably this should be the word

383:43

orange. So, let's guess

383:46

O

383:48

R

383:50

N E G. All right, we know that it works.

383:56

What if somebody types in some input

383:57

that's not valid? Before checking if

384:00

that guess is correct, we'll do some

384:02

input validation. What if the user types

384:05

in a whole word like

384:08

pizza? We want the user to only guess a

384:10

single character, not many

384:13

characters. We'll add the following

384:16

line. If the length of our guess that we

384:20

type

384:21

in does not equal

384:24

one, then I will print the following

384:26

message.

384:28

Let's say invalid

384:32

input. Then we will use the keyword of

384:35

continue to skip this

384:38

loop.

384:41

Continue. Okay. Enter a letter. I will

384:43

type the word

384:45

pizza. We get this message of invalid

384:47

input. We skip that loop's current

384:50

iteration. I will guess A. There are two

384:53

A's. I will type banana. And again we

384:57

get invalid input. We have to guess one

384:59

letter at a time. What if somebody types

385:02

in a number like one? We would like to

385:05

prevent

385:08

that. So within this if statement I

385:12

would like to execute this code if our

385:15

guess is not an alphabetical character.

385:18

I can add the

385:19

following or not. Take our guess dot use

385:25

the is alpha method. If our guess is an

385:30

alphabetical character, this returns

385:33

true. If it's not an alphabetical

385:35

character, it's false. So we are

385:38

checking if this is not an alphabetical

385:41

character, we execute this code. Let's

385:44

try this again. I will type in

385:46

one invalid

385:49

input

385:52

42069 invalid

385:54

input. Let's say we guessed the letter

385:56

A. What if we type in a letter we have

385:59

already guessed? I will guess A

386:02

again. If they already guessed a letter,

386:04

I don't want that to count. We'll skip

386:06

the current loop

386:08

iteration. I'll add another if

386:11

statement. If our

386:15

guess is

386:16

in our set of guess

386:21

letters, then I will print the

386:24

following. I'll use an F

386:27

string. Our guess

386:31

is

386:32

already

386:35

guessed. Oh, one thing I'm forgetting.

386:38

Once we check that our guess is not

386:40

within our guess characters, we'll take

386:42

our guess letters. This is a set, add

386:46

the

386:48

guess. We're keeping track of the

386:50

letters we have already

386:53

guessed. So I will type let's guess A.

386:57

We have one A. If I were to guess A

386:59

again, we get that message of A is

387:02

already

387:03

guessed. And then be sure to add

387:06

continue to skip the current loop

387:10

iteration. All right. Now going down to

387:12

this if statement. If guess is in our

387:15

answer. If we guess a character that's

387:18

incorrect, we will take our variable of

387:22

wrong guesses incremented by one. Wrong

387:25

guesses plus equals 1. Let's do a test

387:30

run. I will guess A.

387:34

There is an A. What about Q? There is no

387:38

Q. We display our dictionary where the

387:40

key is one. We display that ASKI

387:43

art. R. Is there an R? Yes, there is an

387:47

R. This is probably

387:52

orange. I would like to be sure we

387:54

display the entire person. I will guess

387:56

some wrong characters.

388:02

We know that that works. Now, we need a

388:05

win condition if we guess all of the

388:07

correct characters and display the

388:08

entire word. We'll work on that

388:11

next. If there are no underscore

388:15

characters not in our

388:18

hint, this will be true if there are no

388:22

underscore characters in our hint. if

388:26

underscores not in

388:28

hint. We'll call our function of display

388:31

man. Pass in the wrong number of

388:35

guesses. Call the function of display

388:40

answer. Pass in our

388:44

answer. We will

388:46

print the text of you win. Then set our

388:51

boolean variable of is running equal to

388:54

be

388:56

false. Let's win this time. I already

388:59

know that this word is probably

389:03

pineapple. Let's guess something

389:11

incorrect. There we go. We have two

389:14

wrong guesses, but we have correctly

389:16

guessed the word pineapple. You win. and

389:19

we exit the program. What if we lose?

389:22

I'll add the following if statement.

389:25

Else if our variable of wrong

389:29

guesses is greater than or equal. So the

389:33

length of our hangman art is a total of

389:37

seven. There's seven total

389:42

keys. But once we hit six, we lose the

389:47

game with this else if statement. If the

389:50

length of our hangman

389:53

art, the length of our hangman art is

389:56

going to be seven. So we are going to

389:58

subtract one for six for a total of

390:02

six. Once our wrong guesses is greater

390:05

than or equal to six, that means we lose

390:08

the game. We will call the display man

390:11

function. Pass in the wrong number of

390:14

guesses. Display what the correct answer

390:17

should have been. Display answer. Pass

390:19

in our answer. We will

390:24

print you

390:27

lose. Then take our boolean variable of

390:30

is running. Set that to be

390:35

false. I'll guess incorrect letters.

390:44

There the word was coconut. We have six

390:46

incorrect guesses. We display the entire

390:48

hangman. The correct answer was coconut.

390:51

You

390:52

lose. If you would like to import a

390:54

larger variety of words, we could create

390:57

a separate Python file for that. So

390:59

within our project folder, we will

391:00

create a new Python file. I will name

391:04

this Python file

391:07

words list. This will be a Python

391:11

file. Let's take our set of words. Cut

391:16

it. I'll add a note that these are words

391:20

for hangman

391:24

game. Words will be a set. I recommend

391:27

looking online for a very large set of

391:30

words that we can use. Then just copy

391:32

and paste them within here. While

391:34

browsing online, I found an extensive

391:36

list of animals that I can use.

391:39

So here are all the possible words for

391:41

my

391:42

game. So from my main Python file, I

391:45

have to import this module of words

391:50

list. From the module of words

391:55

list, import

391:57

words. And now I have a greater variety

391:59

of words I can use. Let's run this one

392:02

last time. This word has four letters.

392:05

I'll guess the vowels. There's an A. No.

392:09

E. I O. There is an

392:14

O. Is it

392:16

goat?

392:18

Nope.

392:20

T R

392:23

bore. All right. The word was boar. You

392:26

win. All right everybody. So that is a

392:29

game of hangman that we can create using

392:31

Python. Hey everybody. So we have

392:34

finally made it to Python objectoriented

392:37

programming. This is a very important

392:39

topic. In Python, an object is a bundle

392:42

of related attributes and methods.

392:45

Attributes are similar to variables to

392:48

describe what the object has. So look

392:50

around you right now. You are surrounded

392:52

by different real world objects. Next to

392:55

me, I have a phone, a cup, and a book.

392:58

Each of these objects can have different

393:00

attributes to represent it. For example,

393:03

an attribute of the phone next to me

393:05

could be version number. I could set

393:07

that to be 13. Is on could be another

393:10

attribute. Is the phone powered on or

393:12

not? That could be true or false. Or

393:14

even a price. I have a cup next to me.

393:17

What liquid is within the cup? In this

393:19

case, coffee. What's the temperature of

393:21

the cup? Is the cup empty? Is empty? Or

393:25

even a book. What's the title of the

393:27

book? That could be a string. How many

393:30

pages does the book have? Pages could be

393:32

another attribute. Now, objects also

393:34

have the capability to do things. They

393:37

have methods, which are functions that

393:40

belong to an object. People mix up

393:42

functions and methods all the time.

393:44

They're technically different. Even when

393:46

teaching, I tend to make that mistake,

393:48

calling a method a function, and a

393:50

function a method. Usually, people know

393:52

what you're referring to, though. A

393:53

method is a function that belongs within

393:56

an object. What are some actions these

393:58

objects can perform? With a phone, you

394:01

can make a call or receive a call. Turn

394:04

the phone on or turn the phone off.

394:07

Those could all be functions. With a

394:09

cup, you could fill the cup, drink from

394:11

the cup, or empty the cup. With a book,

394:14

you can open the book, read the book,

394:16

and close the book. An object is a

394:19

bundle of related attributes and

394:22

methods. They can represent real world

394:25

items. To create many objects, we'll

394:28

need to utilize a class. A class is a

394:31

type of blueprint used to design the

394:34

structure and layout of an object. We

394:36

need to design what our objects have,

394:39

their attributes, and what they can do,

394:42

their methods. We will create a class of

394:45

car. We will create some car

394:47

objects. Class car.

394:52

To construct a car object, we need a

394:54

special type of method called a

394:56

constructor. It works similarly to a

394:58

function. We will define a function of

395:03

double underscore init meaning

395:06

initialize double underscore again and

395:09

then follow this with a set of

395:10

parenthesis. This is our constructor

395:12

method. We need this method in order to

395:15

construct objects. It's a dunder method.

395:18

Dunder meaning double underscore. That's

395:20

a future topic. I don't want you to be

395:22

overloaded with information right now.

395:25

All you need to know is that we need

395:26

this method in order to create objects.

395:29

This method behaves similar to a

395:31

function. We need to set up the

395:33

parameters. Self is already provided to

395:36

us. Self means this object we're

395:38

creating right now. This car. So what

395:41

are some attributes that a car should

395:43

have? A model, that could be a string

395:48

like a

395:49

BMW, a year, that could be a number, a

395:54

color. Let's add a boolean of for sale.

395:59

Is the car for sale or not? That's true

396:02

or false. To assign these attributes,

396:04

we're going to access self. self dot the

396:09

name of the attribute self domodel

396:12

equals the model we

396:15

receive these are parameters when we

396:18

receive the name of a model we will

396:20

assign it to this object let's do this

396:23

with year self doyear equals year self

396:29

doc color equals

396:31

color self for sale equals for sale.

396:37

This is an example of a few attributes

396:39

that a car might have. A model, year,

396:42

color, and if it's for sale or not,

396:45

represented by a boolean. Now, to

396:47

construct a car object, we need a unique

396:49

name for this car. Let's just say car 1.

396:53

Car 1 equals take the name of the class.

396:58

Add a set of parenthesis to invoke the

397:01

constructor. We're going to do this

397:02

almost exactly like a function. We have

397:05

parameter set up. We need to send a

397:07

matching number of arguments. Self is

397:10

provided to us behind the scenes

397:12

automatically. We need a model, year,

397:14

color, and if it's for sale or not. So,

397:18

pick a car of your choosing. I'll pick

397:20

my favorite car. The model will be a

397:23

Mustang. For the year, I'll go with the

397:26

recent year of

397:27

2024. A color, I'll pick red. Is the car

397:32

for sale? I like this car. So, no, I

397:35

will set that to be false. Make sure

397:37

false is

397:38

capitalized. Let's see what happens if I

397:41

attempt to print our car object of car

397:46

1. What we're given is the memory

397:49

address of this car object where it's

397:52

located. But I would like one of the

397:54

attributes located at this memory

397:57

address. Instead of printing the object

397:59

itself, we're going to access one of the

398:01

attributes found within this car, we

398:04

will follow the name of the car with a

398:06

dot. This dot, it's known as the

398:09

attribute access operator. I would like

398:13

the model of car

398:15

1. That would give me

398:18

Mustang. Let's access the year. Take the

398:21

name of the car, car 1 dot the year

398:26

2024, followed by the color car 1 dot

398:32

color

398:34

red car 1 is it for sale. We'll print

398:40

that. That is

398:42

false. Now let's create a second car.

398:45

We're going to reuse this class to

398:47

create a second car. We will create car

398:50

2 equals car. We'll pass in some

398:53

different

398:54

arguments. A Corvette. The year will be

398:58

2025. The color will be blue. Is this

399:02

car for sale? Let's say that is

399:05

true. Instead of accessing car 1's

399:07

attributes, let's access car 2's

399:11

attributes. That would give us a

399:14

Corvette. The year is 2025. The color is

399:17

blue for sale is set to true or even a

399:21

third car. Car 3 equals a new car. We

399:26

will pass in a string of charger. The

399:31

year

399:32

2026 the color will be yellow. Is this

399:35

car for sale? Let's say that is true as

399:38

well. Then I will print car 3's

399:41

attributes.

399:46

The model is Charger. The year is 2026.

399:48

The color is yellow. For sale is set to

399:51

true. With classes, they can take up a

399:54

lot of space. For better organization,

399:57

you can place them within a new Python

399:59

file. So, let's cut our

400:03

class. And we will create a new Python

400:06

file within our project folder. File,

400:09

new, Python file. The name of this

400:12

Python file is going to be all lowercase

400:17

car. Then we will paste the class that

400:21

we cut

400:22

originally. Class car which has a

400:25

capital

400:26

C. So from our main Python file, we're

400:29

going to import our car file, our car

400:33

module. From the name of the module,

400:35

car, import the name of the class, car.

400:39

Then when I run this program, nothing

400:41

should change. We should still have

400:43

access to all of our car

400:47

objects. You could either keep your

400:49

classes within your main Python file or

400:52

import them if you would like to

400:53

organize things. Let's talk about

400:55

methods. Methods are actions that are

400:58

objects can perform within our class. We

401:01

will define a method of drive. self is

401:05

going to be provided to us when we

401:08

invoke the drive function. Let's

401:10

print you drive the car. What other

401:15

things can cars do? Let's

401:19

stop. We will

401:23

print you stop the

401:28

car. Let's take car one access the drive

401:32

method.

401:35

You drive the car. Car 2 also has a

401:38

drive method. You drive the car. Same

401:41

thing with car 3. You drive the car.

401:44

Let's access the stop

401:47

method. Car one.

401:51

Stop. Car

401:54

2. And car

401:57

3.top. These methods are identical for

402:00

each car object. Instead of printing the

402:03

word car, let's insert the model of the

402:06

car, I will convert these print

402:08

statements to

402:11

fstrings. Instead of the word car, let's

402:13

add a placeholder. Let's add self dot

402:18

model. Self is referring to the object

402:21

we're currently working with. Use the

402:24

attribute access operator followed by

402:26

the name of the attribute. Let's also do

402:29

this with the stop method.

402:32

self

402:36

do. Let's take car one. Use the drive

402:40

method. You drive the Mustang. car

402:44

one

402:47

stop. You drive the Mustang. You stop

402:49

the Mustang. Let's do this with car

402:52

two. You drive the Corvette. You stop

402:55

the

402:56

Corvette. Car

402:58

three, you drive the Charger. You stop

403:00

the

403:01

charger. Now within our F strings, let's

403:04

also insert Let's insert the

403:08

color. I'll add a placeholder. self dot

403:12

color. Do this with stop as

403:15

well. self dot

403:20

color. You drive the yellow Charger, you

403:23

stop the yellow Charger. Car one, you

403:27

drive the red Mustang, you stop the red

403:29

Mustang. Car two, you drive the blue

403:32

Corvette, you stop the blue Corvette.

403:35

Let's add one last

403:37

method. Let's create a method to

403:40

describe our car. We'll print the

403:42

details of the

403:43

car. Let's print I'll use an

403:47

fring. Add three placeholders.

403:51

Let's print self

403:55

dotyear followed by self dot

403:58

color then self do

404:03

model. We'll take car 1 use the describe

404:06

method that we

404:08

created. Describe car 1. Car 1 is a 2024

404:14

red Mustang. Describe car 2. Car 2 is a

404:18

2025 blue Corvette. Car 3 is a 2026

404:24

yellow Charger. All right, everybody.

404:26

So, those are objects in Python. An

404:29

object is a bundle of related

404:32

attributes. Attributes are variables

404:34

that an object has and methods. Methods

404:38

are functions that belong to an object.

404:41

They define what this object can do. And

404:44

well everybody that is a summary of

404:46

object-oriented programming using

404:49

Python. Hey everybody today I got to

404:51

talk about class variables in Python.

404:54

Class variables are shared among all

404:57

instances meaning objects created from a

405:00

class. Instance variables are defined

405:02

inside of the constructor. Class

405:04

variables are defined outside of the

405:07

constructor. With class variables, they

405:09

allow you to share data among all

405:12

objects created from the class. With

405:14

instance variables, each object has

405:17

their own version. With a class

405:19

variable, all those objects share one

405:22

variable. Here's an example. We will

405:24

create a class of

405:27

student. We also need a constructor.

405:30

When we create a student object, this

405:32

constructor is automatically going to be

405:34

called, but we need to pass in some

405:36

arguments. We are provided with self.

405:39

Self refers to the object we're

405:41

currently working with. We will set up a

405:44

name parameter and an age parameter. We

405:47

will assign self the object we're

405:50

currently working with. Set the name

405:53

attribute to equal the data for the name

405:56

that we receive from this parameter. And

405:59

self age equals age. Let's construct two

406:04

student objects. We will have student

406:07

one equals then call the constructor for

406:11

student. So type the name of the class

406:13

followed by a set of parenthesis to

406:15

invoke it. This will automatically call

406:17

the constructor. But we have to pass in

406:19

data for the name and the age. For the

406:22

name, let's pass in Spongebob because

406:25

basically everybody in the world knows

406:26

who Spongebob is. I don't know how old

406:28

Spongebob is. We'll say he's 30. We'll

406:32

create another student object which we

406:34

will refer to as student two. We will

406:37

call the constructor of our student

406:39

class. Pass in data for the name and

406:42

age. Student two will be Patrick.

406:45

Patrick will be 35. Okay, let's make

406:49

sure this works. Let's print student

406:53

one's name followed by student one's

406:57

age.

407:01

And we should get Spongebob and his age

407:04

is 30. Let's print student 2's name and

407:07

student 2's age. Patrick. Patrick is 35.

407:12

Now we'll create a class variable. Class

407:14

variables are defined outside the

407:16

constructor and they are shared among

407:19

all objects created from that class.

407:21

Each object has their own name and age

407:24

property. These are instance variables.

407:27

But class variables are defined outside

407:29

the constructor. Each object will share

407:32

this one variable. So if we're working

407:34

with students, let's say there is a

407:38

class

407:39

variable of class year. What is the

407:44

graduating year of this

407:46

class?

407:48

2024. Now let's print student one's

407:52

graduating year.

407:55

print student one dot

407:59

class

408:04

year. Okay, so Spongebob has a class

408:07

year of 2024. That's when he's

408:10

graduating. Let's check student

408:15

two. Patrick, his age is 35. His

408:19

graduating class year is 2024. Now with

408:22

class variables, you can access them

408:25

through any one object such as student

408:28

one or student two. It's good practice

408:30

to access a class variable by the name

408:33

of the class rather than any object

408:35

created from the class. Since we're

408:37

accessing class year, we'll access this

408:40

class variable by the name of the class

408:42

of student. Make sure the S is

408:47

capital. This helps with clarity and

408:50

readability. If I was looking at this

408:52

print statement, I can tell that class

408:54

here is a class variable because we're

408:57

accessing it directly from the class and

408:59

not any instance from this class.

409:02

Without looking at this class, I can't

409:04

tell if class year is an instance

409:07

variable or a class variable. But if I

409:09

access it via the class name, it's more

409:12

explicit. So, it's good practice to

409:14

access a class variable by the class

409:17

name itself and not any one instance of

409:19

this class.

409:21

Let's create another class

409:23

variable. We'll create a class variable

409:26

to keep track of how many students we

409:28

have created. This class variable will

409:30

be num students meaning number of

409:34

students equals zero. So within our

409:37

constructor we can write any code that

409:39

we want. This code will always be

409:42

executed when we instantiate an object.

409:45

I would like to take our number of

409:46

students and increment it by one each

409:50

time we construct a new student object.

409:52

So instead of using self, self refers to

409:55

the object we're currently working with.

409:57

If we're constructing student one, just

409:59

imagine we're replacing self with

410:01

student one or student two if we were

410:04

constructing student two. If we're going

410:07

to be modifying a class variable, in

410:09

place of self, we'll use the name of the

410:12

class student. access our class of

410:15

student get the class variable of number

410:18

of students then I will increment it by

410:21

one plus equals

410:24

1. We are constructing two student

410:28

objects. I will

410:30

print access our class of

410:33

student get the number of students and

410:36

print it. We're constructing two student

410:39

objects. If I print the number of

410:41

students that we have, it should be two.

410:44

Then just to be sure that this is

410:46

working, let's construct a third student

410:48

object. Student three equals student.

410:53

This student will have a name of

410:55

Squidward. Squidward's age will be

410:59

55. Now we have three

411:02

students. And for good measure, let's

411:04

construct one more.

411:07

Student 4 equals we will create a new

411:11

student with a name of Sandy. Sy's age

411:15

will be

411:16

27. The number of students is now four.

411:20

Just as an

411:22

exercise using an fstring let's print

411:25

the student classes class year as well

411:28

as the number of

411:29

students. I will print use an F string

411:33

my

411:36

graduating class of let's add a

411:40

placeholder access the class of

411:44

student then access the class

411:47

year my graduating class of

411:52

2024 has then we need the number of

411:55

students we'll add a

411:56

placeholder access the class of

411:59

student access the number of

412:02

students has

412:04

blank

412:07

students. Let's see if this works. My

412:10

graduating class of 2024 has four

412:13

students. Now, if I were to change 2024

412:16

to 2025, my graduating class of 2025 has

412:21

four

412:22

students. Let's print the name of each

412:25

student. These are instance variables.

412:28

Student one

412:32

name. Then we need student two, three,

412:35

and

412:38

four. My graduating class of 2025 has

412:42

four students. Spongebob, Patrick,

412:44

Squidward, Sandy. All right, everybody.

412:47

So, those are class variables. Class

412:49

variables are shared among all instances

412:52

of a class. They are defined outside of

412:55

the constructor. The benefit is that

412:57

they allow you to share data among all

412:59

objects created from that class. And

413:02

well everybody, those are class

413:03

variables in

413:05

Python. What is going on everybody? So

413:08

today I got to talk about inheritance in

413:10

Python. Inheritance allows a class to

413:13

inherit the attributes and methods from

413:15

another class. Much like how a child in

413:18

real life can inherit traits from a

413:20

parent. By having a class inherit

413:22

attributes and methods from another

413:24

class, this helps with code reusability

413:27

and extensibility. In this example,

413:29

we're going to create an animal class.

413:31

The dog, cat, and mouse class will

413:33

inherit attributes and methods from the

413:36

animal class. We will create a class of

413:40

animal. Then I will define the

413:45

constructor. When we construct an animal

413:47

object, let's pass in a name. It's not

413:51

required, but it might be good for this

413:53

example. We will assign the attribute of

413:56

name equal to the name we

413:58

receive. Let's also add an attribute of

414:02

is alive. Whenever we create an animal,

414:05

we will set their is alive attribute to

414:07

be true and that is a capital

414:11

T. All animals can eat. Define eat. We

414:16

will print using an string. Add a

414:20

placeholder

414:21

self.name. The name of this animal is

414:25

eating. All animals should be able to

414:28

sleep. Define

414:31

sleep. Print. I'll use an

414:34

fstring. Insert

414:37

self.name is sleeping. And that is all

414:41

we need for the animal class. Let's

414:44

define class dog. For a child class to

414:48

inherit the attributes and methods from

414:50

another class after the class name

414:52

that's going to inherit, we need to add

414:55

an inheritance list with a set of

414:57

parenthesis. Then list the name of the

414:59

class we're inheriting from the parent.

415:02

The dog class is going to inherit all of

415:04

the attributes and methods of its parent

415:07

animal.

415:09

For the time being, as a placeholder,

415:10

I'll add pass just to demonstrate this.

415:14

Class cat is also going to inherit from

415:20

animal. And class mouse will also

415:24

inherit from

415:27

animal. Okay, I will collapse this for

415:29

now. We'll create a dog object. Dog

415:32

equals dog. Then pass in a name for this

415:35

dog because we have one parameter set up

415:38

of

415:38

name. This dog will be

415:42

named Scooby as in

415:45

Scooby-Doo. Cat equals call the cat

415:50

constructor. This cat will be named

415:54

Garfield. And

415:56

mouse mouse equals mouse. Our mouse will

416:00

have a name of

416:02

Mickey. Even though there's nothing

416:04

within this dog, cat, or mouse class, we

416:07

should still have these attributes and

416:09

these methods. If you inherit the animal

416:12

class, you should have a name attribute

416:14

and is alive attribute set to true. You

416:17

can eat and you can sleep. Let's print

416:20

our dog's name. dog.name.

416:27

Scooby print dog is

416:33

alive. Our dog is alive. That is

416:36

true. Let's have our dog object use the

416:39

eat

416:41

method. Scooby is eating and sleep. dog

416:46

sleep. Scooby is sleeping. Let's replace

416:50

dog with cat.

416:55

The name of the cat is Garfield.

416:57

Garfield is alive. Garfield is eating.

416:59

Garfield is sleeping. And

417:02

mouse. Replace any instance of cat with

417:05

mouse. Our mouse's name is Mickey.

417:08

Mickey is alive. Mickey is eating.

417:10

Mickey is sleeping. Even though these

417:12

children classes are empty, we're still

417:15

inheriting these attributes and methods

417:17

from its parent of animal. This is

417:19

convenient because you don't need to

417:21

copy and paste these attributes and

417:23

methods for every single class. For

417:26

example, if I were to copy these

417:27

attributes and methods and paste

417:32

them, well, we have a lot more code to

417:34

write. And as a consequence, if I need

417:37

to make a change to one of these

417:38

methods, I would have to do that to

417:40

every single instance of this method.

417:42

For example, let's replace is sleeping

417:44

with is asleep. Well, now I need to find

417:49

every single sleep method and change it

417:56

manually. It's not too bad if you only

417:58

have a few classes, but imagine if you

418:00

have hundreds of classes. That's going

418:02

to take a lot of work. It's a lot easier

418:05

to write the code once and then reuse

418:07

it. And I only need to make that change

418:09

in one place rather than make that

418:11

change many times. So, let's change is

418:14

sleeping to is asleep and see if that

418:17

works

418:19

again. Mickey is

418:21

asleep. Let's replace mouse with

418:26

dog. Scooby is asleep. Not only that,

418:29

but with children classes, they can have

418:32

their own attributes and methods that

418:34

are different from one

418:35

another. So, dogs have all these

418:37

attributes and methods and they can

418:40

speak.

418:41

Let's create a speak method. And I will

418:44

print a unique message for dogs. Woof.

418:48

Cats will also have a speak method, but

418:50

it's going to be

418:52

different. Cats will

418:57

meow. Then for our mouse class, they

418:59

will

419:04

squeak. Let's have our dog speak.

419:11

Woof. Let's have our cat

419:14

speak. Meow. And our

419:17

mouse.

419:18

Squeak. All right, everybody. So, that's

419:20

an introduction to inheritance.

419:22

Inheritance allows a class to inherit

419:25

attributes and methods from another

419:27

class. Much like in real life, a child

419:30

can inherit traits from a parent. These

419:33

are also known as sub and

419:36

superasses which is a topic for another

419:38

day. Inheritance helps with code

419:40

reusability and extensibility. If all of

419:43

these children classes inherit these

419:45

attributes and methods from another

419:47

class, we only need to write that code

419:49

once and not copy it for every single

419:52

class that needs it. We can write and

419:54

change the code in one place for better

419:56

reusability and extensibility. And well

419:58

everybody, that is an introduction to

420:00

inheritance in Python.

420:02

Hey everybody. So today we got to talk

420:04

about both multiple and multi-level

420:07

inheritance. We'll begin with multiple

420:09

inheritance. That's when a child class

420:11

inherits from more than one parent

420:13

class. For example, a class of C can

420:17

inherit the traits from both class A and

420:20

B. In Python, you can have more than one

420:22

parent. Multi-level inheritance we'll

420:25

talk about near the end of this topic.

420:27

So in this example, we're going to

420:28

create two parent classes.

420:31

prey. I'll write pass for

420:34

now. And

420:39

predator we'll create a class of

420:43

rabbit, a class of

420:48

hawk, then class

420:54

fish. Rabbit, hawk, and fish are going

420:57

to be children classes. Prey and

421:00

predator will be parents. If one of

421:03

these classes, rabbit, hawk, or fish,

421:05

inherit from prey, they get the ability

421:07

to flee. We will define a method of

421:11

flee. All we'll do in this example is

421:14

print the following

421:16

text. This animal is fleeing. If you're

421:21

a predator, you get the method to hunt.

421:24

Define hunt.

421:27

We will

421:29

print this animal is

421:34

hunting. Rabbits, they will inherit from

421:37

the prey class. They're typically not

421:39

predators except that one rabbit in

421:41

Montipython and the Holy Grail. That's

421:43

the exception. Rabbit will inherit the

421:46

prey class. Then it gets access to a

421:48

flea method. Hawks are predators. They

421:52

will inherit the predator class. Now

421:55

fish, they will hunt smaller fish and

421:59

flee from bigger fish. You can consider

422:01

fish both prey and predators. So they

422:04

will inherit both classes. We will use

422:07

multiple inheritance. They will inherit

422:10

everything from the prey class and the

422:12

predator class. Now let's see if this

422:14

does in fact work. Now we'll create a

422:16

rabbit object. Rabbit equals rabbit.

422:19

There are no parameter setup. We don't

422:21

need to send any arguments to the

422:22

constructor.

422:24

hawk equals

422:26

hawk and fish equals

422:29

fish. So, let's take our rabbit object

422:32

and they should have a flea method.

422:34

Rabbit.flea method. This animal is

422:37

fleeing, but they do not have a hunt

422:39

method because they're not

422:41

predators. Rabbit object has no

422:44

attribute hunt. Hawks can

422:47

hunt. They're predators. They inherited

422:50

that method. This animal is hunting, but

422:53

they can't flee. They're not prey. Hawk

422:57

object has no attribute flee. Fish can

423:00

do both. They inherit from the prey

423:02

class and the predator

423:05

class.

423:06

Fish.fle. This animal is fleeing.

423:11

Fish.unt. This animal is hunting.

423:14

Children classes can inherit from more

423:16

than one parent, which is what we did

423:18

for fish. They are both prey and

423:20

predators. Whereas in rabbits are just

423:23

prey, hawks are just predators. If you

423:25

need to inherit from more than one

423:27

parent, you just add that additional

423:29

class to the inheritance

423:31

list. With multi-level inheritance, a

423:35

parent can inherit from another parent.

423:38

We will create a

423:39

class of

423:41

animal. And for now, I'll write pass.

423:44

Prey and predator are going to inherit

423:47

from the animal class. So, we need to

423:49

add animal to each inheritance

423:53

list. Let's say if you're an animal, you

423:56

get a method to eat. All animals will

424:00

eat.

424:02

Print this animal is eating and you can

424:07

sleep. Define

424:10

sleep.

424:12

Print this animal is sleeping.

424:18

So think of rabbit, hawk, and fish as

424:22

children classes. Prey and predator are

424:25

those classes parents, and animal is the

424:29

grandparent. Prey and predator will

424:31

inherit everything that the animal class

424:33

has. Rabbit, hawk, and fish will inherit

424:37

everything the prey and predator classes

424:38

have. So now our rabbit, hawk, and fish

424:41

classes should have the ability to eat

424:44

and sleep. And we'll test that.

424:48

Rabbit. This animal is eating.

424:52

Rabbit. This animal is sleeping. Let's

424:55

check out fish. fish

424:58

fish. This animal is eating.

425:02

Fish. This animal is

425:05

sleeping. Okay, we're going to expand

425:07

upon our example a little bit. Let me

425:09

zoom out. Each of our objects is going

425:12

to have a name. Our rabbit will have a

425:15

first name of bugs. Hawk will be Tony as

425:19

in Tony Hawk. Our fish will be

425:24

Nemo. Within our classes, we don't have

425:26

any constructor set up. In which class

425:29

should we assign the name

425:32

attribute? Let's do so within our animal

425:35

class. So, we will define a

425:39

constructor to assign these attributes.

425:42

we will receive a

425:44

name. We'll assign

425:47

self.name equals name. Now, with these

425:51

other classes, if you're not assigning

425:53

any attributes or if you don't need any

425:55

other initialization logic, you don't

425:57

need a constructor. We'll implicitly use

426:00

the constructor we inherit from the

426:02

parent. Let's convert each of these

426:04

print statements to an fstring.

426:10

Replace animal with

426:21

self.name. Now let's have our rabbit use

426:25

the eat

426:28

method. Oh, we should get rid of

426:34

this. There we go. Bugs is eating

426:38

rabbit.

426:41

Bugs is sleeping. Rabbit

426:44

flee. Bugs is fleeing. Let's check out

426:47

our hawk. Hawks don't have a flea method

426:50

because they're predators, not

426:53

prey. Let's eat. Tony is eating. Let's

426:58

sleep. Tony is sleeping. Let's

427:02

hunt. Tony is hunting. Let's check our

427:06

fish next. Our fish can eat. Nemo is

427:09

eating. Our fish can

427:11

sleep. Nemo is sleeping. They can

427:15

flee. Nemo is fleeing and

427:19

hunt. Nemo is hunting. Okay, everybody.

427:23

That is both multiple and multi-level

427:25

inheritance. With multiple inheritance,

427:28

a child can inherit from more than one

427:31

parent class. You just add each

427:33

additional class to the inheritance

427:35

list. With multi-level inheritance, a

427:39

child can inherit from a parent which

427:41

inherits from another parent. Class C

427:44

can inherit from B where class B

427:47

inherits from A. Think of C as the

427:50

child, B is the parent and A as the

427:53

grandparent. C will have all the

427:55

attributes and methods even available

427:57

within the grandparent class of A. And

427:59

well everybody that is both multiple and

428:01

multi-level inheritance in Python. Hey

428:05

everybody. So today I got to talk about

428:07

the super function in Python. Super is a

428:10

function. It's used within a child class

428:13

to call methods from a parent class. The

428:16

child class is the subclass. The parent

428:18

class is the superass. Hence why this

428:21

function is named the super function.

428:23

Using the super function, it allows you

428:25

to extend the functionality of the

428:27

inherited methods. Here's an example.

428:30

We'll create a few shape objects. We'll

428:32

need to set up the classes though. We'll

428:34

have class

428:36

circle. For the time being, I'll just

428:38

write pass. We'll fill it in later.

428:40

Class

428:44

square and

428:46

class

428:49

triangle. For each of these classes, in

428:52

order to instantiate objects, we'll need

428:53

a constructor. We will define our

428:56

constructor, our innit method.

429:00

When creating circles, what sorts of

429:02

attributes should a circle have? Let's

429:04

say a color. What's the color of the

429:07

circle? Is it filled or

429:10

not? Filt will be another attribute and

429:13

a

429:14

radius. Then let's assign

429:17

these. Self doc color equals the color

429:20

that we receive. self

429:24

do.filled equals

429:26

filled. Self do.t radius equals

429:31

radius. Let's do this with the square

429:33

and triangle. Really, I'll just copy our

429:36

constructor and paste it. Squares don't

429:39

have a radius. With a square, the width

429:42

and the height are the same. Let's

429:44

replace radius with width. We'll also

429:46

keep the color and field

429:48

attributes. Self do width equals width.

429:53

Now, with

429:54

triangles again, let's copy our

429:56

constructor. We'll need a width and a

430:01

height.

430:03

self.height equals

430:05

height. So with programming, we try not

430:08

to repeat ourselves if we don't have to.

430:10

What do all of these classes have in

430:12

common? They all share the attributes of

430:15

color and

430:18

filled. The ways in which they are

430:20

different is that circle has a radius

430:22

attribute, square has a width, triangle

430:25

has a width and a height. If we have to

430:27

make any changes to one of these

430:28

attributes, we would have to do so

430:31

manually. For example, let's replace

430:33

filled with is filled. Now, I need to

430:35

look throughout my code for any instance

430:37

of filled and replace it with is

430:40

filled. It's a lot of work and I might

430:43

make a

430:44

mistake such as here and here. It's

430:48

better to write your code once and try

430:50

and reuse it. So, that's where

430:51

inheritance and the super function can

430:53

come in handy. We're going to take the

430:55

attributes of color and is filled and

430:57

place it within a parent class. These

430:59

children classes will inherit those

431:02

attributes. So class, what do they all

431:05

have in common? They're all shapes.

431:07

Class shape. And for now, I'll write

431:10

pass. Circle is going to inherit from

431:13

its parent of shape. That also applies

431:16

with square and triangle. We'll set up a

431:19

constructor for shape.

431:22

define

431:25

init. We will pass in the color and is

431:32

filled. Then we will assign these

431:35

attributes self.c color equals

431:39

color

431:42

self.isfilled equals is filled. We don't

431:46

need to manually assign these attributes

431:48

within each of these constructors for

431:49

the children.

431:52

Instead what we have to do is within the

431:54

constructor for each of these children

431:56

classes we have to call the constructor

431:58

for the parent also known as the

432:01

superass of shape. So we will eliminate

432:04

these two lines of

432:05

code. Use the super

432:09

function dot call the constructor of the

432:12

parent that is the dunder init method.

432:16

But we need to pass in the color that we

432:19

receive and is filled. This will be a

432:23

boolean. And let's do this with the

432:26

square

432:27

class and the triangle class.

432:31

We still need radius for the circle,

432:33

width for the square, width and height

432:35

for the triangle. We're going to call

432:37

the super function to take care of

432:39

whatever attributes all these types of

432:41

shapes have in common such as color and

432:44

is filled. Now let's see if this works.

432:46

Let's construct a few objects. We will

432:48

create a circle named

432:50

circle called a constructor for circle.

432:53

We have to pass in a color, a boolean if

432:56

it's filled or not, and a radius. So for

432:59

the color of the circle, let's say

433:02

red is filled. Let's say that is true.

433:06

And a radius of five. You could even use

433:09

keyword arguments for better

433:10

readability. Although not necessary, but

433:13

for clarity, let's say color equals

433:16

red is filled equals

433:19

true radius equals

433:22

5. Let's see if this works.

433:25

I will print our circles

433:32

color. It is

433:35

red. Print our colors is filled

433:39

attribute. The circle is filled. That is

433:42

true. And the

433:44

radius print

433:46

circle dot radius. The radius of the

433:50

circle is five. We could even convert

433:52

this to an string.

433:55

I'll add a

433:59

placeholder. Then add

434:03

centimeters 5 cm. Let's construct a

434:07

square

434:08

object. Square equals

434:11

square. We'll need a color is filled and

434:14

a width. I'll just copy what we have and

434:16

make a few changes. Replace radius with

434:19

width. The color will be blue. Is filled

434:24

will be false. The width will be six. We

434:27

don't need a height because squares have

434:29

an even width and height. If we ever

434:31

need the height, we can assume it's the

434:33

same as the width. In this case, six.

434:36

Let's check out our square. Square.color

434:40

square.filled

434:44

square.idth. Our square is blue. It's

434:47

not filled in. The width is 6 cm.

434:51

Let's create a triangle object. Triangle

434:54

equals

434:56

triangle. Pass in our

434:59

arguments. The color will be yellow. Is

435:02

filled will be true. The width will be

435:06

seven. And the height will be

435:10

eight. Let's print our triangle's color.

435:13

Is it filled? Its width and its

435:17

height.

435:21

Our triangle is yellow. It's filled in.

435:25

The width is 7 cm. The height is 8

435:28

cm. So that's how you can use the super

435:31

function to reuse the constructor of a

435:33

parent class. We don't need to manually

435:36

assign each of these attributes within

435:38

each of the children classes. We can do

435:40

that in just one place. When we refer to

435:43

super, imagine that we're replacing this

435:45

with the parent class name such as

435:48

shape. That might be a good way to think

435:51

of

435:52

it. Use the constructor of the parent

435:55

class of shape and pass these arguments

435:58

in. What you could do as well is extend

436:01

the functionality of a method. So within

436:03

our shape class, let's create a method

436:07

of describe.

436:09

We will describe the attributes of this

436:11

shape. We will

436:14

print use an fstring. When we want to

436:17

describe our shape, let's say it is at a

436:20

placeholder self doc color. What is the

436:24

color of this shape? And is it filled or

436:27

not? And add a placeholder. We'll use a

436:30

turnary operator. Print

436:34

filled. If self is filled is true else

436:40

we will

436:42

print not

436:45

filled. Each of these types of shapes

436:48

circle square and triangle will have

436:50

access to a describe

436:52

method. Let's attempt to use

436:55

it. Take our circle. Use the describe

436:58

method that's inherited.

437:01

It is red and filled

437:04

square. It is blue and not filled

437:08

triangle. It is yellow and

437:11

filled. So then we also have method

437:13

overwriting. What if we create a similar

437:16

method of describe within circle,

437:18

square, and triangle? Let's do

437:21

that.

437:23

Define a describe

437:27

method within our circle. Let's

437:30

calculate the area. What's the area of

437:32

the circle? I'll use an F string. It is

437:36

a

437:37

circle

437:38

with an area of then we'll calculate the

437:43

area given the

437:44

radius. To calculate the area of a

437:47

circle, we can take pi, I'll just say

437:49

3.14 just to keep it simple, times the

437:52

radius squared

437:54

self. Time self.raius.

437:59

If I were to call the describe method,

438:01

will we use the parents version of

438:03

describe or the

438:06

child? So let's take our circle use the

438:10

describe

438:11

method. The result it is a circle with

438:15

an area of 78.5. I should really add

438:19

centime squared after

438:21

that. Cime

438:24

squared. This is called method

438:26

overwriting. If a child shares a similar

438:29

method with a parent, you'll use the

438:31

child's version and not the parents.

438:34

This is method overriding. If you would

438:36

like to extend the functionality of a

438:38

method from a parent, you can use the

438:41

super function. Not only do I want to

438:43

use the describe method of the child, I

438:45

would also like to use the describe

438:47

method of the parent. So within this

438:50

function we will use the super function

438:53

access the describe method of the

438:56

parent. What we're doing is extending

438:58

the functionality of the describe

439:02

method. It is a circle with an area of

439:05

78.5 cm squared. The circle is red and

439:09

it's

439:10

filled. Or you could change up the

439:12

order.

439:15

Let's use the parent classes describe

439:17

method and extend the functionality with

439:20

our own print

439:21

statement. It is read and filled. It is

439:24

a circle with an area of 78.5 cm

439:27

squared. Let's finish this with the

439:29

square and triangle classes. I'll copy

439:32

what we have for the describe method

439:33

within the circle class, but we'll make

439:36

a different

439:39

calculation. Describe the square. It is

439:42

a square with an area of take self

439:46

dowidth times

439:50

self.width. The height and the width are

439:52

going to be the same if it's a

439:54

square. Then describe our

440:00

triangle. It is a

440:03

triangle with an area of width time

440:06

height. We have a height in this case

440:08

divided by two. We've already described

440:11

our circle. Let's describe our

440:14

square. It is a square with an area of

440:17

36 cm squared. It is blue and not

440:20

filled. Let's describe our

440:22

triangle. It is a triangle with an area

440:25

of 28.0 cm squared. It is yellow and

440:29

filled. All right, everybody. That is

440:31

the super function. It's used in a child

440:33

class to call the methods from a parent

440:36

class, also known as the superass. It

440:39

allows you to extend the functionality

440:41

of the inherited methods within a child

440:44

class. You could use it within a

440:45

constructor to assign any attributes

440:48

that all of its siblings have in common,

440:50

such as color or if that shape is

440:53

filled. When used within any other

440:55

method, you can extend the functionality

440:58

of that method. Not only are we printing

441:00

this message from the parent, we're

441:02

tacking on another print statement

441:04

before that. And well everybody that is

441:07

the super function in Python. What is

441:10

going on everybody? So today I got to

441:12

talk about polymorphism in Python.

441:15

Polymorphism is a programming concept.

441:17

It's a Greek word that means to have

441:19

many forms or faces. Poly means many.

441:23

Morph means form. In programming, an

441:26

object can take one of many forms.

441:28

There's two ways to achieve

441:29

polymorphism. One is through

441:31

inheritance. An object could be treated

441:33

of the same type as a parent class.

441:36

There's also duct typing, which we'll

441:38

talk about in the next topic. In this

441:40

video, we're more focused on

441:41

inheritance. What we'll do in this video

441:43

is create a class of shape. We'll write

441:47

pass as a placeholder. We will create a

441:50

class of circle which will inherit from

441:53

shape. Again writing

441:56

pass class square inherits from

442:02

shape class

442:05

triangle which inherits from

442:10

shape. If I was to create a circle

442:12

object circle equals

442:15

circle our circle identifies as a

442:18

circle. And since our circle class

442:20

inherits from the shape class, our

442:22

circle is also considered a shape. It

442:25

has two forms. It's a circle and it's a

442:28

shape. But our circle isn't a square or

442:30

a triangle. That could also apply to our

442:32

square

442:34

class. Our square is a square. Our

442:37

square is also considered a shape. But

442:39

our square is not a circle or a

442:40

triangle. Those are two possible forms

442:43

for our square. It's a square and a

442:45

shape. So let's say we would like to

442:47

create a list of shapes. What do they

442:49

all have in common? Well, they're all

442:51

shapes. A descriptive name for this list

442:54

would be shapes equals an empty list. I

442:58

will instantiate a circle object, a

443:01

square

443:02

object, and a triangle

443:06

object. Our circle is a circle and a

443:09

shape. Our square is a square and a

443:11

shape. Our triangle is a triangle and a

443:14

shape. Each of these objects has two

443:17

forms or two faces. Let's fill in some

443:20

of these classes. Let's say that with

443:22

our shape class, we will define an area

443:25

method. Define area. I'm going to turn

443:29

this into an abstract method. I'll just

443:31

write pass. To work with abstract

443:34

classes, we need to import that from

443:37

ABC import capital ABC as well as

443:42

abstract method. Preceding the area

443:45

method, I will add a decorator of

443:47

abstract method. Our circle, square, and

443:50

triangle classes, they're all considered

443:52

shapes. They inherit from this class. We

443:55

need to define an area method for each

443:57

since they're all considered a shape.

444:00

Every shape has an area with our class

444:02

of circle. Let's define a

444:05

constructor. Define

444:08

init. We will pass in one argument. A

444:11

radius. What is the radius of the circle

444:14

assign an attribute of radius equals the

444:17

radius we receive. Let's do this with

444:20

square. Define

444:23

innit one parameter the length of a

444:27

side. self dot side equals side then

444:33

triangle define

444:37

init. We have two parameters base and

444:43

height

444:45

self.base equals

444:47

base

444:49

self.height equals

444:51

height. All right. Now let's finish

444:53

defining these area methods for each

444:55

class.

444:57

We will

445:00

return

445:02

3.14

445:04

time

445:06

self.US to the power of

445:08

2. So given a radius that's how to

445:11

calculate the area of a circle. Then

445:14

with our

445:16

square define

445:19

area we will

445:22

return self do side to the power of

445:28

two. Then with our

445:31

triangle define

445:35

area

445:37

return

445:39

self.base time self.height

445:42

height time

445:45

0.5. Now we have to pass in some

445:47

arguments. For our circle, we need a

445:49

radius. I'll pick four. For the square,

445:52

the length of a side will be five. Then

445:54

our triangle, the base will be six. The

445:57

height will be seven. We're going to

445:59

write a loop to iterate through our

446:01

shapes. for every shape in

446:05

shapes. Then we're going to

446:07

print for every shape called the area

446:14

method. And that would give me these

446:17

numbers. If you would like, you can

446:19

format the output. I'll just use an F

446:25

string. I'll add centime squared.

446:35

Much better. What if we were to create a

446:38

class that's completely unrelated to

446:41

shapes? I will create a class of

446:47

pizza. I will define a

446:50

constructor. To construct a pizza

446:52

object, we need a

446:55

topping and a radius. What is the radius

446:58

of the pizza?

447:01

self. Equals

447:05

topping

447:07

self.raius equals

447:09

radius. Within my list of shapes, I'll

447:12

add a pizza

447:13

object. But I have to pass in a topping

447:16

such as

447:19

pepperoni. And what is the radius of the

447:22

pizza? Let's say 15 cm. So, our pizza,

447:26

our pizza class doesn't have an area

447:28

method. Here's what happens when I run

447:31

this. We get an attribute error. Pizza

447:35

object has no attribute

447:37

area. Our pizza object is considered a

447:40

pizza, but it is not considered a shape.

447:43

It does not inherit from the shape class

447:46

at the top here. You know what? A pizza

447:48

is circular. It could be considered a

447:50

circle. So, how about this? Let's take

447:53

the pizza class. it will inherit from

447:55

the circle class. And within our circle

447:58

class, we're already assigning the

448:01

radius to the radius attribute. So

448:03

instead of doing that here within the

448:05

constructor for our pizza class, let's

448:07

call the super constructor super, which

448:10

refers to the parent, use its

448:13

constructor, then pass in the radius we

448:16

receive. Let's see if this works.

448:20

Now that does. Here is the area of our

448:24

pizza. Our pizza is considered a pizza.

448:27

It inherits from the circle class. So,

448:29

it's also considered a circle. And our

448:31

circle class inherits from the shape

448:34

class. Our pizza has three forms. Our

448:37

pizza is considered a pizza. It's also

448:40

considered a circle and it's also

448:41

considered a shape. It would make sense

448:44

for it to fit into this list of shapes

448:46

because our pizza also identifies as a

448:49

shape. So that's polymorphism everybody.

448:52

It's a Greek word meaning to have many

448:54

forms or faces. Poly meaning many, morph

448:57

meaning form. In Python, there's two

448:59

ways to achieve polymorphism. One

449:01

through inheritance. An object could be

449:03

treated of the same type as a parent.

449:06

And there's also duct typing, which

449:08

we'll discuss more in the next topic.

449:10

Stay tuned for that. And well everybody,

449:12

that's polymorphism in

449:15

Python. Hey everybody. So today I got to

449:18

talk about duct typing in Python. Duct

449:20

typing is another way to achieve

449:22

polymorphism besides using inheritance.

449:25

Objects can be treated as if they're a

449:26

different type as long as they meet the

449:28

minimum necessary attributes and methods

449:30

required of them. It follows this adage.

449:33

If it looks like a duck and quacks like

449:36

a duck, it must be a duck. As long as an

449:39

object resembles another, it could also

449:42

be treated of that type. So in this

449:44

example, let's create a class of animal.

449:48

We will have a class attribute of alive.

449:51

If you're an animal, you will have an

449:54

attribute of alive. You're a living

449:56

creature. Let's create a class of dog.

450:00

The dog class will inherit from the

450:02

animal class. They will inherit the

450:05

alive attribute. Let's also define a

450:07

speak method. If you're a dog, you gain

450:10

the ability to speak. We will

450:14

print woof. Then we'll create a cat

450:19

class. Class cat inherits from animal.

450:23

For the speak method, we will print

450:26

meow. Let's create a list of animals.

450:29

What do these two classes have in

450:31

common? They both can be considered

450:33

animals. Let's create a list of

450:36

animals. We will construct a dog object

450:40

and a cat object.

450:42

If I was to write a for loop for every

450:45

animal in my list of

450:48

animals, have each animal use its speak

450:52

method, which will result in the dog

450:56

going woof, the cat going meow, they're

450:58

both

450:59

speaking. What if we add a class that

451:02

has nothing to do with

451:04

animals like class car?

451:08

Cars will have a horn method. That's how

451:11

they

451:12

speak. When you honk the horn, you will

451:16

print

451:18

honk. Within my list of animals, let's

451:22

create a car object. It really doesn't

451:24

belong in here, but let's see what

451:28

happens. We have an attribute error. Car

451:31

object has no attribute

451:34

speak. Our car object doesn't have the

451:37

minimum necessary attributes and

451:40

methods. When iterating through this

451:42

list of animals, we're calling each

451:44

animal speak method, which our car

451:47

object doesn't have, but it does have a

451:49

horn method. So, what if we rename our

451:52

horn method as speak? Maybe it's an AI

451:56

car or

451:58

something. Well, this would work. The

452:01

dog goes woof. The cat goes meow. The

452:03

car goes

452:05

honk. So our car

452:08

object, it quacks like a duck. We could

452:11

consider it a duck. It has the minimum

452:14

necessary methods to be considered an

452:17

animal. Animals inherit this alive

452:20

attribute. Let's utilize that. After the

452:23

animal

452:24

speaks, let's print their alive

452:28

attribute. Print my animals alive

452:31

attribute. my car object doesn't have

452:34

that attribute. We get an attribute

452:36

error. Car object has no attribute

452:40

alive. But if I was to add that

452:43

attribute alive equals

452:48

false, we have true for the dog, it's

452:51

living. True for the cat, it's living.

452:53

But false for the car, it's not living.

452:56

It's not a living creature.

452:59

My car meets the minimum necessary

453:01

requirements to be considered an animal.

453:04

If I were to set this to be

453:07

alive, well then it would be a living

453:09

car. Kind of like the movie Cars. So

453:13

with Python, duct typing is another way

453:16

to achieve polymorphism besides using

453:18

inheritance. As long as an object has

453:20

the minimum necessary attributes and

453:22

methods, you could treat it as a

453:24

different type of object. If it looks

453:26

like a duck and quacks like a duck, it

453:29

must be a duck. And well everybody, that

453:31

is duck typing in

453:34

Python. Hey, what's going on everybody?

453:36

Today I'm going to talk about static

453:38

methods in Python. A static method is a

453:41

method that belongs to a class rather

453:44

than any object from that class, any

453:47

instance. Instance methods, we're

453:49

already familiar with them. They are

453:51

methods that belong to individual

453:53

objects created from that class. They're

453:55

best for operations on instances of that

453:58

class, any objects. Whereas static

454:01

methods, they're best for utility

454:03

functions within a class that do not

454:05

need access to class data. I'll

454:07

demonstrate the differences between an

454:09

instance method and a static method.

454:12

We'll begin by creating a class of

454:15

employee. We'll need a constructor.

454:18

Let's define

454:20

that. To create an employee object,

454:23

we'll need a name and a job

454:26

position. We will assign

454:29

self.name equals name.

454:33

self.position equals

454:36

position. We will create an instance

454:39

method of get info. We will return

454:42

employee

454:44

info. We will return an fstring where we

454:48

will display self.name.

454:52

name equals

454:57

self.position. Get info is an instance

455:00

method. Each object that we create from

455:03

this class will have their own get info

455:05

method to return the information on that

455:08

object. The object's name and the

455:10

object's position. Now we'll create a

455:13

static

455:13

method. To create a static method, we

455:16

need a decorator of static method.

455:20

Static methods are best for general

455:23

utility functions within a class. We'll

455:25

define a method to check to see if a job

455:29

a position is valid, which we will name

455:32

is valid

455:35

position. So static methods, they don't

455:38

have self as the first argument. We're

455:40

not working with any objects created

455:42

from this class. To check to see if a

455:44

position is valid, we will pass in a job

455:47

position, which I will name as

455:51

position. I will create a list of

455:54

valid

455:57

positions. Let's assume that our company

455:59

is the Krusty Krab. What are some valid

456:02

positions? A manager is a valid

456:05

position, a

456:07

cashier, a cook, then let's say a

456:10

janitor.

456:14

Then we will return we'll use a

456:17

membership

456:18

operator. Check if position that we

456:22

receive is in our list of valid

456:29

positions. What we have done is that we

456:31

have created a static method. We don't

456:34

need to rely on any objects to use this

456:36

method. For

456:39

example, to use a static method, we will

456:42

use the name of the class rather than

456:44

any object that we create from this

456:46

class such as

456:48

this. We don't need to do

456:51

that. We type the class name followed by

456:55

the static method is valid

457:01

position. Then I did set this up to

457:03

accept one argument. Let's check to see

457:06

if a cook is a valid

457:10

position. Then I do need to print this.

457:13

What is the

457:15

output? A cook is a valid position. What

457:19

about a rocket scientist? That would

457:22

probably be Sy's job. That is false. A

457:27

rocket scientist is not a valid position

457:29

at the Krusty

457:30

Krab. This is a static method. It

457:33

belongs to the class, not any object

457:35

created from that class. Now let's

457:38

create a few employee objects. Let's say

457:40

employee 1 equals a new

457:44

employee. We have to pass in a name and

457:47

a job. Eugene will be the first name.

457:50

That's Mr. Krabs. He will be a

457:54

manager. Employee

457:57

2 equals

458:00

employee

458:02

Squidward will be a

458:06

cashier. Employee

458:09

3 equals

458:11

employee. Employee 3 will be

458:14

Spongebob. Spongebob will be a

458:17

cook. To call an instance method, we

458:20

have to access one of the instances of

458:22

the class in order to use it.

458:25

If I want to check the info on employee

458:27

1, I will access that object, that

458:31

instance. Use the get info method. Then

458:35

I need to print

458:38

it. Take employee one, get the info.

458:42

Eugene is the manager. Let's do this

458:45

with employee 2 and employee

458:50

3. Eugene, Mr. Krabs, is the manager.

458:53

Squidward is the cashier. Spongebob is

458:56

the cook. For an instance method, you

458:59

access an object, then call the instance

459:01

method. With a static method, you only

459:04

need to access that class. You don't

459:07

even need to create any objects from

459:08

that class. It's a general utility

459:12

method. All right, everybody. Those are

459:14

static methods. They're a method that

459:17

belongs to a class rather than any

459:19

objects created from that class. They're

459:21

usually used for general utility

459:23

functions that do not need access to

459:26

class data. And well everybody, those

459:28

are static methods in

459:30

Python. Hey, what's going on people? So

459:33

today I got to talk about class methods

459:35

in Python. A class method allows

459:38

operations related to the class itself.

459:40

They take CLS as the first parameter

459:43

whereas instance methods will take self.

459:46

Self refers to any object created from

459:48

that class. Cls meaning class refers to

459:51

the class not any objects. Here's an

459:54

example. We will create a class of

459:58

student. We'll need a constructor to

460:01

construct some student

460:03

objects. All students will have a name

460:06

and a

460:08

GPA. self.name equals name.

460:14

self.gpa equals GPA.

460:17

We will also create a class variable for

460:20

this demonstration of count. We will

460:23

count how many students we

460:25

create. Whenever we construct a student

460:28

object, we will access the class of

460:31

student take our count variable

460:34

incremented by one. Whenever we create a

460:37

student object increase count by

460:40

one. I will create an instance method of

460:44

get

460:47

info. Instance methods have self as the

460:50

first parameter. We're referring to the

460:53

object we're currently working with. I

460:55

will return an fstring where we will

460:59

display the students name and their GPA.

461:03

self.name

461:05

name

461:08

self.gpa. I'll add a comment that this

461:11

is an instance

461:14

method. Now to create a class method to

461:17

work with class data, we will declare a

461:20

class method with a class method

461:22

decorator. Class

461:26

method. What we're going to do is define

461:28

a method to get the count the class

461:31

variable of count.

461:33

This method will be called get

461:37

count. Rather than self as the first

461:39

parameter, we'll be working with a class

461:43

cls meaning

461:44

class. I will return an

461:47

fstring total number of

461:53

students. Add a

461:55

placeholder cls

461:57

count. Let's test this. To call a class

462:01

method, you take the name of the class

462:04

followed by the class method get count.

462:07

And then we do need to print

462:12

this. What is the count of my current

462:15

students? Total number of students is

462:18

zero. Let's create a few student

462:20

objects. We will create student one

462:23

equals call the student constructor. We

462:26

have to pass in a name and a GPA. Let's

462:29

say that the name is Spongebob.

462:31

Spongebob has a GPA of

462:34

3.2. We'll create two more

462:37

students. Student two. Student three.

462:40

Student two will be

462:42

Patrick. Patrick has a

462:46

2.0. Then Sandy. Syy's smart. In fact,

462:50

she's a genius. She has a perfect

462:53

4.0. Now, let's count the number of

462:56

students.

462:57

Total number of students is

463:00

three. When we call this class

463:03

method, we can access or modify class

463:06

data. This class variable of count.

463:10

Rather than using self, we use CLS for

463:13

the

463:14

class. Let's create one more class

463:16

method. This time I'll calculate the

463:19

total GPA of all my

463:22

students. We'll need a class variable to

463:24

hold that data. Let's say total GPA

463:29

equals

463:31

zero. Whenever we construct a student

463:33

object, we will access our class of

463:36

student get the total

463:40

GPA. Then add plus equals this student's

463:44

GPA that we have just created.

463:47

Basically speaking, the total GPA, this

463:50

variable is going to accumulate all of

463:52

the GPA of every student and store it as

463:55

a sum. To find the average, we're going

463:57

to divide it by the count, the number of

464:00

students. We'll do that within a class

464:02

method. To create a class method, again,

464:04

we need to use the class method

464:07

decorator. I will define a method of get

464:11

average GPA. The first parameter is cls

464:15

for

464:16

class. I will check if cls count the

464:22

count variable of my class is equal to

464:26

zero. That means if we have no students.

464:29

If that's the case, if there's no

464:30

students, we're going to return

464:32

zero because otherwise we're going to

464:35

divide by zero and we'll get an

464:38

error. else we're going to return an f

464:42

string. Follow this formula. We're going

464:45

to take the total GPA of my class. Class

464:48

dot total GPA divided by class.c count

464:53

the number of students we have. That's

464:55

how to calculate the average

464:57

GPA. After getting the count of the

465:00

number of students to access a class

465:02

method, we take the name of the class

465:04

student call the class method get

465:07

average

465:08

GPA. Then I will print

465:15

it. Total number of students is three.

465:18

The average GPA is 3.06

465:22

repeating. After calculating the

465:24

average, I'm going to add a format

465:26

specifier of 2F just to round to two

465:29

decimal places. And I'll add average GPA

465:34

colon space. Then we'll calculate the

465:39

average. All right, everybody. Those are

465:41

class methods. Instance methods are best

465:44

for operations on instances of the

465:47

class, any objects. Static methods are

465:50

best for general utility functions which

465:53

do not need access to class data. Class

465:56

methods are best used when we're working

465:58

with class level data or we require

466:01

access to the class itself such as when

466:04

we're working with class variables

466:06

rather than using self as the first

466:08

parameter. We're going to use cls

466:10

meaning class. And well everybody those

466:13

are class methods in

466:15

Python. Yo, what's going on people? So

466:18

today I'm going to explain magic methods

466:21

in Python. Magic methods are also known

466:23

as dunder methods meaning double

466:26

underscore. You typically find these

466:27

within classes. We're already familiar

466:29

with one of them. Our dunder init

466:31

method. We have double underscores on

466:33

the left and double underscores on the

466:35

right, but there are others. I'll cover

466:38

a few of the more beginner friendly

466:39

ones. So, what these methods do is that

466:42

they're automatically called by using

466:44

some of Python's built-in operations

466:47

such as printing an object, seeing if

466:49

two objects are equal, greater than, or

466:52

less than. When we use many of Python's

466:54

built-in operations with objects, we can

466:57

define and customize the behavior of

466:59

those objects. So, in this

467:01

demonstration, I'm going to create a

467:03

class of book. We will construct some

467:06

book objects. We will define a magic

467:09

method, a dunder method of init. To

467:12

initialize these objects for a book, we

467:15

need a title, an author, and the number

467:20

of pages. We'll say num

467:23

pages.

467:25

self.title equals

467:28

title.

467:30

Self.author equals author.

467:34

self dot number of

467:36

pages equals number of pages. When we

467:40

call the class of book, we are

467:41

automatically calling done a nit. So

467:44

let's create a book object. Book one

467:47

equals

467:48

book. We need a title, an author, and

467:51

number of pages. So since we're dealing

467:53

with this topic of magic methods, I'll

467:55

pick some fantasy related books. For my

467:58

first book, I'll pick The

468:00

Hobbit. That's the title. The author is

468:05

JRR Tolken. The number of pages is

468:10

310. So for my next

468:12

book, book

468:14

two, I will

468:17

pick Harry

468:19

Potter and the Philosopher

468:26

Stone. The author is JK Rowling.

468:31

The number of pages is

468:34

223. Then we have book

468:39

three. For my third book, I will pick

468:42

The Lion, The

468:44

Witch, and The

468:49

Wardrobe. The author is CS

468:53

Lewis. The number of pages is 172. Okay,

468:58

here are my three book objects. When we

469:00

call the class of book and pass in

469:02

arguments, we will call the dunder init

469:05

method. It's a magic method. It's

469:07

automatically called behind the scenes.

469:10

Within this magic method, we can define

469:12

and customize the behavior of objects.

469:15

And in this example, we're just

469:16

assigning the attributes of title,

469:18

author, and number of pages. That is one

469:22

built-in operation of Python. What would

469:24

happen if I was to print book one

469:27

directly to the console? Here's what

469:30

happens. Well, we're given a memory

469:33

address. Here's book two and book

469:37

three. Well, we can customize this

469:41

behavior. We will use the dunder string

469:46

method. Double underscore str meaning

469:49

string double underscore. Again, we have

469:52

one parameter of self. Instead of

469:54

returning a memory address, we can

469:56

customize this behavior.

469:59

Let's instead return an

470:01

fstring. I'll add two placeholders. We

470:04

will display self.title, the title of

470:07

the book by

470:11

self.author. And I'll place the title

470:13

within single

470:15

quotes. Now, let's print book one. We

470:18

have The Hobbit by JRR

470:21

Tolken. Let's print book two.

470:25

Harry Potter and the Philosopher Stone

470:26

by JK Rowling and book three, The Lion,

470:30

the Witch, and the Wardrobe by CS Lewis.

470:33

So that is dunder string. We can return

470:36

a string representation of the object

470:38

when we print it directly to the

470:41

console. Here's another dunder method.

470:43

We can check to see if two objects are

470:45

equal. I will

470:48

print is book one equal to book two.

470:54

That gives me

470:55

false. If they were to have the same

470:59

title, the same

471:01

author, and the same number of

471:05

pages, then Python would say they're not

471:07

equal still. So, let's customize this

471:13

behavior. We will define a method of

471:16

dunder equals, which is just

471:19

EQ. For parameters, we have self, the

471:22

first book we're examining. In this

471:24

case, book one and other. Other means

471:27

the other book. We're examining two

471:29

objects for

471:31

equality. To do that, we'll see if the

471:33

title of two books and the author is the

471:37

same. We'll disregard the number of

471:40

pages. You can have two different

471:42

versions of the same book. They might

471:44

have different font sizes or the

471:46

dimensions of the physical pages might

471:48

be

471:49

different. So, we will return a boolean

471:51

value. We will examine if self that's

471:55

the first book is the title

471:58

attribute equal to our other book's

472:01

title and is the author of the first

472:05

book

472:06

self.author equal to our other book's

472:10

author. If I were to run this we get

472:13

false. Book one does not equal book two.

472:16

But if they have the same title, I'm

472:19

going to replace these and the same

472:23

author, then they would be equal. And

472:26

we'll disregard the number of pages.

472:29

Let's say that with this version of The

472:30

Hobbit, they're using a smaller font

472:32

size, so there's less

472:35

pages. We're using dunder equals to

472:38

compare if two objects are equal.

472:41

What if I was to print book two is less

472:45

than book three? Like what does that

472:48

even mean? And I'm just going to get rid

472:50

of these two

472:53

lines. Type error less than is not

472:55

supported between instances of book and

472:59

book. So we can't use less than on two

473:01

objects. But we can customize that

473:04

behavior by using dunder less than which

473:07

is just lt. We're examining one book and

473:11

the other

473:12

book self and

473:15

other. Let's compare the number of

473:17

pages. We'll compare if the pages of

473:20

book two is less than book three. We

473:23

will return a boolean

473:25

value is self dot number of

473:30

pages less than other number of

473:34

pages. So now this should not give us an

473:38

error. Book two does not have less pages

473:41

than book three. Another would be

473:44

greater than. I'll just copy what we

473:47

have. Dunder GT for greater than for our

473:51

first book of self. Is it greater than

473:53

the number of pages of the other

474:00

book? Well, that's true. The number of

474:02

pages of book two is greater than book

474:05

three. Let's use dunder add to add the

474:08

pages of two books together. What would

474:10

happen if I were to add two books

474:12

together? Book two plus book

474:15

three. Well, we get a type error.

474:17

Unsupported operand for book and book.

474:21

Well, to customize the behavior of

474:23

addition, we will define dunder

474:27

add. We have self and other for the

474:30

other object.

474:32

Let's add the pages together of two

474:34

books. Maybe we need a summer reading

474:36

list and we would like to see what the

474:38

total number of pages is. I will return

474:42

self dot number of pages attribute plus

474:47

our other books number of

474:51

pages. That would give me

474:54

395. That's 223 + 172. Heck, I'll even

474:58

put this within an F string cuz why

475:06

not? Then I will add the word

475:09

pages 395

475:13

pages. Within an object, we can search

475:16

for a keyword within one of the

475:18

attributes. So let's find the word lion

475:21

within book three. To do that, I would

475:23

write a statement like this.

475:26

Lion in book

475:29

three type error argument of type book

475:33

is not

475:35

iterable. We will define dunder

475:40

contains besides self we will pass in a

475:44

keyword a keyword that we're searching

475:46

for.

475:48

I will return. Then we'll use the in

475:51

membership operator is our keyword in

475:56

self.title. I'm looking for the word

475:58

lion. That's going to return true. If

476:01

lion is in the title of this book or is

476:05

our

476:06

keyword in self.author, maybe we're

476:09

searching for an author. Let's try that

476:13

again. That returns true. Lion is in

476:17

book three. However, Lion is not within

476:20

book one. That's

476:23

false. Is Rolling in book two? That's

476:27

the author. That is true. Is rolling in

476:32

book three? That is false. That is

476:36

dunder contains. We are searching for a

476:38

keyword in an object.

476:42

Now, we could search for a key given an

476:44

object. For book one, we'll use the

476:47

index operator and look up an attribute.

476:51

Let's get the title of book

476:54

one. The default behavior is that we get

476:57

a type error. Book object is not

477:01

subscriptable. So to customize this

477:04

behavior, we will use dunder get

477:09

item. Besides self, we have one

477:12

parameter of key. We're accessing book

477:15

attributes by indexing. With this

477:18

object, return the value at this key.

477:21

What's that

477:22

attribute? We will check if our key that

477:26

we

477:27

receive is equal to title, which it is

477:31

in this case. We will return

477:34

self.title. What's the title of the

477:36

book?

477:39

So that would give me the Hobbit. Here's

477:41

book two and book

477:45

three. What if the key is

477:49

author? None. We didn't set that up

477:53

yet. If key is equal to

477:58

author, then return

478:02

self.author. The author of book three is

478:06

CS Lewis.

478:08

Two is JK

478:10

Rowling. Book one is JRR

478:14

Tolken. What about number of pages? Num

478:19

pages. Well, we're not set up for that

478:22

yet. I'm going to turn this into an

478:24

else- if statement.

478:27

Else if

478:28

key is equal to num

478:33

pages then we will return

478:38

self.num

478:39

pages. The number of pages in book one

478:43

is 310. Book two is

478:47

223. Book three is 172. What if there is

478:52

no key? Otherwise, if there is no

478:54

matching key, I'll add an else

478:57

statement. Let's return an

479:01

fstring key

479:03

placeholder. Our key that we pass in as

479:06

an argument was not

479:09

found. What do books not have? Well,

479:13

they don't have audio, I guess, unless

479:15

it's an audio book. Is there a key of

479:18

audio in book three? There is not. key

479:22

audio was not found. And I'll place that

479:25

within single

479:27

quotes. Much better. All right,

479:29

everybody. So, those are magic methods,

479:32

also known as dunder methods, meaning

479:34

double underscore. They are

479:36

automatically called by many of Python's

479:38

built-in operations. They allow

479:40

developers to define or customize the

479:43

behavior of objects when we use those

479:45

built-in operations. And well,

479:48

everybody, those are magic methods in

479:50

Python.

479:51

Hey everybody. So in today's video, I

479:53

got to talk about the property decorator

479:55

in Python. The property decorator allows

479:57

us to define a method as a property. We

480:00

can access it like it's an attribute.

480:02

One of the benefits is that when

480:04

reading, writing, or deleting

480:06

attributes, we can add additional logic.

480:08

The property decorator gives us a getter

480:11

method to read, a setter method to

480:13

write, and a deleter method to delete

480:15

when working with attributes. In this

480:17

example, we'll create a class of

480:20

rectangle. We need a constructor. Let's

480:23

define

480:24

that. When constructing a rectangle

480:26

object, we will need a width and a

480:30

height. We will assign the attribute of

480:33

width equal to the width that we receive

480:36

when constructing this object.

480:39

Self.height equals

480:42

height. Let's construct a rectangle

480:44

object. rectangle equals

480:49

rectangle. We need to pass in a width

480:51

and a height. Then I will print my

480:54

rectangle's width

480:57

rectangle.width and the

480:59

height.

481:02

Rectangle.height. With my rectangle, the

481:04

width is three, the height is four.

481:06

Using the property decorator, when

481:08

reading these attributes of width or

481:10

height, I can write some additional

481:12

logic. Let's say that when accessing the

481:15

width or the height, I would like to

481:17

display one digit after the decimal,

481:19

then add centimeters. Here's one way in

481:22

which I can do that. For each of these

481:24

attributes, I'm going to create a

481:26

method. We will define a method of

481:28

width, no parameters besides self. For

481:32

now, I'll write

481:33

pass and define

481:37

height. Preceding each of these methods,

481:39

I will use the property decorator.

481:43

So at

481:45

property now when accessing the width or

481:47

the height we'll be returned with

481:49

whatever is within these methods of

481:51

width and

481:52

height. But there's one change we're

481:54

going to make to these attributes. We'll

481:56

set these attributes to be private.

481:58

Prefix each of these attributes with an

482:01

underscore. This tells you and other

482:04

developers that these attributes,

482:06

they're meant to be protected. They're

482:08

internal. We shouldn't access the width

482:10

or the height directly outside of this

482:12

class. Technically, we could. I will

482:15

access the internal version of width and

482:18

height. We get three and four, but we do

482:21

have a warning. Access to a protected

482:23

member width of a class. That applies to

482:26

height as well. Our width and our height

482:28

are only meant to be used inside of this

482:30

class. If we need to get the width and

482:32

the height, we will do so through these

482:35

getter methods provided by the property

482:37

decorator. So when accessing the width,

482:40

let's return an

482:43

fstring I will access self dot private

482:48

width add a format specifier to display

482:52

one digit after the

482:54

decimal.1f followed by

482:57

centimeters. We'll do this with the

482:58

height as

482:59

well. We will return self.private

483:05

height. So now when we access the width

483:08

or the

483:10

height we will do so using these getter

483:12

methods. If I access these private width

483:15

and height attributes

483:18

instead again they will be three and

483:21

four. It's kind of like they're raw.

483:23

These attributes are meant to be used

483:25

internally inside of the class. So

483:27

that's the point of a getter method. We

483:29

can add additional logic when reading

483:32

one of these attributes when we try to

483:34

get them. We can also add setter methods

483:37

if we would like to set or write these

483:39

attributes. Here's how. Let's take our

483:42

width. We will create a decorator of at

483:45

width

483:47

setter. When attempting to set the

483:49

width, we will do so using this method.

483:52

We will define our method name of width.

483:54

We will have one parameter, a new width.

483:58

We don't want the parameter name to be

484:00

the same as the method name. That's why

484:02

we're naming it something different.

484:05

When setting the width, let's check to

484:07

see if the new width is greater than

484:11

zero. If so, we will take self.private

484:15

width equals our new

484:19

width. Else, let's print something.

484:22

Let's

484:24

print width must be greater than

484:30

zero. And let's do this with the

484:36

height. Heights setter define height.

484:41

Pass in a

484:43

new height. If our new height is greater

484:46

than zero, assign self.private height

484:51

equals the new height. Else print height

484:55

must be greater than

484:58

zero. Before printing the width and the

485:00

height, let's take our

485:02

rectangles width, set it to be zero.

485:05

Then see what

485:07

happens. Well, we get that message width

485:10

must be greater than zero. If I were to

485:13

set width to be

485:15

five. Well, that does work. Our width is

485:17

now five. Let's change the

485:20

height.

485:23

Rectangle. I will set this to be -1.

485:27

height must be greater than zero and the

485:30

height hasn't changed. What about

485:32

six? Six does work. When using these

485:36

setter methods, we can add additional

485:38

logic when writing or changing one of

485:41

these attributes. These are setter

485:43

methods. Now, if you need to delete an

485:46

attribute, here's

485:49

how. There is a delete keyword. We will

485:52

delete our rectangle's

485:54

width and delete our rectangle's height.

485:57

In this series, we really won't be using

485:59

the delete keyword, but you should still

486:00

know that it

486:02

exists. So, we will create a deleter

486:05

method at take one of the attributes. In

486:09

this example, width. We will create a

486:11

deleter method. The method name will be

486:15

width. The name of the

486:17

attribute. There will be no parameters

486:19

besides

486:21

self. We will

486:23

delete self.private private width. Then

486:28

let's print something just to confirm

486:29

that this was

486:31

deleted. Width has been deleted. Same

486:36

thing applies to

486:38

height. Take the attribute of height.

486:43

Define

486:44

height. Delete private

486:49

height. Height has been deleted.

486:55

When deleting our width or our height,

486:57

we get that confirmation message. Width

487:00

has been deleted and height has been

487:02

deleted. All right, everybody. So that

487:04

is the property decorator. We can define

487:07

a method as a property. Meaning it can

487:10

be accessed as if it was an attribute.

487:12

One of the benefits is that we can add

487:14

additional logic when we read, write, or

487:17

delete attributes. The property

487:19

decorator gives us a getter, setter, and

487:21

deleter method. Getter methods to read,

487:24

setter methods to write and deleter

487:27

methods to delete. And well everybody

487:30

that is the property decorator in

487:33

Python. What is going on everybody? So

487:35

today I got to talk about decorators in

487:37

Python. A decorator is a function that

487:40

extends the behavior of another function

487:43

without modifying that base function. We

487:45

pass the base function as an argument to

487:48

the decorator function. For example,

487:50

let's say we have a base function of get

487:52

ice cream and you can pass in a flavor

487:54

of ice cream. Well, some people might

487:56

want sprinkles on their ice cream and

487:58

others may not. They might just want

488:00

plain vanilla. Well, we could add

488:02

sprinkles by using a decorator. We're

488:04

extending the behavior of a function

488:06

where we get ice cream where we're

488:07

adding sprinkles, but we may not want to

488:09

change the base function because some

488:11

people don't like sprinkles. Think of

488:13

decorators that way. We're adding

488:15

something to a base function without

488:17

changing it. Here's how to create a

488:19

decorator. Let's start with the base

488:21

function. We will create a function to

488:24

get ice cream. There will be no

488:27

parameters for now. All we're going to

488:29

do is print the following

488:32

message. Here is your ice cream. And for

488:36

fun, I'll add an emoji because I like

488:39

emojis. I'll add an ice cream emoji. To

488:43

call this function, all I got to do is

488:45

call the get ice cream function. Here is

488:48

your ice cream. Here's how to create a

488:52

decorator. A decorator is a function.

488:55

We'll need to define it. Define add

488:59

sprinkles. Our decorator function is

489:02

going to have one parameter, a function,

489:06

but we'll just rename it to funk for

489:08

short. We're going to pass a function to

489:10

our decorator function.

489:14

Within our decorator function, we will

489:16

define an inner function of

489:19

wrapper. Currently, there's no

489:21

parameters. We'll set that up

489:24

later. Within this wrapper function, we

489:26

will call the function that we receive

489:29

this

489:31

parameter. Then we will return our

489:34

wrapper function. Up until this point,

489:37

we've been returning values, but now

489:39

we're going to return an entire

489:40

function. Here's the basic formula to

489:43

create a decorator. To apply a decorator

489:46

to a base function, preceding that

489:48

function, you're going to add at the

489:51

name of the decorator. So add sprinkles

489:54

is a decorator. The base function is get

489:57

ice cream. Within our decorator, how do

490:00

we want to add sprinkles exactly?

490:02

Currently, our decorator doesn't do

490:04

anything. Here's what happens. We just

490:07

print here is your ice cream. Let's say

490:10

that before we're given our ice cream,

490:12

we'll print a statement that we add

490:14

sprinkles within our decorator. Imagine

490:17

that we're replacing calling function

490:20

with this print

490:22

statement. Let's create another print

490:24

statement where we add sprinkles before

490:27

it. I will print the following

490:33

message. You add sprinkles and I'll add

490:37

an emoji.

490:38

How about confetti? That could resemble

490:42

sprinkles. Okay, let's see what

490:45

happens. You add sprinkles. Here is your

490:48

ice

490:49

cream. We're decorating our base

490:52

function of get ice cream with a

490:54

decorator of add

490:56

sprinkles. We're not modifying the base

490:58

function. We're extending it. Now, we

491:01

have a nested function of wrapper within

491:03

our decorator. It is necessary to have

491:06

this. Here's why. So, I'm not going to

491:08

call the get ice cream function quite

491:10

yet. So, nothing should

491:13

happen. If I was to remove this

491:21

wrapper, well, we'll end up calling this

491:23

function as soon as we apply the

491:25

decorator. We're not even calling the

491:27

get ice cream function at all. We only

491:30

want to execute this code when we want

491:32

ice cream, not whenever we apply the

491:34

decorator.

491:36

That's why we need that wrapper

491:40

function. We'll get ice cream and add

491:42

sprinkles only when we call that

491:46

function. Then at any point in my

491:48

program, if I call the get ice cream

491:52

function, then we get ice cream with

491:55

sprinkles. Let's apply more than one

491:58

decorator. We'll create a decorator to

492:01

add

492:01

fudge. Define add fudge.

492:06

We have one parameter a function which

492:08

we will rename as funk. We need an inner

492:11

wrapper

492:14

function. This is so that we don't call

492:16

this function when we apply a

492:18

decorator. I will

492:23

print you add

492:29

fudge. Close enough. We'll add a bar of

492:31

chocolate.

492:34

then call the base function that we

492:37

receive. Then we need to return the

492:39

wrapper

492:41

function. All right. Given our base

492:43

function, we can apply more than one

492:45

decorator. Let's say that after adding

492:48

sprinkles, we will apply the decorator

492:51

where we add fudge. So

492:54

now we have the following

492:57

output. You add sprinkles, you add

492:59

fudge. Here is your ice cream. So with

493:02

decorators, you can apply more than one

493:04

decorator to a base

493:06

function. What if your base function

493:08

accepts arguments? For example, when we

493:11

get our ice cream, we need to pass in a

493:13

flavor like

493:16

vanilla. I will set up one parameter, a

493:19

flavor. I will convert our print

493:21

statement to be an string. Here is your

493:25

add a

493:26

placeholder flavor of ice cream.

493:30

Let's run this and see what

493:33

happens. All right, we have a type

493:36

error. Our wrapper function isn't set up

493:39

to accept arguments. What you'll see

493:41

within wrapper functions is that they'll

493:42

have parameters of

493:44

args and quarks to accept any number of

493:48

arguments and keyword arguments.

493:51

Then when you call your base

493:53

function, in this case get ice cream, we

493:57

will also set this up to accept any

493:58

number of arguments and keyword

494:01

arguments. Let's do that within our add

494:03

fudge decorator too. Our wrapper

494:06

function will accept any number of

494:07

arguments and keyword arguments. Same

494:10

thing goes with the base function. And

494:12

now this should work.

494:14

You add sprinkles, you add fudge. Here

494:17

is your vanilla ice

494:19

cream or any other flavor of your

494:21

choosing like

494:24

chocolate. You add sprinkles, you add

494:27

fudge. Here is your chocolate ice cream.

494:30

All right, everybody. So, those are

494:32

decorators. They're a function that

494:34

extend the behavior of a base function.

494:37

In this case, get ice cream. Decorators

494:40

extend a function without modifying it.

494:42

If you would like to apply a decorator

494:44

to a function, you preede that function

494:46

when you define it with at the name of

494:49

the decorator and you can apply more

494:51

than one. And well everybody, that is an

494:54

introduction to decorators in

494:56

Python. Hey everybody. So today I got to

494:59

talk about exception handling in Python.

495:01

An exception is an event that interrupts

495:04

the normal flow of a program. There are

495:06

many different types of exceptions which

495:08

include but are not limited to zero

495:10

division error exceptions when you

495:12

attempt to divide a number by zero. For

495:14

example, 1 divided by 0. That would

495:17

interrupt our program. We have a zero

495:20

division error. Another is a type error.

495:22

That's if we attempt to perform an

495:24

operation of a value that's of the wrong

495:26

data type. For example, one plus a

495:29

string of one. That would give us a type

495:32

error. unsupported operand for int and

495:35

string. Value errors tend to happen when

495:38

you attempt to type cast a value of the

495:40

wrong data type. So let's say we attempt

495:42

to type cast the word pizza as an

495:47

integer. Well, pizza isn't a number. We

495:49

have a value error invalid literal for

495:52

int base with 10. Pizza. So exceptions

495:56

will interrupt our program if they're

495:58

not handled gracefully. And here's how

496:00

we can do that. There's three steps. We

496:03

can write a try, accept, and finally

496:06

block. Any code that's dangerous where

496:09

it could cause an error, you'll place

496:11

within a try block. For example, anytime

496:13

we accept user input, that is considered

496:16

dangerous code because a user can type

496:18

in anything. So, let's say we have a

496:20

number. Number equals we will accept

496:24

some user input. We will tell a user to

496:27

enter a number.

496:30

Then we're going to type cast it as an

496:34

integer. Then I'm going to

496:37

print 1 / whatever the user types

496:41

in. If I were to type in zero, we get a

496:44

zero division

496:46

error. If I type in the word pizza, we

496:49

get a value error. We would like to

496:51

prevent our program from stopping. This

496:54

code is considered dangerous. A user can

496:56

really type in anything. So, we're going

496:59

to surround this code within a try

497:01

block. We'll type try colon and then

497:05

indent any code underneath it. We're

497:08

going to try this code. If an exception

497:11

happens, we will move on to step two.

497:13

Subsequently, following the try block,

497:15

we will add an accept

497:18

block. If we run into one of these

497:21

exceptions, we can execute some

497:23

alternative code. For example, a zero

497:25

division error. If somebody attempts to

497:28

divide a number by zero, we can take a

497:30

different course of action. Instead of

497:32

our program crashing and coming to a

497:35

halt, let's

497:37

print

497:39

you can't divide by

497:43

zero. Idiot. Let's attempt to divide by

497:46

zero. Enter a number

497:49

zero. You can't divide by zero, idiot.

497:53

We have gracefully handled this

497:54

exception. So now let's say somebody

497:57

types in the word pizza when we're

497:59

asking for a number. Well, we have a

498:01

value error. Well, we can chain accept

498:04

blocks. If we encounter a value

498:07

error, let's add an accept block for

498:10

that. Accept value

498:13

error. We're going to

498:16

print enter only numbers.

498:22

Please enter a number. I'll type in the

498:24

word pizza. Enter only numbers, please.

498:28

That's good. We're not interrupting our

498:30

program. Now, what you may see some

498:32

people do is they will just catch all

498:35

exceptions.

498:37

Except

498:38

exception. Now, this is actually

498:40

considered bad practice. Exception will

498:43

catch all exceptions. However, it's too

498:46

broad of a

498:47

clause. It's good practice to tell the

498:49

user what went wrong exactly. If we

498:52

resort to just catching all exceptions,

498:55

you may see an error message such as

498:57

something went wrong. I'm looking at

499:01

you, Microsoft. We want to tell the user

499:04

what went wrong exactly. I would only

499:06

catch all exceptions as a last resort.

499:09

First, let's try and tell the user what

499:11

went wrong

499:12

exactly. So, I'm going to undo all this

499:16

code. If there's an exception that

499:19

occurs, it's not a zero division error

499:21

and it's not a value error, then we can

499:24

add that catch all where we catch any

499:26

unseen

499:27

exceptions. Now, lastly, we have the

499:29

finally block. The finally block always

499:32

executes regardless if there's an

499:34

exception or not. It's usually used for

499:37

any sort of cleanup that you need to do,

499:39

such as if you're handling files. You

499:42

may try and open a file and then you

499:44

want to be sure to close that file when

499:46

you're done with it. that would be

499:47

handled within the finally block. But

499:50

we'll get to file handling pretty soon

499:51

in the next topic. So just for the time

499:54

being, I'm going to

499:56

print do some cleanup

500:00

here. All right, let's test this. Enter

500:03

a number. I'm going to divide by zero.

500:07

You can't divide by zero. And we still

500:09

execute the finally

500:11

block. Enter a number. I'll enter in

500:14

one.

500:15

1 / 1 is 1 and we still execute that

500:19

finally block. The finally block will be

500:22

more useful in future videos. All you

500:24

need to know is that it always executes

500:26

regardless if there's an exception or

500:28

not. All right, everybody. So, that's

500:30

exception handling. An exception is an

500:32

event that interrupts the normal flow of

500:34

a program. There are many different

500:36

types of exceptions. You can always look

500:38

under the official Python documentation

500:40

for an extensive list. And well

500:42

everybody that's exception handling in

500:45

Python. Hey, what's going on everybody?

500:47

Today I'm going to show you how we can

500:49

handle basic file detection using

500:51

Python. This topic is the first of many

500:53

involving a minieries on file handling

500:55

using Python. First we'll need to cover

500:58

file detection. Before we read and write

501:00

files to work with files using Python,

501:03

we will import the OS module. OS means

501:06

operating system. This module provides a

501:09

way for Python programs to interact with

501:11

the operating system. Be sure to import

501:13

the OS module at the top. For my

501:16

demonstration, within my project folder,

501:19

I'm going to create a new file, new

501:21

file. I will name this file test. And

501:25

this will be a plain text file. It will

501:27

have the file extension of

501:30

.txt. This file really doesn't need to

501:32

say anything. I'm just going to type I

501:34

like pizza because I do.

501:37

The context doesn't matter. We're not

501:39

going to be reading files in this video.

501:42

For convenience, I'm going to assign a

501:44

variable of file

501:45

path. This will be a string. For file

501:49

detection, we can either use a relative

501:51

file path or an absolute file path.

501:54

We'll cover relative file paths first.

501:56

These two files are right next to each

501:58

other. My main Python file and my test

502:01

file. If we're using a relative file

502:04

path, I only need the file name,

502:06

including the extension

502:09

test.txt. We'll be passing in the string

502:12

of file path as an argument. To check to

502:15

see if this file exists, I will use an

502:17

if statement. If access the OS

502:20

module access the path, there is a

502:24

built-in method of

502:27

exists. We'll pass in our file path as

502:29

the argument. This method returns a

502:32

boolean value of true or false if this

502:35

file

502:36

exists. So if this file does exist,

502:40

test.txt, let's print the

502:43

following. I'll use an

502:46

fstring. The location I'll add a

502:50

placeholder exists.

502:54

I will place my file path within that

502:56

placeholder and I'll surround it with

502:59

single quotes to make it look nice. If

503:02

this method returns true, do

503:05

this else we'll do something else. I

503:09

will

503:10

print that

503:12

location doesn't

503:15

exist. All right, let's see what

503:19

happens. The location test.txt txt

503:23

exists. Now, what if I get the extension

503:25

wrong? Let's say that I'm looking for a

503:28

PDF, but it's really a txt

503:31

file. Well, that location doesn't exist.

503:35

You do have to be sure to get the file

503:36

extension

503:38

correct. What if this file was in a

503:41

folder within my Python project? I will

503:44

create a new

503:46

directory. I will name this directory

503:48

stuff.

503:50

Then I will place my test file within

503:52

the stuff

503:53

folder. PyCharm wants me to refactor my

503:56

code because the location changed. I'm

503:59

not going to do that. I'm going to be

504:01

sure that this box is unchecked and

504:03

press refactor. We're using a relative

504:06

file path. That test file is no longer

504:08

next to my main Python file. Here's what

504:11

happens. That location doesn't

504:14

exist. With our relative file path,

504:17

we'll have to navigate to our stuff

504:18

folder. then find the test file. So

504:22

preceding this file name, I will access

504:25

the stuff folder stuff/ the name of the

504:28

file

504:30

test.txt. And now we can locate that

504:32

file. The location

504:35

stuff/est exists. When working with

504:38

relative file paths, you may need to

504:40

open up a folder, then find your

504:43

file. You also could work with absolute

504:46

file paths. So for this demonstration on

504:49

my desktop I'm going to create a new

504:51

file

504:53

new text

504:55

document

504:58

test. If I were to look at the

505:00

properties this is a txt file a text

505:04

document. I'm going to copy the

505:09

location within my file path. I will

505:12

paste it. Then list the name of the file

505:14

test.txt.

505:17

This is an absolute file path. One

505:20

problem we're running into when working

505:22

with strings, a backslash does serve as

505:25

an escape sequence. Python thinks we're

505:28

trying to print a tab character. We can

505:30

solve this with double

505:33

backslashes or we could use a forward

505:37

slash. Either one works. All right,

505:40

let's see if that file

505:42

exists. That

505:44

does. the location of that absolute file

505:47

path does

505:48

exist. If I were to get the extension

505:50

wrong, let's say this is a

505:54

PDF, well, that location doesn't

505:58

exist. There is a built-in method of is

506:00

file to check to see if that file is in

506:02

fact a file and not a directory. Let's

506:05

add the

506:07

following. After we detect this file,

506:10

we'll write a nested if statement. If

506:14

Oos.path dot is

506:18

file then pass in our file path as an

506:21

argument. If this file is in fact a file

506:25

and not a directory, I will

506:28

print that is a

506:32

file. The location of that absolute file

506:35

path does exist. That is a file. What if

506:39

it was a directory, a folder?

506:42

I'm going to delete this. Go to

506:45

new folder. I will name this folder

506:50

test. To check to see if a location is a

506:53

directory, let's add an else- if

506:55

statement. Else if

506:59

ospath dot is dur meaning is

507:03

directory. This is a method. We'll pass

507:06

in our file path. If this is a

507:09

directory, a folder, I will print that

507:14

is a

507:16

directory. Let's run this again. That

507:19

location doesn't exist. Oh, we have to

507:21

get rid of the file

507:23

extension. It is not a plain text

507:28

file. The location of that absolute file

507:31

path exists. That is a directory, a

507:35

folder. All right, everybody. That's

507:38

basic file detection. In the next few

507:40

videos, we're going to be reading and

507:42

writing files. And well everybody, that

507:44

is basic file detection using Python.

507:47

Hey, what's going on everybody? In

507:49

today's video, I'm going to show you how

507:50

we can write and output files using

507:52

Python. We'll cover plain text, JSON,

507:55

and CSV files, but we'll start with

507:57

plain text because it's the easiest.

508:00

Suppose we have some data that we would

508:01

like to output. I'll create a variable

508:04

of text data.

508:06

Think of a food you like. I will output

508:09

I like

508:11

pizza. For convenience, we'll create a

508:14

variable, a file path. This can be a

508:17

relative file path or an absolute file

508:19

path. Within this file path, we'll need

508:21

a name for this file. I will name this

508:24

output. Then include the file extension.

508:27

This will be a .txt file, a plain text

508:30

file. This is a relative file path. When

508:33

I generate this file, it will be within

508:35

the same project folder as my main

508:37

Python

508:38

file. To create a file, we'll write the

508:42

following with open

508:45

function pass in our file

508:48

path and a character of W to write as

508:53

file. And for now, I'll write pass.

508:56

There's a few things going on here.

508:58

Width is a statement. It's used to wrap

509:01

a block of code to execute. If we open a

509:04

file, the width statement will also

509:06

close that file when we're done with it.

509:08

So, we don't need to manually close

509:10

files. When you open a file, it is good

509:13

practice to close it because if you

509:15

don't, you may run into unexpected

509:16

behavior. The width statement takes care

509:18

of that for you. The open function will

509:21

return a file object. The first

509:24

parameter is the file path. The second

509:26

parameter is the mode. W is write. X

509:30

will also write if this file doesn't

509:32

exist. If it already does exist, we'll

509:35

receive an error. A is for append to

509:37

append a file and R is to read, but

509:40

we'll take care of reading in the next

509:42

video. So, we will stick with W to write

509:44

a file. The open function returns a file

509:47

object. The first argument is the

509:51

file. The second argument is the mode.

509:54

You can set these to be keyword

509:56

arguments if it's easier for you to

509:59

read. When the open function returns a

510:01

file object for us, we're using the as

510:04

keyword to give it a name as file. It's

510:07

kind of like we're instantiating a file

510:09

object. File equals file. File is the

510:13

name of the file object. To write to

510:16

this file, we're going to take our file

510:18

object, use the built-in write method,

510:21

then pass in our text

510:23

data. Then when this is done, I'm going

510:26

to print a confirmation

510:28

message. I'll use an fring. Let's say

510:31

text

510:33

file. I'll add our file

510:36

path. Place it within single

510:40

quotes was created. Let's see what

510:44

happens.

510:46

text file output.txt was

510:49

created. And here's that file. I like

510:53

pizza. We also have the capability of

510:56

setting an absolute file path. Let's say

510:59

I would like to output this file to my

511:00

desktop. I would just need that

511:02

location. Let me just get the location

511:05

from one of these folders by going to

511:07

properties. I will copy this location.

511:10

This is the location to my desktop. But

511:14

for you, it's probably going to be

511:15

different. Then I will paste the

511:17

absolute file path. A backslash is an

511:20

escape sequence within a string. We

511:23

either could use double

511:26

backslashes or a forward

511:31

slash. Now, let's see if this outputs to

511:33

my

511:35

desktop. Text file. Here's the file path

511:39

was created. And here's that file.

511:43

It's a plain text file and it

511:46

says I like

511:50

pizza. So when working with the file

511:52

path, it can be a relative file path or

511:55

an absolute file path. All right. Now

511:58

for our text data. There are different

512:00

modes as well. W is for write. If we use

512:04

X, we'll write a file if that file

512:07

doesn't already exist. In this case, it

512:09

does. On my desktop, we already have a

512:12

file named output and it's a plain text

512:14

file. So when I run this with the mode

512:18

of X, we get a file exists error. That

512:21

file already exists. We could catch this

512:25

exception so that our program isn't

512:27

interrupted. I will copy the name of

512:29

this

512:31

error. I will place my code within a try

512:34

block. We will try this code and catch

512:37

any exceptions.

512:40

except file exists error. If this file

512:44

already exists, let's take a different

512:47

course of action. Let's print that file

512:51

already

512:54

exists. So now when I run this again,

512:57

our program isn't interrupted. We

512:59

receive this message. That file already

513:02

exists.

513:04

If I were to delete that

513:06

file,

513:08

bye-bye. Then run this

513:11

again. Well, we create a new file. Text

513:14

file that absolute file path was

513:17

created. And here it is

513:19

again. Now for the mode, there's also a

513:22

a to append. Any new data will be

513:25

appended to that

513:29

file. We get I like pizza. I like pizza.

513:33

When appending data, if you would like

513:35

that data on a new line, we can add a

513:37

new line

513:38

character. W will overwrite a

513:43

file. So, we're back to the

513:46

original. When appending, either before

513:49

or after we write our text data, we

513:51

could add a new line character. Let's

513:54

say let's do that

513:56

before. New line plus our text data.

514:00

Here's the

514:01

output. Again, we're appending, not

514:04

writing. I like pizza. I like pizza. Our

514:07

second sentence is on a new line. Let's

514:10

run this a couple

514:12

times. We should have several lines

514:18

now. Let's work with a collection. Let's

514:20

say we have a list of

514:23

employees. We'll pick some employees at

514:25

the Krusty Krab. So, we have Eugene. I

514:28

guess he's technically the manager. I

514:30

don't know if that counts as an

514:32

employee.

514:35

Squidward,

514:36

Spongebob, and Patrick. Patrick worked

514:39

at the Krusty Krab in one episode. He

514:42

counts. Then we'll have to be sure we're

514:44

writing our

514:46

employees. This is what's going to

514:49

happen. We have a type error. Write

514:52

argument must be a string, not a list.

514:55

In order for us to write each item

514:57

within a list, we'll need to iterate

514:59

over it using some sort of loop. We

515:01

can't write a list or any other

515:03

collection

515:05

directly. Here's what we'll change. For

515:08

every

515:10

employee in our collection of

515:15

employees, we're iterating over

515:17

something that is iterable.

515:20

We will access our file object. Use the

515:23

write method. Then write each

515:27

employee. Here's the

515:31

result. We get one long string of each

515:34

item in this

515:36

list. If you prefer, after writing each

515:39

employee, we could add a new line

515:41

character

515:46

after. And here's the output. We get

515:50

each item in our list on a new

515:53

line. Or rather than a new line

515:55

character, we could use a

515:57

space. This would output all the

516:00

employees but space them

516:02

out. Now we'll be outputting a JSON

516:05

file. In summary, a JSON file is made of

516:08

key value pairs. For our data, let's say

516:11

we have a dictionary of employee.

516:16

A dictionary is made of key value pairs.

516:18

We'll have a name of

516:22

Spongebob. Spongebob's age will be

516:28

30. His job, his position is that he is

516:32

a

516:34

cook. So this is the data I would like

516:36

to output. I'll keep the file path the

516:39

same. We'll change the file extension to

516:42

JSON.

516:44

We will need the help of the JSON

516:46

module. Let's be sure to import that.

516:48

import

516:50

JSON. Within our width block, we'll make

516:52

the following change. We're going to

516:55

access our JSON

516:56

module. Use the dump method. The dump

517:00

method will convert our dictionary to a

517:02

JSON string to output it. So we have to

517:06

pass in our JSON data of

517:09

employee our file as the second

517:13

argument. Then for a confirmation

517:15

message let's print JSON file was

517:18

created. Here's the result. JSON file at

517:22

this location was

517:25

created. And here's my JSON file. I'll

517:28

go to properties. We'll confirm it is a

517:30

JSON file. It is. And I'll open it.

517:34

Here's the result. Now, you could add

517:38

indentation after each key value pair.

517:40

Here's

517:41

how. After our second argument, our

517:45

file, we can pass in a keyword argument

517:48

of indent. For each key value pair, by

517:51

how many spaces do we want to indent

517:53

each? Let's say

517:56

four. And let's take a look. I think

518:00

that's more readable. We're indenting

518:02

each key value pair by four

518:05

spaces. So that is a JSON file. It's a

518:08

collection of key value

518:10

pairs. A dictionary or anything that

518:13

uses key value pairs is a great

518:15

candidate to be output to a JSON

518:18

file. All right. Now we're going to work

518:20

with CSV files. CSV means commaepparated

518:24

values. CSV files are pretty common with

518:27

a spreadsheet of data like an Excel

518:29

spreadsheet. We will create a 2D data

518:31

structure of

518:34

employees. This will be a list of

518:38

lists. Let's add

518:46

four. We'll need the help of the CSV

518:49

module. Import

518:52

CSV. Think of our 2D data structure as a

518:55

table of rows and columns. So for the

518:58

first row I will add

519:02

name, age, comm,

519:07

job. The second row will have a name of

519:10

Spongebob age 30, job cook. For the next

519:16

row, we'll have

519:19

Patrick. Patrick will be

519:22

37. What is Patrick's job? I don't know.

519:26

He's

519:29

unemployed. Then we'll have

519:31

Sandy. Sandy will be

519:35

27. Sandy is a

519:39

scientist. Okay. Now with our file path,

519:42

the file extension is going to be a CSV

519:45

file, commaepparated values. Within the

519:48

context of our width block, we're going

519:50

to create a writer object to write to a

519:54

file. writer equals access the CSV

519:58

module. Use the writer method of that

520:01

module. Then pass in our

520:04

file. Writer is an object. It provides

520:07

methods for writing data to a CSV

520:10

file. And then we'll print a

520:12

confirmation message of CSV file was

520:15

created. Here's the output.

520:19

Currently we have a CSV file. I'll go to

520:22

properties to confirm it.

520:26

Well, we have no output. We have to

520:29

iterate over all the rows in our 2D

520:32

collection. We'll write the following.

520:35

For every row in our data of

520:41

employees, we'll take our writer object,

520:44

use the write row method, and pass in

520:48

that row that we're iterating over. Now,

520:51

let's take a look.

520:56

That's better. However, the writer

520:58

method gives us a new line after each

521:02

row. So, if we would like to prevent

521:04

that, when we open this

521:07

file, I will set the keyword argument of

521:10

new line equal to no characters, an

521:15

empty

521:16

string. Let's take a look

521:19

again. Yeah, that's much better. So this

521:22

is a CSV file. It's made of

521:25

commaepparated

521:27

values. All right everybody. So that is

521:29

an introduction to writing files using

521:33

Python. What's going on everybody? Today

521:35

I'm going to show you how we can read

521:37

files using Python. We'll cover plain

521:39

text, JSON and CSV files. In the

521:42

previous topic we have created some

521:44

sample files to work with. Here is my

521:46

plain text

521:48

file. my JSON

521:51

file and my CSV file. They're all named

521:55

input. They each have a different file

521:58

extension. For convenience, I will

522:00

create a variable of file

522:02

path. We can list a relative file path

522:05

or an absolute file path. I'll use an

522:08

absolute file path. I'm going to right

522:10

click on the file I would like to read,

522:12

go to properties, copy the

522:16

location, then paste it, then add the

522:19

file name, including the extension

522:21

input, and this is a .txt

522:24

file. Within the context of a string,

522:27

backslashes are escape sequences for

522:30

special characters. We would either need

522:32

to use double backslashes or a forward

522:35

slash. Here is the absolute file path to

522:39

the file I would like to

522:41

read. To read this file, I will add a

522:44

width block. Width is a statement. It's

522:48

going to wrap a block of code within a

522:50

context manager and it'll close a file

522:53

if we open it. It is good practice to

522:55

close a file if you do open it. If you

522:57

don't, it can lead to unexpected

522:59

behavior. We will use the open function.

523:02

The open function has two arguments. our

523:05

file

523:06

path and a

523:08

mode. To read a file, we'll set the mode

523:11

to be R for

523:13

read. The open function is going to

523:15

return a file object which we will give

523:18

a nickname of

523:20

file as

523:23

file. When we read our file object, it's

523:26

going to return one long string which we

523:29

will assign to a variable named content.

523:32

content equals file. Use the read method

523:36

and assign it to this

523:38

variable. Then I'm going to print the

523:40

content. Print our content, the content

523:44

of the file. Here's the

523:47

result. That is the content of my file.

523:50

I like pizza. It's really

523:54

good. Let's say we can't find this file.

523:57

Perhaps I forget the file extension.

524:00

We'll run into a file not found error.

524:03

This will interrupt our program. We can

524:05

catch exceptions when they happen. Any

524:08

dangerous code that may cause an

524:10

exception, we can wrap within a try

524:13

block. If there's an exception, we will

524:16

catch them by stating except the name of

524:20

the exception. In this case, file not

524:22

found error. Instead of our program

524:25

being interrupted, let's take a

524:27

different course of action. We will

524:29

print that file was not found. Let's try

524:35

this

524:37

again. That file was not found. At least

524:41

our program isn't being

524:42

interrupted. Let's add the file

524:44

extension back. What if we don't have

524:47

permission to read this

524:49

file? To demonstrate that, I'm going to

524:51

rightclick on that file, go to

524:54

properties, go to

524:56

security, edit the

524:58

permissions. I will deny any sort of

525:02

control. I will attempt to read this

525:04

file. And we get a permission error.

525:07

Permission denied. We could handle this

525:09

exception as

525:11

well. If we encounter a permission

525:14

error, I will print the following.

525:18

You do not have

525:21

permission to read that file. Let's run

525:26

this again. You do not have permission

525:28

to read that

525:29

file. Those are a few exceptions we can

525:32

handle in case they appear. File not

525:34

found errors and permission errors.

525:37

Let's say we would like to read a JSON

525:39

file. We will need the help of the JSON

525:41

module. I will import the JSON module.

525:44

At the top of my

525:46

program, I need to get the file path of

525:48

this JSON

525:50

file. It's pretty much the same as

525:52

before. In this

525:56

case, the file extension is a JSON file.

526:01

There's only one change we're going to

526:02

make. We will assign our variable of

526:06

content equal to access the JSON module.

526:10

Use the load method and load our file.

526:14

And that should read the contents of my

526:16

file. Here's my JSON file. Name

526:20

Spongebob age 30 job

526:23

cook with the data of your JSON file.

526:26

You could access a value given a key. I

526:29

will access our content by its key of

526:33

name that will return the value of

526:35

Spongebob.

526:37

age

526:39

30

526:41

job

526:42

cook. Now, here's how to read a CSV

526:45

file. We will import the CSV module. The

526:49

file extension is going to be CSV.

526:52

Again, this is on my desktop in the same

526:54

location as the previous files. My

526:57

content will equal access the CSV

527:00

module. Access the reader method and

527:04

pass in our file.

527:06

Here's the content. Currently, we're

527:09

given a memory

527:11

address. With a CSV file, what we need

527:14

to do is read the CSV file line by line.

527:18

All of the data is within a collection,

527:20

which we need to iterate

527:23

over. So to do that, we're going to

527:26

create a for loop. For every line in my

527:30

content, I will print each line

527:36

That's much better. The format resembles

527:39

a spreadsheet, like an Excel

527:41

spreadsheet. There's

527:44

rows and

527:48

columns. To get a specified column, we

527:51

can access an index. In my example, our

527:55

line at index of zero would give me the

527:58

first column, name, Spongebob, Patrick,

528:02

Sandy. The next index would be all the

528:05

ages of each person 30, 35,

528:09

27. And index two would be the job

528:12

positions, cook, unemployed, and

528:16

scientist. If you need a specific column

528:19

of data from a CSV file, you can use an

528:22

index as one possibility. All right,

528:24

everybody. So, those are a few ways in

528:26

which we can read files using

528:28

Python. Hey, what's going on everybody?

528:31

So, in today's video, I'm going to show

528:32

you how we can work with dates and times

528:34

using Python. We will import the date

528:38

time module. This allows us to work with

528:40

dates and times using our system clock,

528:43

our computer's clock. This video serves

528:45

as more of an introduction. To create a

528:48

date object, we will assign an object of

528:50

date. Let me zoom in a little

528:52

bit. We will access the datetime module.

528:56

Call the date method. Within the date

528:59

method, we will pass in the following

529:01

arguments. A year of our choosing. So

529:04

for me, I'll say 2025, a month, one

529:07

corresponds to January. These are

529:10

numeric months. And a day, a day of the

529:12

month. I will say the

529:15

second. If I was to print the state

529:18

object, here's what it

529:20

outputs. The year is 2025, January

529:25

2nd. to get the date right now. Let's

529:28

say today. This will return a date

529:31

object that represents

529:33

today. Access the date time

529:36

module. Access the class of date. Then

529:40

call the today method to return the date

529:43

of today. Let's print today. Currently,

529:47

I'm recording this video July 14th,

529:50

2024. For me, that is the result of my

529:53

today object when I print it. Now we'll

529:56

work with time. I will create a time

529:58

object. Access the datetime

530:01

module. Call the time method. We have to

530:05

pass in hours, minutes, and then

530:07

seconds. So for the hour, let's say 12,

530:11

30, and 0 seconds. I will print the

530:14

current time. It is 12:30.

530:19

Now to get the time right now on our

530:22

system clock I will create a datetime

530:25

object of now equals access the datetime

530:29

module now within the datetime module

530:32

there is a datetime class we have to

530:34

access we will access that I know it

530:37

looks kind of silly datetimed datetime

530:41

dot the now method so we're accessing

530:44

the datetime module there is a built-in

530:47

datetime class we have access. Then

530:49

within that class, there's a now

530:52

method. What is the time right now

530:55

according to my system

530:57

clock? This returns a date and a time.

531:00

July 14th, 2024. It is just after 9:00

531:05

a.m. We can format the appearance of the

531:08

string. Here's

531:10

how. I'm going to reassign our datetime

531:13

object of

531:15

now. Our datetime object has a string

531:19

format time

531:20

method strf time. We're going to pass in

531:25

a string and include some format

531:27

specifiers. Let's say I would like to

531:29

display the hour first. I'm going to add

531:32

a percent. These format specifiers you

531:35

can find according to the datetime

531:37

documentation online. So I will display

531:40

the hours. That would be percent

531:44

H, percent M for

531:48

minutes, percent S for seconds. Let's

531:52

see what we're working

531:53

with. We have the hours, the minutes,

531:56

and the seconds. I will separate each of

531:59

these with a

532:02

colon. That's

532:04

better. Now I'll add the date. I'll

532:07

start with the month. I will add a

532:09

format specifier of lowercase

532:13

M then the day a format specifier of D

532:18

then the year format specifier capital Y

532:22

here's the

532:24

result we have the month the day and the

532:27

year I'll add a dash to separate

532:33

these better or if you prefer the day

532:36

first rather than the We can switch this

532:40

around. It depends on how you read dates

532:42

in your country. Now, we're going to

532:44

cover an exercise. We're going to see if

532:47

the current date and time has passed a

532:50

target date and time. So, we are going

532:52

to create a target date time

532:57

equals access the datetime

533:00

module. We will create a new date time.

533:04

So now we have to pass in a date and a

533:08

time. For my date time, let's say it's

533:10

something far into the future like the

533:12

year 2030, January

533:15

2nd. For the hour, it will be 12 30 and

533:20

1 second. I'm going to get the time

533:23

right now which I will name current

533:28

datetime equals access the datetime

533:32

module access the datetime class call

533:36

the now method to return the current

533:38

date and time right

533:41

now using an if statement I will see if

533:44

our target date

533:46

time is less than the current date

533:51

time. Have we already passed this date?

533:54

If our target date is less than the

533:57

current date, that means this date and

533:59

time has already passed. I will print

534:02

the following if that's the case. Target

534:06

date has passed.

534:11

else I will

534:15

print target

534:18

date has not

534:21

passed. Here's the

534:23

result. Target date has not passed. What

534:27

if I set the target date to the year

534:30

2020? Well, then the target date has

534:33

passed. So, that's how we can check to

534:35

see if a date and time has already

534:38

passed. Has it elapsed?

534:40

All right, everybody. So, that is an

534:42

introduction to working with dates and

534:44

times using

534:45

Python. All right, everybody. So, in

534:48

today's video, we're going to create a

534:49

working alarm clock using

534:52

[Music]

534:57

Python. For this project, we will need

534:59

the following imports. We will import

535:02

time. We'll be updating our clock every

535:05

second. The time module is going to help

535:07

us with that as well as import date

535:11

time. The datetime module allows us to

535:14

work with string representations of a

535:15

time. In my opinion, the easiest way to

535:18

work with sound effects is to actually

535:21

use pygame. So we will import

535:24

pygame. Now you may need to download the

535:27

pygame package. Here I'm getting a

535:29

message that there's no module named

535:31

pygame. There might be a link to install

535:33

it even too. One way in which you can

535:36

download the Pygame package is to open

535:38

up a terminal then use pip. Pip is

535:41

Python's package manager. pip install

535:47

Pygame. All right, we have our three

535:50

imports. Let's create a function to set

535:54

alarm. We have one parameter an alarm

535:59

time. And for now I'll write

536:02

pass. Our alarm time parameter is going

536:05

to be a string representation of a time

536:08

in military

536:09

time. I would like to start this program

536:12

if I'm running my main Python file

536:14

directly. I can add the following if

536:16

statement. If dunder name is equal to a

536:21

string of dunder main. If we are running

536:25

this main Python file directly then we

536:28

will set the alarm. But first we have to

536:30

prompt the user what they would like to

536:32

set the alarm to. So we will define a

536:34

variable of alarm time equals ask for

536:38

some user input using the input

536:41

function. We will prompt the user to

536:44

enter the alarm time and give a

536:48

format hours, minutes and

536:52

seconds. Again this is going to be in

536:55

military time. Once we have our alarm

536:58

time, we will call the set alarm

537:00

function and pass in our alarm

537:04

time. All right, we are now within the

537:07

set alarm function. When we call this

537:09

function, let's print the following.

537:11

I'll use an

537:13

fstring alarm set for then include the

537:17

alarm

537:19

time. You will need an MP3 file to work

537:22

with. If you don't have one available,

537:25

here's one

537:26

recommendation. You could use YouTube's

537:28

audio library and then search for sound

537:31

effects or some music. These audio files

537:34

are only allowed for non-commercial use

537:36

outside of

537:38

YouTube. So, you can search for a song

537:40

or some sound effects. Find one that you

537:42

like and download

537:44

it. Once you find a song that you like,

537:47

move it to your project folder.

537:51

Now I will create a variable of sound

537:54

file equals. This will be a relative or

537:58

absolute file path. My MP3 file is right

538:01

next to my main Python file. I only need

538:04

to list the file name. I named mine my

538:07

music and this is an MP3 file. I'm going

538:10

to perform a test run. We're not going

538:12

to play our sound quite yet.

538:15

We do have this output that displays

538:17

that says hello from the Pygame

538:19

community. Let's say I set my alarm to

538:21

9:00 a.m. Then enter alarm set for 9:00

538:26

a.m. If you would like to suppress this

538:28

output for Pygame, we can navigate to

538:30

our virtual environment. Go to library

538:34

Pygame underneath this file named dunder

538:40

init. Let's scroll all the way to the

538:42

bottom.

538:46

And we should have this if statement. We

538:48

display the version of Pygame we're

538:49

using and a print statement of hello

538:51

from the Pygame community. We could

538:54

comment this out or even just delete it.

538:57

That is the most simple

538:59

solution. So we shouldn't get that

539:01

message

539:04

anymore. We're going to create a boolean

539:06

variable of is running. Is our alarm

539:10

clock running? I will set that to be

539:12

true.

539:14

While is running while this is true, we

539:18

will continue the alarm

539:20

clock. We need to get the current time.

539:24

Current time equals we will access the

539:28

datetime

539:29

module. Access the class of date

539:33

time. Call the now method to get the

539:36

time and date. Right now we could method

539:39

chain the string format method strf

539:43

time I would like the hours minutes and

539:46

seconds but not the date. So we will

539:49

type percent h colon let me zoom out a

539:54

little percent m for minutes and percent

539:58

s for seconds.

540:01

We're getting the hours, minutes, and

540:03

seconds of the date and time right now

540:07

and storing it within this variable of

540:09

current

540:11

time. Then I'm going to print the

540:13

current

540:15

time. We'll perform a test run. However,

540:18

currently we're within an infinite loop.

540:20

At the end of the while loop, I'll set

540:22

is running to be

540:26

false. Okay. Enter the alarm time. Let's

540:28

say 10:00

540:30

a.m. Alarm set for 10:00 a.m. and the

540:34

time for me right now is 9:42 and 16

540:38

seconds. We'll get rid of this line

540:40

where we set is running to be false.

540:43

Instead, I'm going to access the time

540:45

module and call the sleep method. We

540:48

will pass in a number of seconds to

540:50

sleep. So, 1 second.

540:53

I'll set the alarm to be 10:00

540:55

a.m. Now, the time should update every

540:58

second, which it

541:01

is. However, when the current time is

541:04

equal to the alarm time, we have to

541:06

trigger the

541:09

alarm. So, after printing the current

541:12

time, we will write an if statement to

541:14

check if the current time is equal to

541:19

the alarm time.

541:22

If this is true, then let's print the

541:25

following. Wake

541:30

up. And I'll add an emoji cuz it's

541:34

silly. Once our alarm triggers, we will

541:37

set is running to be false within this

541:39

if

541:40

statement. Let's do a test run. We're

541:43

not going to play the sound quite

541:46

yet. I will set the alarm to 9:45.

541:51

and then I'll come back a little bit

541:56

later. All

541:58

right. Once the current time matches the

542:01

alarm time, we print wake up and set is

542:05

running to be false to exit the while

542:07

loop and then subsequently exiting the

542:10

program. Now we need to play an MP3

542:15

file. We will access our package of

542:18

Pygame.

542:19

access the module of

542:22

mixer. So mixer is a module for loading

542:25

and playing sounds, but we have to

542:28

initialize it, but we're going to

542:30

initialize it with init to

542:33

initialize. The initialize method is

542:35

another way to call the constructor. We

542:38

can pass in some keyword arguments for

542:40

the frequency, size, channels, buffer,

542:43

all that, but that might be a little too

542:45

complicated for us at this level. We'll

542:47

use the default settings by not passing

542:49

in anything. The next step is to load

542:52

our sound file. Access the package of

542:56

pygame. Access the module of

542:59

mixer. Access the module of music. Then

543:03

call the load method. We will load our

543:06

sound

543:10

file. Our sound file contains the file

543:12

path to our MP3 file. Once we load our

543:16

music, we have to play it.

543:21

Pygamemixer music call the play

543:25

method. Our MP3 file is only going to

543:28

play for a brief second. I'll

543:30

demonstrate that. I will set the alarm

543:32

to

543:35

949 and just give it a few

543:39

seconds.

543:43

Our sound file stops playing when the

543:46

program terminates. What we need to do

543:49

next is continue playing our sound file

543:52

while that sound file is busy. We will

543:55

add a while

543:56

loop.

543:58

file access

544:03

pygamemixer dot

544:05

music call the get busy

544:09

method. This returns a

544:11

boolean. If our song is busy, if it's

544:15

still playing, then we will call the

544:17

time modules sleep method and sleep for

544:20

1 second. Once the song finishes or we

544:24

terminate the program prematurely, the

544:27

sound file will no longer be busy. So,

544:30

this should be the finished product.

544:32

Let's test it. I will set the alarm for

544:39

952. And we just have to give it some

544:42

time.

544:49

[Music]

545:03

So, uh, yeah, I'm going to talk about

545:05

multi-threading in Python today.

545:07

Multi-threading is used to perform

545:09

multiple tasks concurrently. Think of it

545:12

like we're multitasking. We're

545:14

performing a few different actions at

545:16

once. For example, I could study and

545:18

listen to music and eat something at the

545:20

same time. Multi-threading is good for

545:23

IO bound tasks. IO meaning input output,

545:27

such as reading files or fetching data

545:29

from an API, things that may take some

545:31

time to do and we don't know when it's

545:33

going to end exactly. To use

545:35

multi-threading, we'll import the

545:37

threading module. Import

545:41

threading. We access the threading

545:44

module, then call the thread constructor

545:46

and pass in a target function. What

545:48

we'll do for this demonstration, let's

545:50

say we have a bunch of chores to do. We

545:52

have to walk the dog, get the mail, and

545:54

take out the trash. Let's define some

545:56

functions to handle that. We have a

545:59

function to walk the

546:02

dog. Then I will print the following

546:05

message. You finish walking the dog.

546:12

Let's create a function to take out

546:19

trash. Then we will

546:21

print you take out the

546:27

trash. Then another function of get mail

546:31

as in get the mail from the

546:34

mailbox. Then I will

546:36

print you get the mail.

546:42

Just to simulate these functions taking

546:45

an indeterminate amount of time, I'm

546:47

going to import the time module to help

546:50

us. Let's say walking the dog takes 8

546:55

seconds. I will access the time module,

546:59

call the sleep method, and pass in 8 for

547:01

8 seconds.

547:04

When we call the walk dog function,

547:06

we'll wait around for 8 seconds, then

547:08

finish walking the dog. This chore will

547:11

take quite a bit of time to

547:13

complete. Taking out the trash, it's

547:15

fairly

547:17

quick. Taking out the trash will take 2

547:20

seconds. Getting the mail will take 4

547:26

seconds. Let's call these functions and

547:28

see what happens. We will begin by

547:31

walking the dog.

547:34

I will call the walk dog

547:36

function followed by take out trash

547:42

function and the get mail

547:45

function. Here's the

547:48

result. We're going to wait around for 8

547:50

seconds until the walk dog function is

547:54

complete. Right about

547:57

now you finish walking the dog, you take

548:00

out the trash.

548:02

and you get the

548:05

mail. These functions are running on the

548:08

same thread, the main thread, our main

548:10

Python program. We have to complete

548:12

these chores in order one by one because

548:16

they're all running on the same thread.

548:18

Instead of walking the dog and then when

548:20

we're done taking out the trash and then

548:22

when that's done, we get the mail. We

548:25

could accomplish all three tasks at the

548:27

same

548:28

time. Let's say we have a thread object.

548:31

We could say thread one. Or to be more

548:33

descriptive, let's say we have chore

548:36

one. Let me zoom in a little

548:39

bit. Chore one is going to contain a

548:42

thread. We will access the threading

548:46

module. Call the constructor for a

548:48

thread. We have to pass in a keyword

548:51

argument of target. What is the first

548:54

chore that we have to do? Let's walk the

548:56

dog.

548:58

To start this thread, we will take our

549:00

thread object of chore

549:02

one and call the start method to start

549:05

it. Okay, let's do this with chore

549:10

2. Access the threading

549:13

module. Call the thread constructor.

549:16

Pass in a

549:17

target. Then the name of a function.

549:20

Take out

549:21

trash. Chore 2.

549:25

Start. And then we have chore three.

549:28

I'll just copy what we have because I'm

549:30

feeling

549:32

lazy. Chore three will be get

549:35

mail. Here's the result.

549:40

Now we finish taking out the trash

549:42

first, then we get the

549:45

mail. Then we finish walking the dog. So

549:49

we're executing these functions

549:51

concurrently. We're multitasking. We're

549:54

taking out the trash and getting the

549:56

mail and walking the dog all at the same

549:58

time. One thing that I did want to point

550:01

out, notice how we finish taking out the

550:03

trash first, followed by getting the

550:05

mail, then walking the dog. These tasks

550:09

finished in a different order compared

550:11

to when we weren't multi-threading.

550:13

That's because taking out the trash

550:14

finished first. It took 2 seconds.

550:17

Getting the mail took 4 seconds. And

550:19

walking the dog took the longest. It

550:21

took 8 seconds.

550:23

Previously, we finished walking the dog

550:25

first, then took out the trash, then got

550:28

the mail. When all the chores are

550:30

complete, I would like to print a

550:31

message. I will print the

550:34

following. All

550:36

chores are

550:39

complete. Here's what happens.

550:41

Currently, we get this message that all

550:44

chores are complete, but we haven't

550:46

finished any yet. We're still completing

550:48

them.

550:51

There may be at times you want your

550:52

program to wait for all threads to

550:56

finish. Before we print that

550:58

confirmation message that all chores are

551:00

complete, we're going to use the join

551:03

method. Take each thread, use the join

551:08

method. We'll do this with chore 2 and

551:11

chore 3 as

551:13

well. With the join method, we will wait

551:16

for these threads to finish before

551:18

continuing with the rest of the program.

551:19

Here's the result.

551:22

Now you take out the trash, you get the

551:29

mail, and you finish walking the dog,

551:32

all chores are complete. When

551:34

constructing a thread object and we have

551:36

a keyword argument of target if some of

551:39

these functions take parameters for

551:41

example with the function of walk dog

551:44

let's say we have a first name I will

551:47

convert this print statement to an

551:49

fstring we will display first for the

551:53

first name you finish walking whatever

551:56

your dog's name

551:58

is. So when we're creating a thread and

552:01

the target is that function and that

552:03

function accepts arguments, we need one

552:06

more keyword argument and that is args.

552:09

We will send this function a tpple. We

552:12

need a set of parenthesis within this

552:14

tpple. We will list our arguments. Let's

552:17

say that our dog's first name is Scooby.

552:21

Now, since this is a tpple, if we only

552:23

have one argument, we have to end that

552:25

tpple with a comma to let Python know

552:28

that this is a tpple. Here's the

552:33

result. You take out the trash. You get

552:36

the

552:39

mail. You finish walking Scooby. All

552:43

chores are complete. If we were missing

552:45

this

552:47

comma, this is what would happen. We're

552:50

no longer passing in a

552:51

tpple. What if we have multiple

552:54

parameters? We have first for first name

552:57

and last for last name. You finish

553:00

walking first and

553:03

last. We have first name of Scooby, last

553:06

name of

553:10

do. You take out the trash. You get the

553:14

mail.

553:17

You finish walking

553:19

Scooby-Doo. All chores are

553:22

complete. All right, everybody. So, that

553:24

is multi-threading. It's used to perform

553:26

multiple tasks concurrently. As if we're

553:29

multitasking, we're executing multiple

553:32

functions at the same time.

553:34

Multi-threading is good for IO bound

553:36

tasks such as reading files or fetching

553:39

data from APIs. And well everybody, that

553:41

is an introduction to multi-threading in

553:44

Python.

553:45

Hey everybody. In this video, I'm going

553:47

to show you how we can connect to an API

553:49

using Python. In this demonstration,

553:52

we're going to connect to the Poke API

553:54

to get some information on a Pokémon of

553:55

our choosing. I'm assuming that most of

553:57

us are familiar with Pokémon. I thought

553:59

it'd be a fun example. So, according to

554:01

this API, we can look up a Pokémon such

554:05

as Pikachu.

554:08

Then we can get the stats for Pikachu,

554:10

such as Pikachu's

554:13

name, height, ID number, and all sorts

554:17

of moves and abilities that a Pikachu

554:19

may have. We will need this URL, but

554:22

we'll handle that

554:25

later. Our first step is that we're

554:27

going to import the requests library to

554:29

make an API request. However, when I run

554:32

this, I have a module not found error.

554:36

No module named

554:37

requests. Requests is one package we'll

554:40

have to install. It's not normally

554:42

included with the standard Python

554:43

download. If I was to go to my project

554:46

folder, go to my virtual environment

554:49

library site packages. There is no

554:52

package for requests. We'll have to

554:54

download that. With PyCharm and VS Code,

554:57

there is a built-in terminal that we can

554:59

use to download the request package. We

555:02

can use pip. Pip is a package manager

555:05

for Python. It's normally included when

555:07

you install Python. We'll type pip

555:10

install

555:12

requests. It'll take just a

555:15

second. And now we have that package of

555:18

requests within our project

555:19

folder. If I run this

555:22

again, that error goes away. process

555:25

finished with exit code zero. That means

555:27

there were no

555:29

errors. Going back to our Pokemon API,

555:32

we will need this

555:33

URL. Let me zoom in so you can see

555:40

it. I'm going to store that as a base

555:43

URL so it's easier to work

555:46

with. For convenience, I'm going to

555:48

create a function name. Get

555:52

Pokemon

555:54

info. To get some info on a Pokemon,

555:57

we'll have to pass in the name of a

555:58

Pokemon. For now, I'll write pass.

556:02

Outside of this function, let's say we

556:04

have a variable of Pokemon

556:07

name. Pick a

556:09

Pokemon. I will pick Pikachu for now.

556:13

Then I will call the get Pokemon info

556:15

function. then pass in my Pokemon

556:18

name. Remember that your parameters can

556:21

be named different than your arguments.

556:23

When you send data to a function, you

556:25

can rename it to something else

556:27

temporarily. Now that we have the name

556:29

of the Pokémon we would like to look up,

556:31

we can complete the

556:32

URL. This will be an string.

556:37

So with our Pokemon API, we have the

556:39

base URL followed by the word Pokemon,

556:42

then the name of a

556:45

Pokemon. So we have the base URL. I'll

556:49

add a placeholder and insert it forward

556:52

slash the word

556:53

Pokémon slash the name of that

556:57

Pokémon. In this example, it's going to

556:59

be Pikachu. We now have the full URL.

557:04

We'll access the request module, use the

557:07

get method and pass in that

557:10

URL. This method is going to return a

557:12

response object which I will assign to

557:16

response. Response is a response

557:19

object. And I'm just going to print our

557:22

response just to see what we're working

557:26

with. Here's our response object. It has

557:29

a status code. This is an HTTP status

557:32

code of 200. 200 means the response was

557:36

okay. Here's a few examples of response

557:39

codes. You're probably familiar with

557:41

404. Not

557:45

found. So, we are looking for 200. The

557:49

response is

557:51

okay. After we get our

557:54

response, I'll add an if statement.

557:57

If our response our response object does

558:00

have an attribute of status code to read

558:03

what the status code is. If this status

558:06

code is equal to 200 that means the

558:09

response is

558:10

okay. But for now I'll write

558:13

pass. Else I'm going to print the

558:16

following. else I'm going to print

558:19

failed

558:21

to retrieve

558:24

data and I will print the status code of

558:27

the response

558:30

object. So temporarily I will print data

558:35

retrieved if it was

558:39

successful. I can't spell.

558:42

Okay, we have our data. Data was

558:45

retrieved. If our status code of our

558:48

response object is equal to

558:50

200, I will take our response object and

558:54

use the JSON

558:56

method. Our response is a JSON format.

558:59

Using this method, we'll convert it to a

559:01

Python dictionary. It will consist of

559:04

key value pairs much like a JSON file,

559:07

but I'm going to assign that to a

559:09

variable of Pokemon data so it's easier

559:14

to work with.

559:16

Then I will print our Pokemon

559:23

data. So here's the data on Pikachu.

559:26

It's really difficult to read all

559:29

this. You can see some keywords. We have

559:32

abilities, base experience. This is an

559:35

extremely large dictionary.

559:39

Once we have our dictionary, I will

559:41

return that dictionary of Pokemon data

559:45

back to the place where we call this

559:47

function and I will store that as a

559:50

variable. Pokemon info equals get

559:55

Pokemon info. Pass in a Pokemon's

559:58

name. And now we should have a

560:00

dictionary that we can work with. Let me

560:03

zoom out.

560:06

If our dictionary exists, we can use the

560:08

if

560:09

keyword. If Pokemon info, if that's

560:12

true. If it exists, this will be true. I

560:16

will print the following. I'll use an f

560:20

string. To access the value of a

560:22

dictionary, we can access it by a key.

560:25

We'll take our dictionary of Pokémon

560:27

info. Access the key of

560:31

name. Let's see what happens exactly.

560:35

we get Pikachu. Let's get Pikachu's ID

560:39

number. We will access the key of ID.

560:43

The given value is 25. Pikachu is the

560:46

25th Pokémon in the

560:51

franchise. Let's get Pikachu's

560:55

height. Pikachu's height is four. I

560:58

don't know what unit of measurement they

560:59

use in that franchise. 4 feet or 4 in. I

561:02

don't know.

561:04

Let's get Pikachu's

561:08

weight. Pikachu's weight is 60 60 lb 60

561:13

kg. I don't know. Just to make this look

561:16

nice, I'm going to add

561:18

name,

561:22

ID,

561:24

height, and

561:27

weight. That looks much better. Let's

561:30

pick a different Pokemon. I will pick my

561:33

favorite Pokemon of

561:39

Tyloian. Failed to retrieve

561:42

data. Does that have to be a lowercase

561:45

T? Yes, it does. Okay. So, name

561:49

Tyloian. I'll follow the name with the

561:52

capitaliz method to make it

561:58

capital. There we go. So, my favorite

562:01

Pokemon is

562:02

Typhloian. ID is 157. Typhloian's height

562:06

is 17 and weight is 795. All right,

562:10

everybody. That is one way in which we

562:12

can connect to an API using Python.

562:14

Also, tell me what your favorite Pokémon

562:16

is in the comment section down

562:18

below. All right, everybody. In today's

562:20

video, we're going to get started

562:22

working with the PIQT5 graphical user

562:24

interface, also known as a GUI GUI. In

562:28

this topic, we'll be creating a basic

562:30

window. So, let's get started. All

562:32

right. The first step is that using pip,

562:34

we're going to install the PIQT5

562:36

package. Open up a terminal. Both

562:39

PyCharm and VS Code have a built-in

562:40

terminal that you can

562:42

use. We're going to use pip, that is

562:44

Python's package manager. pip install

562:50

PIQT5. Enter. And this might just take a

562:53

second. Once your download has finished,

562:57

you should have a package within your

562:58

site packages folder named

563:01

piqt5. We can work with it as long as we

563:03

import

563:04

it. First, we are going to import the

563:08

module of CIS. CIS meaning system. This

563:11

module provides access to variables used

563:14

and maintained by the Python

563:15

interpreter. Then from the package of pi

563:20

QT5, do pay attention to the

563:22

capitalization. It's easy to mess that

563:24

up. Use dot to access the module of

563:29

QT widgets. Widgets are the building

563:32

blocks of a PIQT5 application. They

563:35

begin with Q. That helps distinguish

563:37

them from widgets from other libraries.

563:39

They typically begin with Q. From this

563:42

module, import the following widgets. Q

563:48

application and Q main window. Here's

563:54

some boilerplate code that we have to

563:56

write in order to get this application

563:57

up and running. First, we will create a

563:59

class of main window which will inherit

564:04

from the class of Q main

564:06

window by inheriting from the parent of

564:09

Q main window. We can customize our own

564:11

windows to display to the user. We will

564:14

need a constructor. Let's define

564:16

that. Define innit. There will be no

564:20

arguments currently besides self. And in

564:22

case we have to pass any arguments to

564:24

the parent of Q main window, we will

564:26

access the superass that's the parent

564:30

and call the parents

564:32

constructor. But currently we don't have

564:34

any arguments to pass

564:36

in. We will return to this class

564:39

momentarily. Let's define a function of

564:42

main. When we begin this program, we

564:44

will call the function of main to begin

564:47

the application. For now, I'll write

564:49

pass.

564:51

If we are running this file directly,

564:53

let's add the following if statement. If

564:56

dunder name is equal to a string of

565:00

dunder main. If we are running this file

565:03

directly, call the main function in

565:05

order for us to

565:07

begin. If that's true, we will call the

565:09

function of main. Within the main

565:12

function, we will create an app object.

565:15

app equals we will call the constructor

565:18

for Q application that class but there's

565:22

one argument that we have to pass in we

565:25

will access our module of

565:28

cis

565:29

argv meaning arguments so by passing in

565:33

this argument this allows piqt to

565:36

process any command line arguments

565:37

intended for it that's if we use command

565:40

prompt or terminal we won't be doing

565:42

that in this series but you may someday

565:44

in the future it would be a good idea

565:45

for us to futureproof our code.

565:48

Otherwise, you may see people pass in an

565:50

empty list. So, we now have an app

565:52

object. Next, we will create a window

565:55

object. Window equals call the

565:58

constructor for our class of main

566:00

window. Currently, we don't have any

566:02

arguments to pass in. We have an app

566:05

object and a window object by calling

566:07

their respective constructors. Now if I

566:10

run this program currently, our window

566:12

is not going to show. The default

566:14

behavior for a window is to hide it. In

566:18

order to show our window, we will access

566:21

our window. Call the show method to show

566:24

it. It's only going to appear for a

566:27

brief second when I run this

566:29

script. I don't know if you saw it, but

566:32

it pops up for a brief second.

566:35

We need to ensure that the window stays

566:37

until we interact with it or close it.

566:40

After we show our window, we will access

566:42

our module of

566:45

CIS call the exit method. The exit

566:48

method ensures a clean exit of our

566:50

program. Within our exit method, we will

566:53

pass in as an argument our app object.

566:57

Our app object has a built-in method of

567:02

exec. And this is a method so we can

567:04

call it. This is the execute method.

567:07

There is an underscore character after

567:10

exec for execute that distinguishes it

567:13

from the execute method. There is a

567:15

separate version of this execute

567:16

function that ends with an underscore.

567:18

Our apps execute method. It waits around

567:21

for user input and handles events such

567:24

as if we click buttons, press keys, or

567:26

close the window. Now that we're calling

567:29

this method, when we run our program,

567:31

this window should stay in place. We can

567:34

maximize it, minimize it, or close

567:39

it. That's all the boilerplate code that

567:42

we need for a basic window. Let's

567:44

customize it. Within our constructor for

567:47

our main window, what would we like to

567:49

add? Let's set the title for our

567:52

window. self dot set window title

567:58

method. We will pass in a string. Think

568:01

of a title for your

568:02

program. My cool first GUI

568:09

guey. And now we have a new title. My

568:12

cool first guey graphical user

568:15

interface. When this window appears, we

568:18

can set the geometry of where the window

568:20

appears and the size of the window.

568:23

access self dot set geometry

568:29

method. There's four

568:32

arguments. X and Y for the X and Y

568:34

coordinates, a width of the window, and

568:37

a height of the window. If I were to set

568:40

X and Y to be both zero, this window

568:43

will appear in the top left corner of my

568:45

screen. I'll also need a width and a

568:47

height. Let's say, I don't

568:51

know, 500 for

568:53

each. So now my window is now a square.

568:57

The width and the height are both the

568:59

same. They're both 500. The width is 500

569:01

pixels. The height is 500 pixels. With

569:04

the first two arguments, we set the

569:07

initial placement of our window to be

569:08

where x is 0 and y is zero. That

569:11

corresponds to the top left corner. If I

569:14

set the first argument to be

569:17

100, well then the window is going to

569:20

move to the right by 100 pixels. There

569:23

are ways to center your window in the

569:24

very center of your screen, but that's a

569:27

little too advanced for us right now.

569:28

For the time being, I'll pick something

569:30

roughly near the middle of my screen.

569:33

700 pixels on the xaxis and 300 on the

569:37

y-axis.

569:39

It should appear roughly in the middle,

569:40

but feel free to adjust these values

569:42

based on the size of your screen. We'll

569:45

discuss layouts in the future. Now, if

569:48

you would like a window icon, we can

569:50

change that. You will need an image to

569:52

work with. So, within my project

569:56

folder, I have a profile picture for my

569:59

YouTube channel. I'll set that to be the

570:01

icon. Find an image that you like, then

570:04

add it to your project folder.

570:06

In order to work with icons, we'll need

570:08

to make the following import. From

570:13

piqt5, that's the package. Access the

570:16

module of qt

570:19

gui. import the following Q icon. Now we

570:25

can work with

570:27

icons. After we set the geometry for our

570:31

window, access this object of self, this

570:34

main window, call the method of set

570:38

window

570:40

icon. Within this method, we will call

570:42

the constructor of Q icon. We'll pass in

570:47

either a relative file path or an

570:49

absolute file path. My main Python file

570:52

is right next to my profile picture,

570:54

that image. I only need the file name

570:57

within a string. So the name of my

571:00

image, it's going to be different for

571:02

you depending on what the name of your

571:03

image is. My image is named

571:08

profile_pic and this image is a JPEG

571:12

jpg. Then when I run this program, I'm

571:16

using my image as an icon for this

571:19

window. All right, everybody. That is

571:21

how to create a window using PIQT5. And

571:24

in the next topic, we will be creating

571:26

some

571:27

labels. What's up everybody? In today's

571:29

topic, we're going to create some labels

571:31

using

571:32

PIQT5. We will import the widget of Q

571:37

label. This label class is used to

571:40

create label widgets that can display

571:42

text or images. Within the constructor

571:45

of our main window, this is where we'll

571:47

create a label. We will declare a label

571:50

object. label equals call the

571:53

constructor for Q

571:56

label. For the text of the label, we'll

571:59

pass in a string. That's the first

572:01

argument. Let's say the word

572:04

hello. For the second argument, we will

572:06

pass in self. Self refers to this window

572:10

object that we're calling and

572:12

instantiating. All right, let's do a

572:14

test

572:16

run. Here is my label. Although you can

572:19

barely see it, the font is really small,

572:21

but it does say

572:23

hello. Let's set the font. We'll need

572:26

another

572:27

import from pi

572:31

qt5 dot

572:34

qt

572:36

gui import q

572:40

font. By importing the qfont class, we

572:44

can begin working with fonts.

572:46

We're going to take our label call the

572:48

set font

572:51

method. Within this method, we will call

572:54

the constructor of Q

572:56

font. Pick a font that you would like. I

572:59

will pick Ariel, but feel free to choose

573:02

really any font. Then the second

573:04

argument is a font size. I'll pick

573:08

30. Let's do another test

573:11

run. That's much better.

573:14

Let's increase this to 40 for the font

573:17

size. Now I'm going to set the geometry

573:20

of this label such as the positioning

573:23

and the width and the

573:26

height. Let's take our

573:28

label. Use the set geometry method. We

573:33

will pass in X and Y coordinates. 0

573:37

corresponds to the top left corner. For

573:40

the width, let's set the width to be 500

573:42

and the height to be

573:44

100. That's better. I'll cover more

573:48

advanced alignments

573:49

momentarily. Let's add a

573:52

stylesheet. PIQT does have styles that

573:55

are very similar to CSS. If you would

573:57

like to learn more about CSS, I do have

573:59

a full course on that topic. We will add

574:01

some CSS like properties by accessing

574:05

our label object. call the method of set

574:09

style

574:12

sheet. Within this method, we will pass

574:15

in some CSS like properties such as a

574:19

color. For the color, let's say blue.

574:22

These CSS like properties should end

574:24

with a

574:26

semicolon. And now the font color is

574:28

blue. You could also use RGB values or

574:32

hexodimal values.

574:34

You could always look up a color picker

574:36

and pick a very specific

574:39

color. Let's pick something

574:42

green. We can either use RGB values or

574:45

hexodimal values. So I will copy this

574:51

value. So I will paste that hexodimal

574:54

value. And now we have a very specific

574:57

shade of

574:58

green. But I think I'll go with

575:01

something dark.

575:03

such as

575:06

that. So this color is going to be a

575:09

dark gray

575:10

color. We could set a background color.

575:13

This will be a new

575:18

string. Background dash

575:21

color. And I will pick a new

575:24

color. I will pick something blue.

575:32

That's a decent

575:37

color. We have a blue background with

575:39

dark gray

575:41

text. We can set the font to be bold.

575:44

Font weight will be

575:49

bold. So the font is now

575:52

bold. The font style can be italic. font

575:57

style

576:00

italic. So our font is italic and we can

576:05

underline text

576:08

decoration

576:12

underline. The text on our label is now

576:15

underlined. Let's work on positioning

576:17

next. Currently my text is left

576:20

justified and set to the center

576:22

vertically.

576:24

To work with alignments, we need this

576:26

import from

576:30

piqt5 QT

576:34

core import

576:37

QT. The class of QT is used for

576:41

alignments. To center the text of our

576:44

label at the top vertically, we will

576:46

take our label use the set alignment

576:51

method. Then pass in a flag access the

576:54

class of Qot access the flag of align

577:00

top. This will align our text vertically

577:04

to the top.

577:08

So then our text is aligned vertically

577:11

to the top rather than the center. For

577:14

the

577:16

bottom, we will use the flag of align

577:23

bottom. We will align vertically on the

577:27

bottom. The text is now on the

577:30

bottom. to align vertically in the

577:33

center. Align V

577:38

center. This will be vertically

577:42

center which it was

577:44

originally. Now for horizontal alignment

577:47

we can add the

577:49

following. Okay. To align right we will

577:52

pass in a flag of align right.

577:59

horizontally align

578:03

right. The text is now all the way to

578:05

the

578:08

right for the

578:10

center. Align H. H for

578:14

horizontal.

578:18

Center. The text is now horizontally

578:20

aligned in the

578:24

center. for the

578:30

left. Align

578:36

left. The text will be aligned to the

578:39

left. We could combine both horizontal

578:42

and vertical

578:44

positioning. Here's how. Take our label,

578:48

call the set alignment method.

578:53

We will align horizontally in the

578:54

center. Follow this with the or bitwise

578:58

operator which is a vertical bar. This

579:00

allows us to combine flags. We will

579:03

align horizontally in the center. Then

579:05

vertically let's align to the

579:09

top. So our text should be aligned

579:12

horizontally. We're aligned in the

579:14

center. And vertically we're aligned to

579:16

the top.

579:18

align bottom

579:23

vertically. Horizontally, we are in the

579:25

center. Vertically, we're aligned on the

579:27

bottom. Then for the very center of our

579:37

label, align horizontal

579:40

center and align vertical

579:45

center.

579:49

Our text will now be in the very middle

579:52

of our label, both horizontally and

579:55

vertically. Now, there is a shortcut for

579:57

the very center. We don't need both of

579:59

these

580:01

flags. The shortcut is the

580:04

following. Set

580:07

alignment align

580:10

center. that will align the text both

580:12

horizontally and

580:14

vertically. So that is center and

580:17

center. All right everybody, so that is

580:19

an introduction to labels in

580:22

PIQT5. What is going on everybody? In

580:25

today's video, I'm going to show you how

580:26

we can add images to

580:28

PIQT5. You will need an image to work

580:30

with me. I'll be using my profile

580:32

picture for my YouTube channel. Feel

580:34

free to take a moment to find a picture

580:36

of your own, maybe a profile picture of

580:38

yourself. We will need the following

580:40

imports. Q label. The most common and

580:44

straightforward approach to displaying

580:46

an image is to add an image to a label

580:49

in order to display it. Then we will

580:51

need this other import from

580:54

piqt5. That's the package. Then the

580:57

module of qt gui import the class of

581:03

qpix map. The class of qpix map it's

581:08

used for handling images and provides

581:10

functionality for loading, manipulating

581:12

and displaying images. We will load our

581:14

image to a qixmap object. Then add this

581:18

qpix mapap object to a label in order to

581:20

display it within our constructor of our

581:23

main window. We will create a label.

581:27

Label equals call the Q label

581:30

constructor. Then pass in self. self

581:34

refers to the window object. Our window

581:36

will be the parent widget. Our label

581:38

widget is one of its children. Once we

581:41

have our label, we'll set the geometry

581:43

of the label. Label set geometry method.

581:48

We have to pass in x and y coordinates

581:51

as well as a width and height of the

581:53

label. For the coordinates, let's say

581:56

zero for each. The label will appear in

581:59

the top left corner. For the width, 250

582:02

is good. and the height 250 as

582:05

well. Here's my window. The label is

582:08

going to appear in the top left corner.

582:10

However, there's nothing added to the

582:12

label. That's where the widget of qpix

582:14

map comes in. We will create a pix map

582:18

object equals call the constructor of q

582:22

pix mapap. We have to pass in a string

582:25

that represents a relative file path or

582:28

an absolute file path to our image. My

582:31

image is right next to my main Python

582:33

file. I just need the file name. The

582:35

name of my image is

582:38

profile_pic and this is a

582:40

JPEG. When I run this, we don't see our

582:44

image. We have to add the pixmap object

582:47

to the label. We have to set it. Here's

582:50

how. Take our label, use the set pixmap

582:55

method, and pass in our pix map object.

582:59

And now we can see the image. However,

583:02

the image doesn't scale according to the

583:04

size of the label. To enable that, we

583:07

have to call the following

583:08

method. Take our label, call the set

583:13

scaled contents method, then pass in

583:17

true. Our image will now scale to the

583:20

size of the

583:21

label. If we were to change the size of

583:24

the label, let's say it's 100

583:28

pixels, it will scale down even further.

583:31

Or I could even increase it to

583:34

500. So now the image takes up the

583:37

entire width and height of the

583:39

window. Let's set that back to

583:44

250. There's a few tricks that we can do

583:46

with positioning of the image. We've set

583:49

our label with an image. We can move the

583:51

label within the confines of the window.

583:54

Currently, it's set in the top left

583:55

corner, but here's a few tricks that we

583:58

can do with positioning. With our label,

584:01

we will set the geometry

584:05

again. So, the top left corner is 0 0

584:08

for the

584:09

coordinates. We could pass in 250 and

584:12

250 again for the width and the height.

584:15

But if we were to change that here when

584:18

we initially create this label, we would

584:20

have to manually change that here as

584:22

well. I think it would be better if we

584:24

were to get the current width and height

584:26

of the label. Take our label, call the

584:29

width method to get the width. Same

584:31

thing applies with the height. Label

584:34

height

584:36

method. And that should work

584:38

fine. Let's say we would like to take

584:41

our image and move it to the right side

584:43

of our window. Here's how. With the

584:47

x-coordinate, we're going to access

584:49

self. That means our window called the

584:52

width

584:54

method. Here's what we have currently.

584:57

We can't see the

584:58

label. It was placed outside of the

585:00

confines of the

585:02

window. Let's subtract our label's

585:06

width.

585:08

Label.width. I'll put each of these

585:10

arguments on a new line just to help

585:12

with readability.

585:16

So now our image is right justified

585:18

within our

585:20

window. For the bottom right corner, we

585:23

will take the second

585:25

argument access

585:27

self.height. That's the height of the

585:29

window that we're

585:31

instantiating minus our labels

585:36

height. And now our image is in the

585:38

bottom right

585:39

corner. For the bottom left corner, we

585:42

will set X to be

585:46

zero. Now, here's the tricky part. To

585:49

have our image placed in the center of

585:51

our window, we will take the width of

585:54

the window minus the width of the label

585:57

divided by two. For integer division,

586:00

we'll be using double forward slashes.

586:03

We need our pixels to be whole integers,

586:05

so we're going to be using integer

586:07

division and not standard division.

586:09

We will round to the nearest whole

586:11

pixel. Then we will do this with the

586:14

height as

586:17

well. And now our image should be in the

586:20

middle of our

586:22

window. All right everybody. And that is

586:24

how to add an image to your PIQT5

586:27

application. Well, hello again friends.

586:30

Today I got to explain layouts in PIQT5.

586:33

We'll discuss vertical, horizontal, and

586:35

grid layouts. But we'll need the

586:37

following imports. We will be importing

586:39

Q

586:41

label Q

586:44

widget. I'm going to put these imports

586:46

on a new line just because we have a

586:49

lot. Q V for vertical box

586:55

layout. And I'm just going to copy

586:57

this. Q H for horizontal box

587:02

layout and Q grid layout.

587:07

Let's be sure that we have all these

587:09

imports. These classes deal with layout

587:12

managers. They aren't widgets. We'll be

587:14

writing a majority of the code within

587:16

our main window class. However, it can

587:18

get disorganized really quick. What will

587:21

help keep things organized is if we

587:22

declare a separate function within the

587:24

main window

587:26

class. This is a common practice that

587:28

you'll see within PIQT5. There will be a

587:30

function for init for initialize UI for

587:34

user interface. no other arguments

587:37

besides self. And for now, I'll write

587:40

pass. When we construct a window object,

587:43

we will call self dot init UI to

587:48

initialize the user

587:49

interface. So, anything that deals with

587:52

the user interface, we're going to be

587:54

writing within this function to help

587:55

keep our code clean and organized.

587:58

Normally, we can't add a layout manager

588:00

to a main window object. Main window

588:02

widgets have a specific design and

588:05

layout structure that's normally

588:07

incompatible with layout managers. What

588:09

we would need to do is create a generic

588:12

widget, add a layout manager to that

588:15

widget, then add that widget to the main

588:17

window in order to display the layout.

588:20

Within our method to initialize our user

588:22

interface, we are going to create what

588:24

is called a central

588:27

widget called the constructor for Q

588:30

widget.

588:32

This is a generic widget. Then we will

588:35

take self. Self is our

588:38

window. Call the

588:40

set central widget method. Then pass in

588:45

our central

588:47

widget. When working with layout

588:49

managers, we will add that layout

588:51

manager to the central widget. The

588:53

central widget is then added to the main

588:56

window.

588:58

So currently this is what we're working

589:00

with. We will need some widgets to

589:02

organize because right now it's

589:05

empty. Let's create a few

589:07

labels. Let's say label 1 equals Q

589:12

label. I'll pass in some text. Number

589:15

one. Okay. Let's create four additional

589:18

labels 1 through 5. I'll just do some

589:22

copying and pasting.

589:28

All of our labels are

589:31

overlapping. Let's add some colors.

589:33

Let's take label one, use the set

589:37

stylesheet

589:39

method, then pass in a background color

589:42

as a CSS

589:44

property. Background dash color will be

589:49

red. Let's copy this line of code. paste

589:53

it four additional times. For labels 1

589:56

through

589:59

5, we'll have a label that is yellow,

590:02

another that is green,

590:07

blue, then

590:11

purple. Here are the labels. They're all

590:14

overlapping one another. That's why we

590:16

can only see

590:17

five. This is where a layout manager

590:20

comes in.

590:21

We'll start with the vertical layout. We

590:24

will create a vertical layout manager

590:26

which we will name

590:28

vbox vbox equals call the constructor

590:32

for

590:34

QV box layout. We are calling the

590:38

constructor.

590:40

We will take our layout

590:42

manager, call the add widget method,

590:46

then pass in a widget such as label one

590:50

near the top

590:51

here. We'll do this with the other

590:53

labels. We'll do some copying and

590:56

pasting. Add label 2, 3, 4, and

591:01

five. There's one last step.

591:06

We will take our central widget which we

591:09

have declared at the top of this

591:12

function. Call the set layout

591:15

method. We are setting the layout of our

591:18

central

591:19

widget with the layout manager of Vbox

591:22

vertical box. Here's the new layout. All

591:26

of our labels, all of our widgets are

591:28

arranged vertically. For horizontal, we

591:32

will use QH box layout. For

591:35

horizontal, replace any instance of Vbox

591:38

with

591:42

Hbox. For the set layout method, pass in

591:46

Hbox. This allows for a horizontal

591:50

layout. Then we have

591:52

grid. Q grid layout. Replace Hbox with

592:02

grid. So what we have to do with grids

592:05

after adding a widget we have to specify

592:08

a row and column with separate

592:10

arguments. The row and column both begin

592:12

with zero. So row one column 1 would be

592:16

row 0 column 0. For label two let's say

592:21

row 0 column 1. Label three will be row

592:26

1 column 0.

592:29

Four will be row one, column 1. Then

592:33

five, row one, column 2. So here's the

592:37

current

592:38

layout. We have labels 1 and two, both

592:41

within row zero. Labels 3, 4, and 5 are

592:44

both within the second row. Let's say

592:47

label 5 is row 2, column 2. That would

592:51

result with something like this. We have

592:54

label five, which is purple, in row two,

592:57

column 2. So it depends on how you want

593:00

to arrange your widgets. All right

593:01

everybody. So that is an introduction to

593:04

layout managers in

593:06

PIQT5. Today I'm going to show you how

593:08

we can create push button widgets in

593:11

PIQT5. To begin we will need the

593:13

following imports. Q push button as well

593:18

as Q label for this demonstration.

593:21

During the previous topic on layout

593:23

managers, within our constructor for our

593:25

main window, we defined a method of

593:28

initialize UI for user interface. Let's

593:31

be sure that we're calling that method

593:33

within our constructor. Within this

593:34

method is where we'll be handling

593:36

managing the user interface. To create a

593:38

button, we will call the push button

593:40

constructor. Normally, when creating

593:42

widgets, we would want to prefix that

593:44

widget with self, then follow the name

593:47

of the widget, for example, button.

593:49

However, I'm going to demonstrate what

593:51

happens when we don't do that because

593:53

without self, we're declaring a local

593:56

variable. We'll get back to that in just

593:58

a moment. Let's create a local button

594:00

object by calling the Q push button

594:04

constructor. We can pass in some text

594:06

such as click

594:09

me. We will add this to our window self.

594:12

Self refers to our window

594:14

object. Let's set the geometry of the

594:16

button. button set

594:21

geometry. We could use a layout manager,

594:23

but I do want to keep this lesson as

594:25

simple as possible. So, let's pick some

594:27

coordinates. I've picked the following.

594:30

For the X and Y coordinates, 150 and

594:32

200. For the width, 200, and the height,

594:36

100. Here's our button. Currently, the

594:39

font is a little small, so I'm going to

594:41

set the

594:43

stylesheet. Set style sheet.

594:48

I'll just increase the font size. We

594:50

could use Q font, but that might be

594:52

overkill for this

594:54

demonstration. Let's just say the font

594:56

size will be 30

594:58

pixels. Now we can read it. So we have

595:02

our button. We're going to be connecting

595:04

our button to a function, but we need to

595:07

define that function. We'll do so within

595:09

our main window class.

595:12

So we will define a function of on

595:15

click. There are no parameters besides

595:18

self. When we click on the button, what

595:21

would we like to do? Let's print a test

595:24

message. Let's say button clicked. And

595:28

that's

595:31

it. When we click this button, nothing

595:34

happens. We have to set up a signal and

595:37

slot for the button. Here's how.

595:41

We will take our button dot list a

595:44

signal. A signal is emitted when a

595:47

widget is interacted with. We have to

595:50

list the type of signal. So the signal

595:52

we're looking for is

595:54

clicked. When we click this button, we

595:57

will perform a slot an action. We will

596:01

take the signal of clicked connect it to

596:04

a slot. Connect is a method.

596:07

The slot will be self dot the name of

596:10

the method on

596:13

click. When we press this button, we

596:16

perform this slot this method of on

596:20

click. Each time I press the button, we

596:23

perform that

596:25

action. Not only should we print a

596:27

message for this demonstration, let's

596:29

set the text of the

596:31

button. So, we have

596:33

button set

596:36

text. Let's change the text

596:39

to

596:41

clicked. So, this actually isn't going

596:44

to work because we're not prefixing

596:46

self. Let me demonstrate what

596:50

happens. We print button clicked. But

596:53

then we have a problem. We have an exit

596:55

code. Our program was

596:57

interrupted. Button is considered local

597:00

to our initializer method. Our on click

597:03

function doesn't recognize what our

597:04

button is. That's why we're going to

597:06

prefix our button with self. So it

597:09

belongs to the class of main window and

597:11

not this method. Any instance of button

597:14

we're going to prefix with

597:18

self. And now this should work. The text

597:22

on my button is going to change when I

597:23

click it. Clicked.

597:28

You don't have to do this, but with my

597:31

personal coding style, whenever I create

597:33

a variable or an object within a class,

597:36

I like to do so within the constructor.

597:38

Even PyCharm is giving me a

597:41

warning. When we declare this button,

597:44

I'm going to move it to the

597:47

constructor. And let me just rearrange

597:52

everything. self dotbutton equals a Q

597:55

push button widget within my initializer

597:58

method. That's when I like to rearrange

598:00

everything and style it. We can also

598:03

disable buttons when we click on them.

598:06

To do that, we will take

598:09

self.button, call the set disabled

598:12

method, then pass in true. When I click

598:16

the button, it will be disabled. I can

598:19

no longer click on it.

598:22

For the last part of this demonstration,

598:24

when we click on our button, let's

598:26

change the text of a

598:29

label. Let's declare self label within

598:32

our constructor equals a Q

598:36

label. The text of the label will be

598:39

hello. We will add this label to self

598:43

the window. When we set up the user

598:45

interface, let's set the geometry of the

598:48

label self.l

598:50

lab set

598:53

geometry. We could use a layout manager,

598:56

but just to keep things simple, I'm

598:57

going to set some coordinates. 150 for

599:00

X, 300 for Y. The width will be 200, and

599:04

the height

599:06

100. Let's change the font

599:09

size.

599:12

self.label set style

599:15

sheet. I will set the font size to be

599:18

30.

599:22

Maybe

599:24

50 better. All right. Within our on

599:28

click function, let's instead take

599:33

self.label set text method. Then pass in

599:37

some new text to display. We're saying

599:40

hello. But when we click the button,

599:43

let's say goodbye.

599:46

So now when I click the button we will

599:49

change the text on a separate widget my

599:51

label which now says

599:54

goodbye. So with buttons you need a

599:57

signal that's connected to a slot. The

600:00

signal is an event. The slot is an

600:02

action that this widget is going to take

600:04

when this signal occurs. And well

600:07

everybody that is an introduction to

600:09

push buttons in

600:11

piqt5. Hey y so today I got to explain a

600:14

checkboxes in piqt5. To work with

600:18

checkboxes we will need the following

600:19

import from the module of widgets from

600:23

piqt5. import q

600:27

checkbox to work with different states.

600:30

We will also need the following import

600:33

from

600:36

piqt5qt

600:38

core importqt.

600:41

this module of QT core it contains

600:44

non-geuey classes relevant to piqt5

600:47

applications so be sure that you get

600:50

this import as well to create a checkbox

600:52

I will create this within the

600:54

constructor of my main window we will

600:57

create a checkbox with self the name of

600:59

the checkbox which I will name

601:02

checkbox

601:03

equals call the constructor of the Q

601:06

checkbox class the first argument is

601:09

going to be the text of the checkbox.

601:12

What do you want the checkbox to say?

601:14

Let's ask, do you like

601:19

food? The second argument is the parent

601:22

widget where we will be adding this

601:24

checkbox. Let's say self. Self will

601:27

apply to this window. We could use a

601:29

layout manager, but I want to keep this

601:31

lesson as simple as possible. We're just

601:33

going to focus on checkboxes and their

601:36

functionality. So, we should have a

601:38

checkbox. However, we can barely see it.

601:41

The font is really small. I have a

601:44

method to initialize the user

601:46

interface. That's where we'll set the

601:48

stylesheet and the geometry of our

601:51

checkbox. Let's set the stylesheet. self

601:54

dot the name of the checkbox.

601:57

Checkbox dot set style sheet method.

602:03

Then we can pass in some CSS like

602:05

properties. Let's set the font size to

602:09

be 30

602:11

pixels. And I will pick a font

602:15

family. Font family

602:20

Ariel. Oh, and we should change the

602:23

geometry of the label. It's getting cut

602:26

off. self dot the name of the checkbox,

602:31

which is checkbox.

602:33

Let's set the

602:35

geometry. Pass in some X and Y

602:38

coordinates for the placement as well as

602:40

a width and a height. I will pick 500

602:44

and

602:45

100. Maybe I'll move it a little more to

602:48

the right by 10

602:50

pixels. That's pretty good. Our checkbox

602:54

has an initial state. It's normally

602:56

unchecked. That's the default behavior,

602:59

but we could set that to be checked with

603:01

the following method when the window

603:03

loads. Let's take our checkbox

603:07

self.checkbox, call the set checked

603:10

method, then pass in true. So then when

603:14

the window loads, the checkbox is

603:17

already

603:18

checked. But let's keep that as

603:21

false. Now this checkbox, it doesn't do

603:24

anything when I check it. Let's add some

603:28

functionality. We'll take our checkbox,

603:31

connect a signal to a

603:33

slot. The slot can be a function or a

603:36

method. Let's define a method within our

603:39

main window class. Let's name this

603:42

method

603:43

checkbox changed. We will call this

603:47

method when the state of our checkbox

603:49

changes. There is one parameter beside

603:52

self a state. Now the state parameter is

603:56

going to be provided to us when we

603:58

interact with our checkbox. When we

604:00

check the checkbox, let's print

604:02

something like a test

604:04

message. You like

604:07

food. We have to connect a signal of

604:10

state changed to a slot of checkbox

604:13

changed. We will take self dot the name

604:17

of the checkbox which is

604:19

checkbox. The signal will be state

604:23

changed.

604:24

To connect a slot to a signal, we use

604:27

the connect method. Then pass in a

604:30

function or method name. So we are

604:33

working with

604:34

methods. This method belongs to the

604:36

window class. We'll prefix the method

604:39

name with self. self.checkbox

604:44

changed. So when I run this program,

604:46

when I check the checkbox, we execute

604:49

this method. You like food. Now when I

604:52

uncheck it, I instead would like to

604:54

display you do not like

604:57

food. So that's where our state is going

605:00

to come in. I'm going to print our state

605:03

just to see what it

605:05

is. Our state is going to be a

605:10

value. When we check the check box, our

605:13

state has a value of two. When we

605:16

uncheck it, it has a value of zero. Zero

605:19

means unchecked. two means checked.

605:22

There's also one for partially checked,

605:24

but that's not going to be relevant to

605:26

this topic. So, zero or two. We could

605:30

add an if statement such as if state is

605:33

equal to two, then print you like food.

605:37

However, that's not really readable.

605:39

Other developers looking over your code

605:41

aren't going to understand what two is

605:43

by looking at it. Instead, let's use the

605:45

following. We will access the class of

605:48

QT.

605:50

There's a built-in constant of

605:54

checked. This also equals to, but it's

605:57

more readable. It's a constant. So, if

606:00

state is equal to QT checked, print you

606:04

like

606:05

food. I will check the checkbox. You

606:08

like food. When I uncheck it, nothing

606:11

happens. Let's add an else statement.

606:15

else. Let's

606:17

print you do not like

606:21

food. So then when I check the check

606:24

box, we print you like food. When I

606:27

uncheck it, we print you do not like

606:30

food. You like food. You do not like

606:33

food. You like food. You do not like

606:36

food. All right, everybody. So that is

606:38

an introduction to checkboxes in

606:41

PIQT5. All right, let's do this thing.

606:44

Today I got to talk about radio buttons

606:46

in PIQT5. To work with radio buttons, we

606:49

will need the following imports. From

606:51

the module of QT widgets, we will need

606:54

the class of Q radio button as well as Q

607:00

button group. To group together

607:02

different

607:03

buttons, let's create three radio

607:06

buttons within the constructor of my

607:08

main window. We will construct three

607:10

radio buttons. For the first radio

607:13

button, this will be named radio one. We

607:16

will call the constructor of the class Q

607:19

radio button. Then we can pass in some

607:21

text. What is the radio button going to

607:24

say? Let's say that we're working with

607:26

payment options. Let's say visa for the

607:29

first option. Then for the second

607:31

argument, I will pass in self. We will

607:34

add this radio button directly to our

607:36

window. That would be self. Let's create

607:40

two more additional radio buttons. Radio

607:42

2 and radio 3. The text of radio button

607:46

two will be

607:47

masterard and three will be a gift card.

607:51

We are selecting different payment

607:54

options. We need to set the geometry of

607:57

these radio buttons because we're not

607:58

using a layout manager. I have a method

608:01

to initialize my user interface. This is

608:04

where I will set the geometry of my

608:06

radio buttons. So let's say

608:09

self.radio 1. We will call the set

608:12

geometry method. Pass in some

608:15

coordinates. 0 0 is good. That applies

608:18

to the top left corner of my window. For

608:20

the width 300, and the height 50 is

608:24

good. Let's do this with radio buttons

608:26

two and three. Radio 2, radio 3. We'll

608:31

just move each radio button down on the

608:32

y-axis by 50 pixels each. So 50, then

608:36

100.

608:38

Here are the three radio buttons.

608:41

However, the font is kind of small. We

608:42

can barely see it. So, let's apply a

608:46

stylesheet. Here's a trick that we can

608:48

do with stylesheets. We can apply

608:50

multiple CSS like properties to an

608:53

entire group of widgets. Rather than

608:55

having to type them and apply them

608:57

individually, we will select our window

609:00

of self. set the stylesheet of our

609:03

window with the set stylesheet

609:07

method. We will add a selector. The

609:09

selector is going to be the name of the

609:11

widget. Q radio button in this case.

609:14

Then add a set of curly

609:19

braces. We can apply CSS like properties

609:22

to an entire group of widgets this way.

609:25

So let's set the font size of all radio

609:28

buttons to be 40 pixels.

609:34

better. Let's set the font

609:37

family to be

609:39

aerial. Then I will add a little bit of

609:42

padding around each radio

609:44

button. Padding 10

609:49

pixels. That's pretty good. So with

609:52

radio buttons, we can only select one

609:54

from any one radio button group. If I

609:57

was making a payment, I can't pay with a

610:00

Visa and a Mastercard at the same time.

610:02

I can only select one option. That's the

610:05

point of radio buttons. We're limited to

610:07

just one option. With the default

610:10

behavior of

610:11

PIQT5, all radio buttons, unless

610:14

explicitly stated, are all part of the

610:16

same group. To demonstrate that, let's

610:19

create two additional radio buttons.

610:22

Radio 4 and radio 5. Radio button four

610:25

will be for a payment method rather than

610:27

a payment type. For example, we could

610:30

say we're paying in

610:33

store. Radio button five will be we're

610:35

paying online. Radio buttons 1 through 3

610:39

will be for the payment type. Radio

610:41

buttons four and five will be for the

610:43

payment method. We're either paying in

610:45

store or we're ordering something

610:47

online. We do need to set the geometry

610:50

for these two radio buttons. I'll just

610:53

copy these two

610:54

lines. Add radio 4. Radio 5. We'll set

610:58

the y-coordinate of four to be 150 and

611:02

five to be 200. All radio buttons will

611:05

be within the same button group. If I

611:07

was to select in store, we deselect one

611:10

of these options. What I would like is

611:12

one option from this first group and

611:15

another option from this other group.

611:17

These buttons are all in the same group.

611:19

I can only select one. If I would like

611:22

to pay with the visa in store and I

611:25

click the in store radio button, we

611:28

unselect the radio button for visa. I

611:31

would like these radio buttons within

611:32

different groups. We need to create two

611:35

different groups and add them

611:37

accordingly. Here's

611:39

how. Within our constructor, we will

611:42

access self. Declare a button group.

611:45

Let's name it button group one for

611:48

simplicity.

611:49

Equals call the constructor of the class

611:52

Q button group. Then pass in self to set

611:56

the parent widget to be the

611:58

window. Then we will create button group

612:03

two. We're going to access self. Select

612:07

the radio button

612:08

group. Button group one. Call the add

612:14

button method. Then pass in a radio

612:18

button self.radio

612:21

one. Then we'll add radio 2 and radio

612:26

3. We'll select button group two this

612:30

time. Button group

612:32

two. Add radio button four and radio

612:35

button

612:38

five. The first three radio buttons are

612:41

within the same group. Radio buttons

612:43

four and five are within a different

612:44

group. We can only select one radio

612:47

button from any one radio button

612:49

group. Maybe I would like to pay with a

612:52

Visa card in store or a master card

612:55

online or a gift card in store. These

612:59

radio buttons are within different

613:01

button groups. We're limited to one

613:03

selection in any one radio button group.

613:06

When we select these radio buttons, they

613:08

don't quite do anything. For each radio

613:10

button, we have to connect a signal to a

613:13

slot. Here's

613:15

how. Let's define a method of

613:19

radio button changed. There will be no

613:23

parameters besides

613:25

self temporarily. I'll write pass. We'll

613:28

fill this in in a

613:30

moment. We will take each radio button.

613:33

Let's start with radio one. Radio one.

613:37

The signal will be toggled. When this

613:40

radio button is toggled, we will connect

613:43

a slot. We will pass in a function or a

613:47

method

613:49

self radio button changed. Then we will

613:53

do this with the other radio

613:55

buttons 1 through

614:01

5. Let's print a test message.

614:05

You selected

614:07

something just to be sure that

614:09

everything is

614:11

working. You selected

614:13

something. Okay, we know that that works

614:18

currently. What we're going to need to

614:21

do is get the sender widget which radio

614:24

button sent the signal of toggled.

614:27

I will create a local radio

614:30

button to store that radio button

614:33

whichever one emitted the signal. We can

614:36

determine that with

614:37

selfender method. The sender method is

614:41

going to return the widget that sent the

614:43

signal. So if we select radio button

614:46

one, our radio button will be radio

614:49

button one. If it was five, then it's

614:51

five in this case.

614:54

Then we'll determine if our radio button

614:56

is checked. Take our radio button. Use

615:00

the is checked method. This will return

615:03

a boolean true or false. If it's

615:06

checked, if this returns true, then

615:09

let's print the following. I'll use an

615:12

fring. We will get the text of the radio

615:15

button. radio button. Call the text

615:19

method to return the text of the radio

615:21

button.

615:23

is

615:25

selected. All right, then let's see if

615:27

this

615:29

works. Let's select Visa. Visa is

615:32

selected, Mastercard is selected, gift

615:35

card is selected, in store is selected,

615:38

and online is

615:40

selected. That's how to determine which

615:43

radio button was selected, which one is

615:45

the sender, which one sent the signal.

615:49

All right, everybody. So that is an

615:50

introduction to radio buttons in

615:54

PIQT5. Why hello everybody. Today I got

615:57

to explain lineedit widgets in PIQT5.

616:00

Also known as text boxes in pretty much

616:03

anything ever made ever. Why are they

616:05

called lineedit widgets? I really don't

616:07

know. Let's begin. From the module of QT

616:10

widgets, we will import the following

616:13

class of Q

616:16

lineedit to create a text box. I mean a

616:19

line edit

616:20

widget. We are accessing our window of

616:23

self. We will call this line ededit

616:26

widget

616:29

lineedit equals call the constructor of

616:33

the class q

616:35

lineedit. Then we will pass in self to

616:38

add this lineedit widget to the

616:42

window. Let's set the geometry but we do

616:45

have a text box in which we can type in

616:46

stuff.

616:49

I have a method to initialize the user

616:53

interface. Within this method, I will

616:55

access self dot the line edit widget and

617:00

set the

617:03

geometry. Let's set it in the top left

617:05

corner where X is 10, Y is 10. Set a

617:09

width, 200 is good, and a height

617:13

40. That's not too bad. Now the text is

617:17

really small. We can change that by

617:20

applying a

617:21

stylesheet. Access our window with self.

617:25

Access our line edit widget. Then call

617:28

the set stylesheet

617:32

method. We can pass in some CSS like

617:35

properties including a font

617:38

size. Let's pick 25 pixels.

617:44

And here's my new text box. We can read

617:46

the text. Now, let's also change the

617:49

font

617:51

family. Font family, I will pick

617:56

Ariel. This text box by itself, it

617:59

really doesn't do anything. We need some

618:02

way to get the text from the text box.

618:05

Let's add a button. When we click on the

618:07

button, we will get the text from the

618:10

text box and do something with it

618:12

because right now it doesn't do

618:14

anything. We will need to import Q push

618:19

button. Let's create one button

618:23

self.button equals call the constructor

618:26

of the class q push

618:29

button. Let's say that this is a submit

618:31

button. I will pass in a string of

618:34

submit. And we are adding this button to

618:37

our

618:38

window. And we do need to set the

618:41

geometry of the button. We're not using

618:43

a layout manager right

618:45

now. Access our window with self. Access

618:49

our button that we have previously

618:51

created in our

618:53

constructor. Then call the set geometry

618:57

method. We'll place our button where X

619:00

is 210, Y is 10, the width will be

619:05

100, and the height will be

619:08

40. Not too bad. Let's change the font

619:11

size of the button. I'll copy these two

619:14

lines of code because I'm

619:16

lazy. Instead of selecting our line edit

619:19

widget, we will select our

619:24

button. That's better. If I were to

619:27

click on the button, it doesn't do

619:29

anything. We'll set up the signal of

619:32

clicked to connect to a method that will

619:34

do

619:36

something. Let's define a method of

619:39

submit. We're submitting something.

619:41

We're submitting the text within the

619:43

text box. And for now, I'll write pass.

619:46

We'll get back to this in a

619:48

second. We're going to take our button

619:51

self.button.

619:53

We'll connect the signal of

619:56

clicked clicked dot connect method we

619:59

will connect the method of submit

620:04

self.submit. So when we click on the

620:06

button we will call this method. Let's

620:08

print a test

620:10

message. You clicked the

620:15

button. Let's type in

620:17

something. Press submit. And we get our

620:21

test message. You clicked the

620:24

button. Let's get the text from the text

620:26

box, then do something with

620:29

it. Let's create a local variable of

620:32

text. Text equals. Now we have to get

620:36

the text from our lineedit widget. self

620:40

dot

620:42

lineedit. That's the widget. To get the

620:45

text, we can use the text method to

620:47

return the text. Then let's print the

620:50

text.

620:52

I'll use an

620:53

fstring. We'll say hello, add a

620:56

placeholder, then display the

620:59

text. So

621:01

now after typing in something, why don't

621:04

you type in your name, then press

621:06

submit. We will display hello, your

621:10

name. You could add some placeholder

621:12

text,

621:13

too. Let's do that here. Let's take self

621:18

do.Eedit line edit

621:20

widget set

621:24

placeholder

621:27

text and let's say enter your

621:31

name. When I run this program, we have

621:34

some placeholder text that says enter

621:36

your name. This time I will type in

621:39

Spongebob. Then press submit. Hello

621:43

Spongebob. All right everybody. So those

621:45

are lineedit widgets also commonly

621:48

referred to as text boxes and well

621:51

everybody those are lineedit widgets in

621:54

piqt5. Hello everybody. So in today's

621:57

video I'm going to explain setting

621:58

stylesheets in piqt5. CSS means

622:01

cascading stylesheets. If you're not

622:03

familiar with CSS you can still follow

622:06

along but knowing CSS is helpful. As a

622:09

reminder, I do have a full free course

622:11

on YouTube on HTML and CSS if you would

622:14

like to learn more. Let's begin. For

622:17

this demonstration, we will need the

622:18

following imports. We will be designing

622:21

some buttons. We will import Q push

622:24

button. We'll be working with the layout

622:26

manager. We will import Q

622:29

widget. And for a horizontal layout

622:32

manager, we will need

622:35

QH box layout. So import these three

622:39

from the module of QT widgets. Now in

622:42

previous topics, we've set the geometry

622:45

of our window. Since we're using a

622:47

layout manager, we don't necessarily

622:49

need that anymore. So I'm going to

622:51

delete it. In the past, I have also

622:53

created a method to initialize our user

622:55

interface and we are calling that within

622:57

the constructor of our main window. We

622:59

will create three push button

623:01

widgets. Self do.button Button one will

623:04

be the first button equals take our Q

623:08

push button class and call the

623:10

constructor. We can add text to the

623:12

button. We will pass that as an

623:14

argument. Now since we're using a layout

623:16

manager, we don't need to add this

623:18

button to self our window. We don't need

623:21

to do that. Let's create two more

623:23

buttons. We'll have button two and

623:26

button three. Button two will say number

623:28

two. Button three will say number three.

623:31

Now we'll create a layout manager. Under

623:33

normal circumstances, we can't add a

623:35

layout manager to our main window. With

623:37

main window widgets, there's already a

623:39

specified layout and format. We're going

623:42

to add a layout manager to a central

623:44

widget. And this widget will be added to

623:47

the main window. Let's take care of that

623:50

within our initialize user interface

623:51

method. We will create a central

623:56

widget equals call the constructor of Q

624:00

widget. Then we will take self that

624:03

means our window and set the central

624:08

widget. Set central widget then pass in

624:13

our central widget to set it. Then we

624:16

will create a layout. We will call the

624:18

constructor within the class of qhbox

624:21

layout.

624:22

Let's name this layout hbox for a

624:26

horizontal box.

624:28

Equals call the constructor within this

624:31

class. We will take our layout of

624:34

horizontal

624:35

box. Then add the following

624:38

widgets. Add widget self.button

624:43

one. We'll do this with two and three.

624:49

Then the last thing we need to do is

624:51

take our central

624:53

widget, call the set layout

624:56

method, then pass in our layout

624:59

manager. And now we should have those

625:01

three buttons. They're all arranged

625:04

horizontally. Now we're going to apply

625:07

some CSS like styling using the method

625:10

of set style sheet. Here's how. Rather

625:12

than apply the CSS properties

625:14

individually such as self.button button

625:17

one set

625:19

stylesheet. And in the past, we've

625:21

passed in individual CSS properties.

625:24

We're instead going to set the

625:25

stylesheet of our window self. We have a

625:29

lot to write. Instead of double quotes,

625:32

we're going to use triple

625:35

quotes. Triple quotes are used to write

625:39

very long strings in a more organized

625:41

way. All of the CSS properties that

625:43

we're going to write are going to be

625:45

within this set of triple quotes. So,

625:47

let me give you a demonstration. We

625:49

could individually apply CSS like

625:52

properties to each of these widgets, but

625:54

we could select an entire class of

625:56

widgets, too. Let's select the class of

625:58

Q push button, then add a set of curly

626:03

braces. The following CSS properties

626:06

will apply to all Q push button widgets.

626:10

So currently this is what we have. We'll

626:13

increase the font size for every push

626:15

button. So we will add the following

626:18

property of font

626:20

size. Then set it to be 40 pixels each.

626:23

Be sure to end each CSS property with a

626:27

semicolon. So the font size is now 40

626:30

for every

626:31

button. Let's set the font. Font family.

626:36

I will pick Ariel.

626:40

Let's add some padding. We can add some

626:43

space around the text and the button

626:46

itself. So with padding, if I was to set

626:50

this to 75

626:52

pixels, we would have 75 pixels worth of

626:56

space between the text and the border of

626:58

the button. I would like to change the

627:00

dimensions of the padding. So, let's

627:03

apply 15 pixels to the top and bottom of

627:06

the button and 75 to the

627:09

sides. That's

627:12

better. Margin is the space around a

627:15

button. Let's set the margin to be 25

627:19

pixels. Now, the buttons are more spread

627:21

out. If this was 250, they would really

627:25

be spread out. That's margin. It's the

627:28

space around a widget.

627:31

Let's set that back to

627:34

25. I'm going to change the border.

627:38

Border 3 pixels

627:42

solid. This would change the border of

627:44

the buttons. We now have a black border

627:47

that's 3 pixels in width. If you would

627:50

like to round the corners, we can use

627:51

border radius. I will set that to be 15

627:55

pixels. With all the buttons, the

627:58

corners are now rounded.

628:00

Within our set stylesheet method, we're

628:02

applying all of these CSS like

628:04

properties to every push button. Now,

628:08

what if you would like to apply CSS

628:10

properties to only one widget rather

628:12

than all of them? Here's how. With each

628:15

of our widgets, buttons 1, 2, and three,

628:18

we need to set an object name. Let's do

628:21

that before we call the set stylesheet

628:23

method. We will take our buttons

628:25

self.button button

628:27

one. Call the set object name method.

628:33

Then pass in a name for this widget.

628:36

We'll keep the name the same as button

628:38

one. So let's do this with button two

628:41

and button

628:42

three, button two, button

628:46

three. Within the context of set

628:48

stylesheet, we will refer to these

628:50

widgets by their object name. Buttons 1,

628:54

2, and three. And now we can select them

628:58

individually. Let's say that with button

629:00

one, I would like the background color

629:02

to be red. We're going to access our

629:05

class of Q push button. Follow this with

629:08

a pound sign. I like to call it a

629:11

hashtag. Then we need the object name

629:14

button one. Button one refers to the

629:16

widget of button one. Again, I kept the

629:19

name the same. Then we need a set of

629:21

curly braces. Between the set of curly

629:24

braces, we can list one or many

629:26

different CSS properties. Let's change

629:29

the background

629:31

color. I will set it to be

629:34

red. And now the background color of

629:37

only that button is red and not all of

629:40

them. If I was to set the background

629:43

color within the class, well then all of

629:45

them would be

629:47

red. Okay. Okay, so with button two,

629:50

I'll just copy what we have and paste

629:52

it. We are selecting the ID of button

629:55

two. Let's set the background color to

629:58

be

629:59

green. So then the background color is

630:02

now green and button

630:07

three. Button three will be blue.

630:13

If you would like a greater variety of

630:16

colors, I recommend looking up a color

630:18

picker, you can just Google color

630:20

picker. So, if I would like a very

630:23

specific shade of red, I can pick that.

630:26

Let's go with that. There are a few

630:29

options provided to you. You can use hex

630:35

values. Now, we have a very specific

630:37

shade of red.

630:40

You can use

630:44

RGB

630:46

RGB enclose it within a set of

630:48

parenthesis and then paste those

630:51

numbers or my favorite which is HSL. HSL

630:55

means hue, saturation and

631:00

lightness. We will enclose our values

631:02

within HSL. If you copy these values

631:06

directly from Google, you would have to

631:07

remove this degree

631:09

symbol. I like HSL because I can also

631:13

control the saturation and the lightness

631:14

pretty easily. Okay, let's pick a very

631:17

specific shade of

631:20

green. That's good. I would say I'll use

631:22

the HSL

631:25

values.

631:28

HSL. Remove the degree

631:31

symbol. And now we have a very specific

631:33

shade of green and

631:37

blue. That's good. I would

631:49

say that's not too bad. If you're

631:52

already familiar with CSS, we can apply

631:55

pseudo classes such as when we hover

631:57

over one of the buttons. Here's how.

632:00

Let's copy these three

632:01

blocks, then paste them

632:06

again. We can add CSS properties. When

632:09

we hover over something, we have to use

632:11

the hover pseudo class. After the ID of

632:15

each of our buttons, we will add colon

632:18

hover. We can apply the following CSS

632:21

properties when we hover over the

632:23

buttons. All I'm going to do is up the

632:26

lightness, let's say by 20%

632:30

each. Then when we hover over one of the

632:33

buttons, the lightness is going to

632:35

change. We apply the new CSS

632:39

properties. All right, everybody. So

632:41

that is a more in-depth explanation of

632:44

the set stylesheet method in

632:47

PIQT5. All right, everybody. In today's

632:49

video, we're going to build a digital

632:51

clock widget using Python's PIQT5

632:54

library. At the top of our Python file,

632:57

we will need the following imports.

632:59

Import CIS. CIS means system. This

633:02

module provides variables used and

633:04

maintained by the Python interpreter. We

633:07

would also need widgets. Widgets are the

633:09

building blocks of a guey application.

633:12

From the package of pi

633:15

QT5, we need to access the module of QT

633:20

widgets. Import the following. Q

633:25

application Q widget. This is a generic

633:29

widget. We'll turn our digital clock

633:31

into its own widget. And Q label to work

633:35

with labels. We will be using a layout

633:38

manager, more specifically QV box

633:44

layout. There's another import we'll

633:46

need too from the package of

633:49

piqt5. Access the module of QT core. The

633:53

QT core module, it provides

633:55

functionality not related to GUI

633:57

components. This is where we'll get a

633:59

timer to keep track of the time. From

634:02

this module, we will import Q

634:05

timer, Q time, and QT. QT is for

634:10

alignment. We will create a class of

634:14

digital clock. Instead of inheriting

634:17

from the main window widget, we will

634:18

inherit from the base class of Q widget.

634:22

Q widget is a base class to create our

634:24

own widgets. Our digital clock will be a

634:27

widget. We will need a constructor. So,

634:29

let's define that. define init pass in

634:34

self. If there are any arguments to send

634:36

to the parent, we will call the

634:38

constructor of the parent the superass

634:42

super call the init

634:44

method. At the end of the constructor,

634:46

what I like to do is call a method of

634:49

initialize UI. Init UI. This will be a

634:54

separate method. Define init UI. There

634:59

are no parameters besides self. And for

635:01

now, I'll write pass. It's within this

635:03

method that we will be designing the

635:05

layout of the digital clock. Within the

635:07

constructor, that's where we will be

635:09

constructing all of the different

635:11

entities for the clock. At the end of my

635:13

Python file, I will add the following

635:15

statement. If dunder name is equal to a

635:19

string of dunder

635:22

main. This statement will be true if we

635:25

are running this program

635:27

directly. To create an application, we

635:29

will create an app object equals call

635:32

the constructor within the class Q

635:35

application. As an argument to the

635:37

constructor, we will pass in the

635:39

following argument. Access the module of

635:41

CIS argv, which means arguments. This

635:45

would apply if we're running from

635:47

command prompt or terminal, but we won't

635:49

be doing that in this video, but it's

635:51

nice just to set it up in case we do in

635:53

the future.

635:54

Now we are going to create a clock

635:57

object clock equals we will call the

636:00

constructor of our digital clock class.

636:03

There are no arguments. Now the window

636:06

doesn't appear. That's because we have

636:08

to use the show method of our clock.

636:10

Take our clock call the show method. Now

636:14

it's only going to appear for a brief

636:16

second just momentarily. I don't know if

636:18

you saw that.

636:21

To ensure a clean and proper exit of our

636:23

application, we need to call the

636:25

following method. Access our module of

636:28

CIS. Call the exit method. Then pass in

636:31

the following. We will take our app

636:34

object. Then call the following method

636:38

exec underscore and then a set of

636:41

parenthesis. It's a method. It's the

636:44

execute method. It starts the main event

636:46

loop of the application. It also handles

636:48

events such as key presses, mouse

636:51

clicks, or other user interactions. So

636:54

then we should have a window that stays

636:56

in place until we exit. Okay, now we

636:59

have the base functionality all set up.

637:02

We have a class of digital clock that

637:04

inherits from the Q widget base class.

637:07

We're not going to be using main window

637:09

in this video. Within the constructor of

637:11

my digital clock, I will create a label

637:14

self dot time label. This will be a

637:18

label that displays the time. We will

637:20

call the constructor within the class q

637:23

label. Then be sure to pass in self. We

637:26

will be adding this label directly to

637:28

our widget of clock. We will need a

637:31

timer self.time timer equals call the

637:35

constructor of q timer. then pass in

637:39

self. We are adding the timer to the

637:42

clock. Now with designing the layout of

637:44

our clock, I'll handle that within the

637:46

initialize user interface

637:48

method. We're going to set a title for

637:51

the window. self set window title

637:56

method. Pass in a string that will be

637:59

used for the title of the window. Let's

638:02

say digital clock. Then our window

638:05

should say digital

638:08

clock. Let's set the geometry of the

638:11

window. self set

638:14

geometry. The first two arguments are

638:16

going to be for the placement of the

638:18

window. Where will it appear within your

638:21

screen? So I'll pick something

638:23

approximately in the middle for me, but

638:25

feel free to change these values. Then

638:27

we need a width for the window. Let's

638:29

say 300. And a height 100 for the

638:32

height. So my window should appear

638:35

approximately in the middle of my

638:36

screen. The base width is 300. The base

638:39

height is 100. Now we're going to need a

638:42

layout manager. I will name this layout

638:45

manager VBOX for a vertical box. vbox

638:49

equals call the constructor within the

638:52

class

638:53

QVbox. This will arrange all of our

638:56

widgets vertically. But we only have one

638:58

widget, a time label. So we will take

639:01

our layout manager of

639:04

vbox add widget that's a method we will

639:09

pass in selftime label as an argument

639:12

we're adding our label to this layout

639:14

manager of

639:16

vbox then to set the layout we will take

639:19

self that applies to our clock call the

639:23

set layout method then pass in our

639:26

layout manager of

639:28

vbox. So currently if I run this we

639:30

don't see anything. Temporarily within

639:33

our label I will add some text just as a

639:36

placeholder so we can see what we're

639:38

working with. Let's say

639:42

12:00. So then we should see something

639:45

at least although the font is kind of

639:47

small. We will be getting rid of this

639:49

later. We just want to be sure that we

639:52

can see

639:53

everything. All right. So after our

639:56

layout, I would like the label to be

639:58

center aligned

640:00

horizontally. Here's how we can set that

640:02

up. We will take our label

640:05

self.time label. Call the set alignment

640:13

method. Access the class of

640:17

Qot. Access align

640:21

center. This should center align our

640:25

time. Now let's work on the font. I can

640:29

barely read

640:31

it. We will take our label

640:34

selftime

640:36

label set style sheet. We can pass in

640:41

multiple CSS like properties. Let's set

640:44

the font size. I'll set it to be 150

640:49

pixels. Now we can read it.

640:53

You could pick a font, but we're going

640:55

to change that at the end of this video.

640:56

We'll import a custom font. But

640:59

temporarily, let's say font family

641:06

Ariel. You could change the color,

641:10

too. So, if I set the color to be

641:13

green, then the font color is going to

641:16

be green, but I would like a very

641:18

specific shade of green.

641:21

You could always Google a color

641:23

picker, then pick a very specific color.

641:27

Uh, let's go with that. Something that's

641:29

bright green. You can copy the hex

641:32

value,

641:33

RGB, or HSL. HSL means hue, saturation,

641:37

and lightness. I'll use HSL

641:41

values. For the color, we will type HSL.

641:45

Add a set of parenthesis. Then paste

641:47

those values. But there is a degree

641:49

symbol. You do have to get rid of that.

641:51

Now the font color is going to be bright

641:53

green. Let's change the background

641:56

color. Here's how. We will take self

641:59

that applies to our clock. Then call the

642:02

set stylesheet

642:04

method. Pass in a background

642:08

color. We will set the background color

642:10

property to be

642:14

black. I think that looks pretty good,

642:16

but it doesn't quite do anything quite

642:18

yet. That's the next step. Let's create

642:21

a method to update time. No arguments

642:26

besides self. I will create a local

642:28

variable of current time equals. Now to

642:32

get the current time, we can access the

642:35

class of Q

642:37

time. Q time dot call the method of

642:42

current

642:42

time. We will need to convert it to a

642:45

string. We will method chain the tworing

642:49

method. Within the two-string method, we

642:51

will design the layout of the time. So,

642:54

I would like hours first. I will type

642:57

two h's colon minutes. That's 2 m's

643:01

colon 2

643:02

s's. To set the text of the label, we

643:05

will take selftime

643:07

label. Call the set text method. Then

643:11

pass in our current time.

643:15

So if I run this currently, we still

643:17

have our placeholder time. Let's update

643:20

it with the current time. We can get rid

643:22

of our placeholder text of 12. We can

643:25

delete

643:27

it. After we set the font, let's call

643:30

the method of update time. self.update

643:36

time. Now we should display the current

643:38

time. So me, I'm recording this video at

643:41

7:44 in the morning.

643:43

If you would like to add AM or PM after

643:46

your time, here's

643:47

how. After our string format specifiers,

643:51

we will add capital A. A means

643:54

anteridium and P means post

643:57

meridian. So then we should display A.M.

644:00

or P.M. depending on when you're coding

644:02

this. Currently, the time for me is 7:45

644:06

a.m. To get the clock to update every

644:09

second, we need to connect our timer

644:12

widget to a slot of update time. We will

644:15

take our timer self.time timer. This

644:18

isn't the time label, it's the timer to

644:20

keep track of the time. During a signal

644:23

of time out, we will connect the

644:27

following slot of

644:30

self.update time

644:33

self.update time. With our timer, we

644:36

need to trigger a timeout signal every

644:39

1,00 milliseconds. Every second, that

644:42

is. To handle that, we will take our

644:44

timer self.time timer, call the start

644:47

method, then pass in 1,00 for 1,00

644:52

milliseconds. So then when we run this

644:55

program, our clock should update every

644:57

second and display the new current time.

645:01

As an added bonus, if you would like to

645:03

download a custom font, here's how.

645:06

Using Google or another search engine, I

645:08

would recommend looking up a font of

645:10

your choosing. So, one font that I like

645:12

is DS Digital. What we need is a TTF

645:16

file, meaning true type font. I'll just

645:20

pick this first

645:21

link. So, these fonts are pretty good.

645:25

So, I'm going to download them.

645:28

I'll pick this specific font, DS Digit.

645:31

And again, the file extension is

645:34

TTF. So once you have your font, move it

645:37

to your project folder. So for

645:39

convenience, we have that TTF file right

645:41

next to our main Python file. Okay. To

645:45

work with specific fonts, we will need

645:46

the following. Import from piqt5.

645:53

QT

645:55

gui

645:56

import Q

645:59

font as well as Q font data

646:06

base. Since we're going to use our own

646:08

custom font, we can delete that from the

646:10

set stylesheet method of our time label.

646:13

So let's set the font right here. We

646:17

will assign a local variable of font

646:20

id equals

646:22

q font

646:25

database. Q font database is a class for

646:28

managing and querying fonts available to

646:31

the application. To add a custom font,

646:34

we will call the following method within

646:35

it. Add

646:38

application

646:40

font. Within the set of quotes, we're

646:43

going to pass in a file path. This can

646:45

be a relative file path or an absolute

646:47

file path. This TTF file is right next

646:50

to my main Python file. I only need the

646:53

file name. My font file is named

646:56

DS digit and get the file extension of

647:01

TTF. We will create a local variable of

647:04

font

647:06

family. We will retrieve the name of the

647:09

font family from this ID. Again we will

647:13

access Q font database dot call the

647:19

application font families method. So

647:23

this method returns a list of font

647:24

names. We will pass in our

647:27

font

647:29

ID. But there's another step. We're

647:32

going to use the index of operator and

647:35

get the index of zero. This will

647:37

retrieve the first element of the font

647:39

family. That's because we're working

647:41

with a list. We will need just the first

647:43

element at index zero. Now we'll have a

647:46

font family to work with. Now to set the

647:49

font, we will create a local variable of

647:53

my font equals call the class. Call the

647:57

constructor within the class Q

648:01

font. Pass in the following arguments.

648:05

our font family, that's the first

648:08

argument, and then a font size, let's

648:10

say 150. To set the font, we will take

648:13

our time label, self dot time

648:18

label, call the set font

648:21

method, then pass in my font, our custom

648:26

font. So then we should have our custom

648:28

font, that digital font that we've

648:31

downloaded. All right, everybody. So

648:33

that is how to create a digital clock

648:35

widget using

648:37

PIQT5. Hey yeah everybody. So in today's

648:40

video we're going to create this

648:41

stopwatch program using Python's PIQT5

648:44

library. Once that's out of the way you

648:46

will need the following

648:48

imports. Import cis. CIS means system.

648:51

It handles system variables for your

648:53

Python interpreter. We will need the

648:55

following widgets from

648:58

piqt5. Access the module of QT widgets.

649:04

Widgets are the building blocks of a

649:06

PIQT5

649:07

application. We will import the

649:09

following widgets.

649:11

Q

649:13

application.

649:14

Q widget. Q label. Q push

649:22

button. QV box

649:26

layout. and QH box

649:29

layout. Let me put these on a new line

649:32

just so we can read everything from the

649:34

package of

649:36

PIQT5. Access QT core. We will

649:40

import Q timer. Our timer will emit a

649:45

signal after a given interval, which is

649:47

what we need for a stopwatch. Q time to

649:50

keep track of the time and QT for

649:53

alignment. Let's do a test run to be

649:55

sure that there's no

649:57

errors. Looks like L and label should be

650:01

capital. There we go. No errors. Once

650:04

you have the following imports, we will

650:07

construct a class, a class of

650:10

stopwatch, which will inherit from the

650:13

base class of Q widget. Our stopwatch

650:16

will be a widget. We will need a

650:19

constructor. We'll define that dunder

650:22

init.

650:23

No arguments besides self. If we have

650:26

arguments to pass to the parent of Q

650:28

widget, we will call the superass the

650:31

parent. Call the constructor of the

650:33

parent. No arguments

650:35

currently. Now if we are running this

650:38

file directly, we'll use an if statement

650:40

to verify that if dunder name is equal

650:44

to a string of dunder main. If this is

650:48

true, if we are running this file

650:50

directly, then we will construct a

650:53

stopwatch. We will create an app object.

650:56

Call the constructor within the Q

650:58

application class. Pass in the following

651:01

access cis our system access argv which

651:06

means arguments. This is if we're using

651:09

command line arguments, which we won't

651:11

be using, but it's nice to futureroof

651:13

our code just in case we do in the

651:15

future. We will create a stopwatch

651:18

object. Stopwatch equals call the

651:22

constructor within our class of

651:24

stopwatch. Our window is not going to

651:27

show unless we call the show method.

651:30

Take our stopwatch. Call the show

651:32

method. Now our window is only going to

651:35

show for a brief

651:37

second. We need to ensure a clean exit.

651:40

We can access cis. Call the exit method.

651:44

pass in the

651:46

following app then call the

651:50

exec method. This method starts the main

651:54

event loop and handles

651:56

events. So then we should have a basic

651:58

window which stays in place until we

652:01

close it. We now have the main skeletal

652:04

structure of a PIQT5 application set up.

652:06

If you're one of the people that have

652:08

jumped ahead up until this point, we

652:10

have a class of stopwatch which inherits

652:12

from the Q widget class.

652:14

We've constructed a stopwatch object and

652:17

we're showing it. So now we can begin

652:19

designing our stopwatch. We will create

652:22

a time object. self dot time equals call

652:27

the constructor within the class of Q

652:29

time. For arguments, we'll pass in the

652:32

hours, minutes, seconds, and

652:34

milliseconds all

652:36

zero. We need a label for the

652:39

stopwatch. self.time

652:41

time label equals call the constructor

652:45

of Q label. What would we like the text

652:48

to say? I'll display some placeholder

652:51

text. A bunch of

652:54

zeros. 0 hours, minutes, seconds, and

652:58

milliseconds. We will add this label to

653:01

self, our

653:03

stopwatch. We need a start button.

653:05

Self.st Start button equals call the

653:10

constructor within Q push button. What

653:13

would we like the text of the button to

653:15

say? Let's say start. We are adding this

653:19

button to self. Our

653:22

stopwatch. We need a stop button. Let's

653:26

replace start with stop. Change the text

653:29

from start to stop and reset.

653:34

The name of this button will be the

653:36

reset

653:37

button. The text will be

653:39

reset. We will need a timer to emit a

653:43

signal at a given interval. self.time

653:46

timer

653:47

equals call the constructor within the

653:50

class Q timer. Then pass in

653:54

self. We're going to call a method of

653:56

initialize UI

653:59

self.init UI.

654:02

But we still have to define this

654:04

method. All right. Within our stopwatch

654:06

class, we need the following

654:08

methods. A method of init UI. This is

654:13

where we'll be designing the user

654:15

interface. I'll write pass for now as a

654:19

placeholder. We need a method to

654:22

start to start the stopwatch. That is a

654:26

method to stop the

654:29

stopwatch. a method to reset the

654:35

stopwatch. We'll create a method to

654:37

format our time. Format time. Besides

654:41

self, there's one parameter. We have to

654:43

pass in a time to format. We will be

654:46

returning a string, a string

654:48

representation of the current

654:50

time and a method to update our display.

654:55

Update

654:58

display. Here are the six methods we'll

655:02

need. Within our initialize user

655:04

interface method, we will set the title

655:07

of the window because right now it says

655:10

Python. We will take self our stopwatch.

655:14

Call the set window title

655:18

method and we will pass in

655:22

stopwatch. That should change the title

655:25

of the window to stopwatch. We're going

655:27

to use a vertical layout manager for the

655:30

label and the

655:32

buttons. We will create a layout manager

655:34

named VBox. vbox equals call the

655:38

constructor of

655:40

QV box

655:43

layout. We will take our layout manager

655:46

and add the following

655:50

widgets. self.time

655:54

label. Then our start, stop and reset

655:59

buttons, start

656:03

button, stop

656:05

button and reset

656:12

button. We will take

656:14

self set the

656:17

layout pass in our vertical layout

656:19

manager.

656:23

So, we have all of our buttons. We have

656:25

our widgets arranged in a column. We're

656:28

going to take our time label and also

656:30

center it

656:32

horizontally. We will take our time

656:34

label self.time

656:37

label. Call the set alignment

656:41

method. Access our class of QT.

656:45

access the flag of align

656:49

center. That's going to center align the

656:52

time. It should be aligned both

656:54

vertically and

656:56

horizontally. Now with your buttons,

656:58

they're arranged in a column. We could

657:01

group them together

657:02

horizontally. Here's how. We will create

657:05

a horizontal layout manager of HBox.

657:08

hbox equals call the constructor of

657:12

QHBOX

657:15

layout. Instead of adding these buttons

657:17

directly to our vertical layout manager,

657:20

let's cut

657:23

them. Paste them underneath

657:26

HBox. Replace Vbox with HBox.

657:31

Then with our vertical layout

657:33

manager

657:35

Vbox, we will add our layout of

657:42

Hbox. This group of buttons is arranged

657:45

vertically with the time

657:47

label. Now we'll be applying a

657:50

stylesheet. Access self our stopwatch.

657:54

Call the set style sheet method.

657:58

We can pass in one extremely long string

658:01

with a set of triple quotes. All of the

658:04

CSS like properties we'll add will do so

658:06

between the set of triple quotes. Let's

658:09

select our buttons. Q push button. We

658:13

are selecting an entire

658:16

class. Within a set of curly braces,

658:19

let's add the property a font size. The

658:22

font size of all buttons will be 50

658:23

pixels.

658:27

Let's customize our label. Select the

658:30

class of Q

658:32

label within a set of curly braces.

658:35

Let's add the following properties. Font

658:38

size will be

658:42

120. If you would like, we can add a

658:44

background color too to the

658:47

label. We can select a background

658:51

color temporarily. I will select blue.

658:54

But we can pick more specific shades of

658:56

blue or another color. Here's

658:59

how. You can look up a color picker and

659:02

select a very specific color. You can

659:05

use hex values, RGB, or HSL. I've

659:09

already selected a color. I'm going to

659:11

copy these HSL values. So, instead of a

659:14

color name, we will select HSL. Then

659:18

paste those values. If you have a degree

659:21

symbol, you will need to remove that.

659:24

And now we have a very specific shade of

659:27

blue. I will also round the corners of

659:29

our

659:30

label. Add the property of border

659:33

radius. I will set that to be 20

659:37

pixels. This will round the corners

659:40

between each button and label. We'll add

659:42

some

659:42

padding. We're going to use multiple

659:45

selectors. We will select all push

659:49

buttons and all labels.

659:52

apply the following properties to each.

659:55

I will add padding of 20 pixels around

659:59

these

660:01

widgets. And I will also make the font

660:04

weight

660:06

bold. Font weight will be

660:11

bold. All right, I think that looks

660:13

pretty good. Hey, this is Bro from the

660:15

future. I am currently editing this

660:17

video. If you would like, you can add a

660:19

font family. One font that I think looks

660:22

really good is

660:24

Calibri. We'll apply that to all push

660:26

buttons and Q

660:28

labels. I really like this font. I think

660:30

it fits a stopwatch, but it's up to you

660:32

if you would like to change the font. I

660:34

just thought I would mention that. Now,

660:36

we just have to add some functionality

660:38

because these buttons don't do

660:40

anything. For each of our buttons, we

660:43

have to connect a signal to a slot. We

660:46

will take our start button self. Start

660:51

button with the signal of clicked. We

660:54

will connect the following slot. We will

660:57

call the start method self.st start

661:00

method. Let's do this with the stop

661:03

button. Change start to

661:06

stop clicked connect self.s stop

661:11

method

661:13

reset self.reset reset button called the

661:17

reset

661:20

method. At a given interval, we're going

661:23

to update our

661:25

display self.time timer during a signal

661:30

of

661:31

timeout. We will connect the following

661:34

method. self.update

661:37

display self.update

661:40

display. Within our start method, we

661:43

will take our timer self.time a timer.

661:46

Call the start method. Pass in 10 for 10

661:50

milliseconds. We will set an interval

661:53

for a timeout every 10

661:57

milliseconds. Within our stop method, we

661:59

will take our timer and instead call the

662:02

stop

662:04

method. We'll get back to reset in just

662:07

a moment. Let's work on the format time

662:09

method.

662:11

From our time that we pass in, we have

662:13

to get the hours, minutes, seconds, and

662:15

milliseconds. We will create some local

662:18

variables. Hours equals access our time

662:21

that we pass in. Call the hour method to

662:24

return

662:25

hours. We have variable minutes. Time

662:29

dot call the minute method to return the

662:32

minutes. We have a variable of seconds.

662:35

seconds seconds equals take our time.

662:37

Call the second

662:39

method. Then for

662:43

milliseconds access our time call the

662:47

mc which means milliseconds and call it

662:51

this is a

662:52

method. I'm going to return a string an

662:55

string to represent the

662:58

time. We will add four

663:01

placeholders hours and milliseconds.

663:06

Each will be separated with a colon

663:08

except for milliseconds which will be a

663:10

dot a

663:12

period. We will display the

663:15

hours. I'll add some leading zeros. Two

663:18

leading zeros. Let's do this for

663:23

minutes. We're using a format specifier

663:25

for two leading zeros as

663:27

well.

663:31

Seconds and milliseconds.

663:39

Now we will work on the update display

663:41

method. We have to get the time self dot

663:45

time equals we will take our

663:49

time but call the add milliseconds

663:53

method

663:56

mcs then pass in 10 for 10 milliseconds.

664:01

We're going to take our time label

664:04

self.time

664:06

label and set the text of

664:09

it. We will call our format time

664:13

method. But we have to pass in a time.

664:16

We will be passing in

664:19

selftime. Let's see what we have

664:22

currently. We can start the

664:25

stopwatch and we can stop it.

664:29

However, we're displaying three digits

664:31

for the milliseconds. We can eliminate

664:34

that within format time. When we get the

664:37

milliseconds, we will use integer

664:40

division. We will divide by 10. This

664:44

will convert our milliseconds from three

664:45

digits to two. We're basically dividing

664:48

by

664:49

10. So, here's our stopwatch. currently

664:52

we can

664:54

start, we can stop, we can start again

664:57

and we can stop again. Now we just need

665:00

to reset. Here's how. Within the reset

665:04

method, we will take our timer self.time

665:07

timer use the stop method to stop. We

665:11

will reassign our time call the

665:14

constructor of Q time. We have to pass

665:17

in hours, minutes, seconds, and

665:19

milliseconds. They're all going to be

665:21

zero. We're resetting our time. And then

665:25

we'll reset the text again of our time

665:27

label.

665:28

self.time label. Call the set text

665:32

method. When we set the text, we will

665:35

first format it with the format time

665:38

method. But we have to pass in a time.

665:40

We will pass in

665:44

selftime. And now we should be able to

665:46

reset our stopwatch.

665:48

We can

665:50

start, we can

665:53

stop, we can reset, start again, and

665:57

stop

665:58

again. All right, everybody. So, that is

666:01

a cool stopwatch that you can make using

666:04

Python. Hey, uh, what's going on

666:06

everybody? So, in today's video, we're

666:08

going to create a working weather app

666:10

that fetches real-time weather data from

666:12

an API. This is a massive project, so

666:15

feel free to take your time. take

666:17

several days or even weeks if you need

666:19

to complete this. Heck, you can even add

666:20

this project to your portfolio. Well,

666:23

let's get started,

666:27

everybody. All right, let's get started,

666:29

everybody. This is a fairly useful API

666:32

to get real-time weather data. The

666:34

website is

666:36

openweathermap.org. You will need your

666:38

own API key, but signing up for an

666:40

account is free. To create an account,

666:42

we'll go to sign

666:43

in, create an account, enter your

666:47

information, and then sign

666:49

in. Once you're signed in, to find your

666:52

API key, go to this drop-own menu, go to

666:55

my API keys, and you would just need to

666:58

copy this API key. If the status is

667:01

inactive, you'll need to toggle it to

667:04

active, like

667:06

so. Now, it may take several minutes for

667:08

your API key to become active. Hopefully

667:11

by the time of this project where we

667:13

will need it, it'll be active. I would

667:15

either leave up this window or copy this

667:17

key and paste it

667:19

somewhere. We will need the following

667:21

imports. We will import CIS. CIS means

667:25

system. It handles system variables for

667:27

your Python interpreter. We will import

667:30

the request module to make a request to

667:33

an API. Then we'll need widgets. Widgets

667:36

are the building blocks of a PIQT5

667:38

application.

667:40

From the package of

667:42

PIQT5, access the module of QT

667:46

widgets. Import the following

667:49

widgets. Q

667:52

application, Q

667:55

widget, Q

667:57

label, Q

668:01

lineedit, Q push

668:03

button. Let me put some of these on a

668:06

new line for readability.

668:10

QV box

668:13

layout. This is a vertical layout

668:16

manager. To work with alignment, we'll

668:18

need the following. From the package of

668:21

piqt5, from the module of QT core,

668:25

import the following class QT, which is

668:29

used for

668:30

alignment. So, these are the imports

668:32

that you'll need. Just to be sure that I

668:34

didn't misspell anything or get the

668:37

capitalization wrong, I'm just going to

668:38

do a test run. No problems. Processed

668:42

finished with exit code

668:44

zero. Sometimes I make one of these

668:46

characters lowercase and then it doesn't

668:49

work. Okay, we have our imports. We will

668:53

need to create a class of weather app.

668:57

Weather app is going to inherit from the

668:59

parent of Q widget.

669:04

We will need a constructor. So we'll

669:06

define that under

669:08

init arguments besides

669:10

self. In case we have arguments to send

669:13

to the parent, we will call the parent

669:16

with super meaning the

669:18

superass then call the constructor. But

669:21

currently we don't have any

669:23

arguments. If we are running our main

669:25

Python file directly, we can verify that

669:28

with an if statement. If dunder name is

669:33

equal to a string of dunder

669:37

main. If we are running this file

669:40

directly then we will create a weather

669:42

app object. Otherwise we won't. If this

669:45

statement is true we will do the

669:47

following. We will create an app object

669:51

app equals call the constructor within

669:53

our Q application class. But we will

669:56

pass in the following. Access the module

669:59

of CIS then access a argv which means

670:03

arguments. If we have command line

670:06

arguments to send to our application,

670:08

this is how we would take care of that.

670:10

But we're not going to be using command

670:11

line arguments in this video, but it's

670:13

nice to futureroof our code just in case

670:15

we do. We will construct a weather app

670:19

object. Weather app equals call the

670:22

constructor of our weather app class.

670:24

Now this window isn't going to show. We

670:27

have to call the show method of our

670:29

weather app. Weather app

670:32

show. And now it's going to show for a

670:34

brief

670:36

second. We need to ensure a clean exit.

670:39

Access

670:40

cis. Call the exit method. Within this

670:43

method, we will pass in the following.

670:46

Take our app. Call the execute method

670:49

which is

670:52

execore. It is a method. So we have to

670:54

call it. This method handles events

670:57

within our

670:58

application such as closing the

671:01

window. So now our window should stay in

671:03

place until we close

671:06

it. If you're one of the people that

671:08

have jumped ahead, we have created a

671:10

class of weather app which inherits from

671:12

the parent of Q widget. We've

671:15

constructed a weather app object and

671:17

we're showing it. If you've made some

671:20

PIQT5 projects in the past, you would

671:22

just have to change some of these

671:24

around. Within the constructor of our

671:27

class weather app, we will declare the

671:29

different widgets that belong to our

671:30

weather app object. We will create a

671:33

label that prompts the user to enter in

671:35

a city. We will name this city label

671:38

equals this is a Q label widget. We can

671:43

set the initial text of the label. Let's

671:46

say enter city

671:49

name. Then the second argument is going

671:52

to be self. We are adding this label to

671:55

our weather app object. Here's what we

671:58

have

671:59

currently. We still have to do some CSS

672:02

formatting, but we'll take care of that

672:05

soon. We will need a line edit widget,

672:08

basically a text box. We will name it

672:12

city input.

672:16

The widget is line

672:19

edit. No parameters besides

672:24

self. Here is our line edit widget.

672:27

We're not currently using a layout

672:28

manager. These widgets are going to

672:32

overlap. We need a button

672:36

self.get weather button.

672:40

This is a Q push

672:43

button. The text on this button will be

672:46

get weather. We are adding this to self,

672:50

our weather app

672:52

object. Here's our

672:54

button. When we click on this button,

672:57

we'll make a request to an API. For the

672:59

next following widgets, we're going to

673:01

add some placeholders just so that we

673:03

can see what we're doing when we apply

673:04

CSS

673:05

styling. We need a temperature label to

673:08

display the temperature.

673:11

temperature

673:13

label equals a Q

673:17

label temporarily for the label. Let's

673:20

say that the temperature is 70° F or

673:24

pick something else in Celsius. So to

673:26

add a degree symbol, if you're using

673:28

Windows, make sure num lock is on, hold

673:30

alt, then on the numpad, type

673:33

0176. I will pick 70° F.

673:37

And then we will add this to

673:39

self. Again, we're just using this

673:41

temperature as a placeholder. We'll

673:43

delete it when we do a test

673:45

run. If you would like to include an

673:47

emoji or some other image, we can create

673:50

a label for that. I will name this emoji

673:55

label equals a Q

673:58

label. I will add an emoji of a sun as a

674:03

placeholder. Again, we're going to

674:05

delete this when we do a test run.

674:07

We are adding this to

674:11

self again. Everything is overlapping.

674:14

That is

674:15

fine. And we need a description of the

674:19

weather.

674:21

Description

674:23

label equals a Q

674:26

label as a placeholder. Let's say that

674:29

it's sunny and we are adding this label

674:32

to

674:33

self. Okay. Here are all the widgets.

674:36

They're all overlapping. So, we need to

674:39

fix

674:41

that. All right, moving on everybody.

674:44

So, now we have to design the layout of

674:46

our web app. Right now, all of our

674:49

widgets are gravitating to the top left

674:51

corner. So, I will define a

674:54

method to initialize our user

675:01

interface. At the end of this

675:02

constructor, we will call this method

675:04

self.initialize initialize UI, then call

675:08

it. Once we've constructed our widgets,

675:11

we'll format them and design the

675:15

layout. So, we are now within our

675:17

initialize user interface

675:19

method. First, let's set the title of

675:22

our window. Self set window

675:27

title. Let's say that the title is

675:30

weather app.

675:32

So that should change, which it

675:36

does. We're going to use a vertical

675:38

layout manager to handle all the

675:41

widgets. Let's name the layout manager

675:44

VBox equals call the constructor of the

675:47

class QVox layout. We're going to take

675:51

our layout manager of VBox. Then add a

675:55

widget. We will start with the city

675:58

label. That's

676:00

first. We will pass in self.c city

676:04

label. And we'll do this with the other

676:06

widgets

676:08

too. We have city

676:13

input, get weather

676:18

button, temperature

676:24

label, emoji

676:28

label, and then a description label.

676:36

take self our weather app set the

676:40

layout. We will pass in the layout

676:42

manager of

676:44

VBox. And here's what we have

676:49

currently. All the widgets are arranged

676:51

in a column. Now we just have to center

676:54

align them horizontally. Here's

676:58

how. We will take self.c city

677:02

label. Call the set alignment

677:07

method. Access the class of QT. Access

677:11

the flag of align

677:14

center. We're going to align all of our

677:17

widgets in the center except for our

677:19

weather button. Currently, our button

677:21

expands to take up the width of the

677:24

window. So, we don't need to

677:26

horizontally align that. So we have five

677:29

widgets to

677:31

align. We have city label, city input,

677:35

temperature label, emoji label, and

677:38

description

677:39

label. All of the widgets are going to

677:42

be arranged in a column

677:44

horizontally. Now we just have to apply

677:46

some CSS styling because right now it's

677:50

kind of

677:51

ugly. We will apply styles based on an

677:54

object name, but we have to set that

677:56

object name. So let's start with our

677:58

city label self. city

678:02

label. Call the set object name

678:08

method. Pass in a unique ID for this

678:11

widget. I will name it city label. I'll

678:14

keep it the same. Okay. We have to do

678:17

this with the other widgets

678:19

too. We have a total of six.

678:22

We have city label, city

678:27

input. We have the get weather

678:33

button, temperature

678:36

label, emoji

678:38

label, and description

678:43

label. Then we're going to set a

678:46

stylesheet. Take self, our weather app.

678:48

Apply a stylesheet with set style

678:52

sheet. We have a lot of properties to

678:55

write. I will do so within a set of

678:57

triple quotes just to keep everything

678:59

more

679:00

organized. We can apply CSS styles based

679:03

on a class. So the class is going to be

679:07

Q label. Within a set of curly braces,

679:09

we can list multiple CSS properties. I

679:12

will set the font family to be Calibri.

679:18

as well as all push buttons. Q push

679:23

button. So here's the font, although

679:26

it's still kind of small. Let's select

679:28

our ID of city label. It's good practice

679:32

to preede this ID with the name of the

679:34

class. So Q label pound sign the

679:39

ID. We preede the ID with the name of

679:42

the class. Just so we're only applying

679:44

these CSS properties to any ID that's a

679:47

city label that falls within the class

679:50

of Q

679:51

label. Let's set the font size to be 40

679:55

pixels. Let's set the font size to be 40

679:59

pixels. That's

680:01

better. I'll set the font style to be

680:05

itallic. Font style

680:09

itallic. That's pretty good.

680:14

Let's select the ID of city input. This

680:17

is a line edit widget. Q

680:21

lineedit pound the ID of city input

680:26

within a set of curly

680:27

braces. Let's set the font size to be 40

680:32

pixels.

680:39

We will select our push button which is

680:41

named get weather button. The class is Q

680:45

push button pound. The ID of get weather

680:50

button within a set of curly braces. We

680:52

will apply the following. Let's set the

680:55

font size to be 30

681:00

pixels. And let's make it bold. font

681:04

weight

681:11

bold. Let's select our temperature

681:14

label. The ID is temperature label and

681:17

this is a Q label pound temperature

681:22

label. We will increase the font

681:25

size. Font size 75 pixels.

681:34

better. Let's work on our emoji.

681:39

Next, we will select the ID of emoji

681:43

label. The class is Q label. The ID is

681:48

emoji

681:49

label. We'll set the font size first.

681:53

Font size 100 pixels. I would like a

681:56

large

681:58

image. To display emojis properly, we're

682:01

going to use a very specific font. We're

682:04

going to set the font family to be, now

682:08

I don't know if I'm saying this

682:09

right,

682:12

segi

682:14

emoji. I probably pronounced this word

682:16

wrong, but I don't

682:20

care. So then our emoji should display

682:22

correctly using this font. It's

682:27

colorful. Then we have the description

682:29

label of the weather. That is the last

682:32

widget description label. The class is Q

682:35

label. The ID is description

682:39

label. Let's take the font size and set

682:43

it to be 50

682:46

pixels. All right. So this is what our

682:48

weather app is going to look like. We

682:51

have the city label, a text box to enter

682:54

in a city, the get weather button, the

682:57

temperature label, an emoji label, and a

683:00

description of the weather currently.

683:02

Now, we just have to add some

683:04

functionality because currently this

683:06

doesn't do

683:08

anything. All right, so now we just have

683:10

to add some functionality to our weather

683:12

app. Temporarily, I'm going to collapse

683:15

our initialize user interface method. We

683:18

will define a few extra methods. Let's

683:20

declare a method of get

683:23

weather. No parameters besides self.

683:27

I'll write pass for now as a

683:29

placeholder. We will need a method to

683:32

display any errors. Display

683:36

error. There's going to be one argument

683:38

besides self, a message. We will pass in

683:41

an error message if there is

683:44

one. and a method to display weather.

683:49

That's if there's no errors. We will

683:52

need some data, our weather

683:55

data. So, be sure that you write these

683:58

three

683:59

methods. Back within our initialize user

684:02

interface method at the

684:06

bottom, we have to connect a signal to a

684:09

slot. When we click on the button with

684:12

the signal of clicked, we will connect a

684:15

slot of get weather. We will access

684:19

self. Take our get weather

684:23

button with a signal of clicked. We will

684:28

connect a slot of self.get

684:32

weather. And I will print a test message

684:36

just to be sure that it's working.

684:38

You get the

684:41

weather. So I press the button and we

684:44

will display you get the

684:48

weather. We can get rid of our

684:50

placeholder text for the temperature,

684:52

our emoji, and the weather

684:55

description. So we can delete these

684:58

strings, but be sure to keep

685:06

self. Scrolling down to our get weather

685:08

method. When we click the button, we're

685:12

going to create a few local variables.

685:14

The first is going to be our API key

685:19

equals. This will be a

685:21

string. Back to the open weather API,

685:25

you will copy your API key and make sure

685:28

that it's active. You can use the toggle

685:30

button to make it inactive and

685:32

active. So, make sure that it's active.

685:37

Paste your API key within a string.

685:40

Please use your own. It still may take

685:42

several minutes for your key to be

685:44

active. Just keep that in

685:46

mind. We will need to get the city that

685:49

we're looking

685:51

up. So let's say we type in Miami. I

685:55

have to get the text from this widget.

685:57

This line ededit widget. We will create

686:00

a local variable of city. city equals

686:04

access our line edit widget. It had a

686:07

name of city

686:11

input. So self.c city input to get the

686:15

text we will call the text

686:17

method. We have the API key and the

686:20

city. Now we will create a URL. This

686:24

will be an

686:25

fstring using the request module. we

686:28

will pass in a URL to make a request

686:32

to. So, back to our open weather API. To

686:35

get the URL for a city, we have to go to

686:38

the tab of

686:40

API, scroll down to current weather

686:43

data, and there's going to be some API

686:46

documentation. To the right, we have a

686:48

link for built-in API request by city

686:51

name.

686:53

We will copy this

686:55

URL and paste it within our F string.

686:59

There's two changes we're going to make.

687:01

We will replace city name with city, the

687:04

name of that variable, and API space key

687:08

with

687:11

API_key. It doesn't matter what you name

687:13

these. Just make sure they're consistent

687:15

with your

687:16

variables. When we make an API request,

687:19

we will be returned with a response

687:21

object. response equals access our

687:25

module of requests call the get method

687:29

then pass in our

687:32

URL with our response object we have to

687:35

convert it to a JSON

687:37

format we will be returned with an

687:39

object we will name this object data

687:42

it's going to be readable to us data

687:45

equals take our response object and use

687:48

the JSON method to convert it to a JSON

687:51

format at. So, let's print our data to

687:54

see what we're working

687:57

with. Let's say I look up the city of

688:04

Miami. So, we have one gigantic

688:08

object. This is our weather data. We

688:11

have coordinates such as longitude and

688:15

latitude, a weather description.

688:18

Currently in Miami, there's broken

688:21

clouds. There's an ID of the weather.

688:24

This is the temperature, but it's in

688:26

Kelvin. If we scroll all the way to the

688:29

end, we are looking for an HTTP status

688:33

code, which is named Cood, short for

688:36

code. 200 means that the response was

688:39

successful. Depending on what this

688:41

number is, we will display one of the

688:43

few error messages. If our status code

688:46

is 404, that means the city wasn't

688:48

found. And there's many others. So 200

688:52

means that the request was

688:54

successful. So let's write the

688:57

following. If our data object at key of

689:03

COD, if this is equal to 200, if the

689:07

request was successful, then we will

689:10

call the display weather method self.

689:13

display

689:14

weather, but we do have to pass in our

689:19

data. Now, temporarily, I'm just going

689:22

to print our weather data. We'll do some

689:25

more complex stuff later, but I just

689:27

want to be sure that everything is

689:29

working. So, let's look up Los

689:34

Angeles. So, here's the weather in Los

689:36

Angeles.

689:39

There is currently broken

689:42

clouds. And again, the status code is

689:44

200. The request was

689:48

successful. I'll write an else statement

689:50

for now. We will print our data. What if

689:54

we can't find a city? For example, I

689:57

will look up the city blah blah blah and

690:01

get the

690:03

weather. So, here's our weather data. We

690:06

have an error code of 404 and a message

690:09

of city not found. Let's do some

690:12

exception handling in case we run into

690:14

one of these status codes that's not

690:17

200. We can get rid of our else

690:20

statement. What we'll do is enclose all

690:23

of our dangerous code. That means any

690:25

code that might cause an exception

690:27

within a try block.

690:30

We will try all of this code and handle

690:33

any exceptions with an accept block.

690:37

There's two types of exceptions we're

690:38

looking for. The first is an HTTP

690:45

error. HTTP error is an exception raised

690:49

by the request module when an HTTP

690:52

request returns a status code that's 400

690:56

or 500. However, this exception is found

690:59

within the request module that we've

691:03

imported. So, we can't simply just say

691:06

accept HTTP error. We first have to

691:10

access the request module then access

691:14

exceptions. Then we can list the

691:17

specific exception of HTTP error.

691:20

will encounter this exception if the

691:23

status code is between 400 and

691:28

500. And for now, I'll write

691:31

pass. So there's one more step within

691:33

our try block. If we're going to handle

691:36

any HTTP errors, we have to raise an

691:39

exception within our try block because

691:42

our try block by itself normally doesn't

691:44

catch these. We will take our response

691:48

object and call the raise for status

691:54

method. This method will raise an

691:57

exception if there's any HTTP errors.

692:01

Normally our try block doesn't do that.

692:03

So we have to manually type

692:05

this. There's another type of exception

692:08

we'll catch and that's the request

692:09

exception. We'll add another block for

692:14

accept

692:16

request

692:19

exception. This is found within the

692:21

request

692:22

module.

692:24

Requests

692:26

exceptions. Request

692:28

exception. With a request exception,

692:31

this can be due to network problems,

692:33

invalid URLs, exceptions of that nature.

692:37

In case we run into one of those types

692:39

of exceptions, we will execute this

692:41

block of code. But for now, I'll write

692:43

pass. We'll get back to it

692:46

later. Going back to our accept block

692:48

where we handle any HTTP errors. Let's

692:51

use a match case statement, we need to

692:54

get the status code of our response.

692:56

I'll print that temporarily.

692:59

Let's print our response objects status

693:01

code and see what it

693:06

is. Again, let's make up a city. Get the

693:09

weather. We have a status code of 404.

693:13

That means the city wasn't found.

693:15

Depending on what this number is, the

693:16

status code, we'll use a match case

693:21

statement. So we will match our response

693:24

objects status

693:30

code. The first case will be

693:35

400. That means there's a bad

693:38

request. So let's print the

693:42

following. Bad request. I'll add a new

693:46

line character.

693:49

Please check your

693:52

input. We'll create a total of I believe

693:55

eight cases. We'll copy what we

694:01

have. So we have

694:03

400 401

694:06

403 404. That one we're familiar with.

694:12

500

694:16

502

694:19

503

694:22

504. So for case 401, that means we're

694:26

unauthorized. Maybe our API key isn't

694:28

active

694:30

yet. So let's say

694:36

unauthorized. Invalid API key.

694:43

for

694:44

403 that means access is denied. It's

694:48

forbidden. So let's print

694:53

forbidden. Access is

694:58

denied. 404 is for something that's not

695:01

found. Not

695:05

found. City not found.

695:10

500 is for an internal server

695:13

error. Internal server error. Please try

695:18

again

695:22

later. 502 is for a bad

695:25

gateway.

695:27

Bad gateway. Invalid response from the

695:30

server.

695:38

503 is for service

695:41

unavailable. Service

695:44

unavailable. Server is

695:49

down. Then 504 is for a gateway

695:55

timeout.

695:57

Gateway time out. No response from the

696:00

server.

696:08

In case there's any unexpected error, we

696:10

can add a wild card of an

696:14

underscore with our HTTP error. Let's

696:18

give it a name as HTTP

696:22

error. And then we'll just print it. In

696:25

case there are no matching cases, let's

696:27

print the

696:29

following. HTTP

696:32

error

696:33

occurred. I'll add a new

696:36

line. Let's convert this to an

696:39

string. Add a

696:41

placeholder. And then I will print our

696:43

HTTP

696:45

error. All right, let's do a test

696:48

run. So, in case we can't find our city,

696:52

we should encounter a 404

696:54

error. Not found. City not found.

696:57

Eventually, we will display this message

696:59

within our app, but we know that it

697:02

works. What if my API key is

697:06

invalid? So, I will take my API key, set

697:10

it to be

697:11

inactive, but it might take a few

697:13

minutes to take

697:14

effect. The status code of our response

697:17

object should be

697:19

401. So, this time I'm going to look up

697:21

a city. I have an invalid API

697:25

key and I get that error message of

697:27

unauthorized invalid API

697:31

key. All right, everybody. So, I am on

697:33

day three of working on and recording

697:35

this topic. Over the course of the day,

697:38

I thought of one change that I can make.

697:40

We're going to add a few extra accept

697:42

blocks. So, we will accept access

697:45

requests access exceptions. We will

697:48

handle any connection error exceptions.

697:56

as well as any timeout

698:03

exceptions and any

698:07

redirects. Too many

698:15

redirects. So if we run into a

698:17

connection error, let's say that our

698:19

internet gets disconnected. Well, we can

698:21

print something. So let's print the

698:24

following. Let's print connection

698:28

error. I'll add a new line

698:31

character. Check your internet

698:36

connection. If we encounter a timeout,

698:40

then we will print the

698:41

following. We have a timeout error.

698:48

the request timed

698:51

out. If we have a too many redirects

698:54

error, that M should be capital, by the

699:00

way. Let's

699:02

state too many

699:08

redirects. Check the

699:12

URL. And if there's anything else we

699:15

don't anticipate, I'll give this

699:17

exception a name of as wreck

699:21

error. And then we'll just print it.

699:25

This is a last resort. I'll use an f

699:28

string request

699:31

error. I'll add a new line. I'll add a

699:35

placeholder. Then display our request

699:38

error. So I'm actually going to turn off

699:40

my internet. I'll see if I can get a

699:42

connection error

699:44

intentionally. So, my internet is

699:46

currently off. I will attempt to look up

699:49

a city, get the weather, and we get a

699:52

connection error. Check your internet

699:56

connection. All right, my internet is

699:58

connected

699:59

again. Let's perform a test

700:03

run. And we get the weather in Miami.

700:08

Now what we're going to do is if we have

700:10

an

700:11

error, we'll display the error message

700:14

within the app and not within our

700:18

console. So we're going to replace print

700:21

with a call to our display error method.

700:24

Let me zoom out a little bit. So replace

700:27

print with self dot display

700:31

error. And we're passing in a message.

700:35

So, let's replace

700:43

those. One thing I forgot to add,

700:46

although it's not necessary, I'm going

700:48

to add a colon after each initial

700:51

message. I think it'll look

700:54

better. You don't have to do this, but

700:56

I'm OCD about the appearance.

701:00

If we encounter one of these exceptions,

701:02

we'll pass along a message to our

701:04

display error method and display it

701:06

within the app. Let's take our

701:09

temperature label self. Temperature

701:14

label and set the

701:17

text to be our message that we pass

701:23

in. Let's do a test run.

701:26

Let's look up a city that doesn't exist.

701:28

Get the weather. So, we get that error

701:31

message. Not found. City not found.

701:34

While we're within this method, I'm

701:36

going to change the font size just so

701:38

that it's a little bit

701:43

smaller. So, let's take our temperature

701:45

label. Self dot temperature label. I'm

701:49

just going to copy this because I'm

701:51

lazy. I will call the set stylesheet

701:54

method.

701:56

and pass along a new property. Let's set

701:59

the font size to 30

702:03

pixels. Let's look up North

702:07

Pole. I don't think that's a

702:09

city. Oh, I guess it is.

702:15

Interesting. The North Pole is a city, I

702:17

guess. Let's look up blah blah

702:21

blah. Not found. City not found.

702:25

Let's do another test. What if our API

702:28

key is invalid? I'll just delete one of

702:30

the

702:32

digits. Let's look up Los

702:36

Angeles. Unauthorized. Invalid API

702:40

key. Let's change that back again. I

702:43

will turn off my

702:45

internet. Then look up

702:48

Miami. Connection error. Check your

702:51

internet connection. All right. So we

702:53

know that our exception handling

702:55

works. Okay. Now we're within the

702:58

display weather

702:59

method. We'll receive an object to

703:02

represent our data. We have to get the

703:05

temperature. But first I'm going to

703:07

print our data. So let me zoom in a

703:09

little

703:11

bit. Let's look up Houston. Houston,

703:16

Texas. I need the temperature. Within

703:20

our data object, we are looking for a

703:22

key of main and that is right here. Main

703:26

contains a dictionary with key value

703:28

pairs. Once we've accessed main, we have

703:31

to access temp to get the temperature.

703:34

And this temperature is in Kelvin. We'll

703:36

have to convert it to Celsius or

703:37

Fahrenheit. It's your

703:39

choice. So, we need to extract this

703:42

value. I will store it as a local

703:45

variable.

703:49

temperature let's say temperature K for

703:52

Kelvin equals take our data object

703:56

access the key of main that's right here

704:01

then we have to go one level deeper and

704:03

get the temperature the key is

704:06

temp then give me the value at the key

704:09

of temp and that should return the

704:12

current temperature so to test it let's

704:15

print it Let's print the temperature in

704:19

Kelvin. So what is the weather in

704:22

Houston, Texas? The temperature that

704:25

is 309

704:28

Kelvin. Let's convert it to Celsius and

704:32

Fahrenheit. Let's create temperature C

704:35

if you want to use Celsius. If you would

704:38

rather use Fahrenheit, you can skip this

704:39

step.

704:41

To convert from Kelvin to Celsius, we

704:43

will take our temperature in Kelvin,

704:46

subtract

704:49

273.15. Then for

704:52

Fahrenheit, let's take temperature F for

704:55

Fahrenheit equals, this is a little more

704:59

complicated. Take our temperature in

705:02

Kelvin times 9 /

705:05

5 subtract 459.67.

705:10

67. Okay. So, let's print the

705:13

temperature in

705:17

Celsius. Let's look up

705:21

Houston.

705:23

36.46°

705:25

C. Then in Fahrenheit, that would

705:31

be

705:33

97.6° F. That's pretty

705:37

hot. All right. So once we have our

705:39

temperature, let's change the

705:41

temperature label. self. Temperature

705:44

label. I'll just copy this. Then we will

705:47

set the text. I'll use an F

705:51

string. Add a placeholder. I'll use

705:54

Fahrenheit, but feel free to use

705:57

Celsius. Then I will add a degree

705:59

symbol. With Windows, make sure num lock

706:02

is on. Hold alt. Then on your numpad,

706:04

type 0176 for a degree symbol. Then F

706:08

for

706:10

Fahrenheit. Let's look up

706:13

Miami. Get the weather. And here's the

706:16

temperature.

706:18

94.964. Now, let's say I would like no

706:21

digits after the decimal. I can add a

706:23

format specifier after our temperature.

706:26

I'll add a

706:27

colon 0F to display no

706:30

decimals. Let's try that again. I will

706:34

look up Miami. Get the weather. The

706:37

current temperature in Fahrenheit is 95°

706:41

F. Now, here's one issue. Let's say we

706:45

display an air, then display the

706:46

weather. If we display an error, we're

706:49

going to be changing the font

706:50

size. So, let's look up blah blah blah.

706:54

Got the weather, city not found. Then,

706:58

let's look up Miami again. Got the

707:01

weather. And the font size is a lot

707:03

smaller. So, if we display the weather,

707:06

let's reset the font size, we can really

707:09

just copy this

707:11

line. So, within the display weather

707:13

method, let's set the font size back to

707:17

75, what it was

707:20

originally. Let's try that

707:23

again. Let's look up a city that doesn't

707:25

exist. Get the weather. City not found.

707:28

Then, we'll look up a city that does

707:30

exist, like Miami, and get the weather.

707:34

95°

707:35

F. Now, let's get a description of the

707:38

weather. We'll display that at the

707:39

bottom. In the center, we'll display a

707:42

picture or an emoji, but we'll handle

707:43

that

707:44

last. Now, we need a description of the

707:47

weather, like, is it sunny? Is it

707:49

cloudy? Is it raining? So, after we

707:52

calculate the temperature, so I'm going

707:55

to print our data

707:58

again. Let's look up Los Angeles.

708:04

So currently it's 85° F. So for the

708:07

weather

708:08

description that is found at the key of

708:11

weather. We're now within a list at

708:15

index zero within our

708:17

list. We'll look up the key of

708:19

description which states clear sky.

708:23

So we will create a local variable of

708:26

weather

708:30

description equals access our

708:35

data at the key of

708:40

weather. There's layers to this. We're

708:43

then within a

708:45

list and actually it's a list with only

708:48

one item in it.

708:50

So at the index of

708:52

zero then at the key of

708:57

description that's going to return this

708:59

description of clear

709:03

sky. So we will take our description

709:06

label self.escription label. Let me just

709:10

copy

709:11

it. This one right here.

709:17

Then we will set the

709:19

text and then pass in our weather

709:23

description. What is the weather

709:25

description of Los

709:29

Angeles? 86° F and there's a clear

709:33

sky. Okay. Now, the last thing we're

709:36

going to do is add an emoji. We'll add

709:38

it right to the center between the

709:40

temperature and the weather description.

709:42

You don't necessarily have to, but I

709:44

think it'll look cool and that's a good

709:46

enough

709:47

reason. So, let's create another method

709:50

to handle

709:51

that. We will define a method of get

709:55

weather

709:57

emoji or a picture if you would rather

709:59

use a picture. We don't need self

710:02

necessarily. We're going to need a

710:04

weather ID.

710:07

This method isn't going to rely on any

710:09

class data or instance data. We could

710:12

make it a static method. I'll add a

710:15

decorator of static

710:17

method. In summary, a static method, we

710:20

haven't covered these for a little bit.

710:22

They belong to a class but don't require

710:25

any instance specific data or any other

710:28

methods. They're used as more of a

710:30

utility tool. We're going to be passing

710:32

in a weather ID and returning an emoji.

710:38

I'm going to show you where we can find

710:39

that weather ID. I'll use a print

710:43

statement. I will print our

710:47

data. Let's look up Miami again. That's

710:50

the first thing that came to

710:54

mind. Now, at the key of weather,

710:57

there's a key of ID, and the value is a

711:00

three-digit number. I'll show you this

711:02

chart.

711:03

Depending on what this three-digit

711:05

number is, that corresponds to a certain

711:07

group of weather. So the 200 range is a

711:11

thunderstorm. 300 is a drizzle. 500 is

711:15

rain. 600 is

711:17

snow. 700 is atmosphere, like if there's

711:21

a tornado or there's a volcanic

711:25

eruption. 800 exactly is a clear sky.

711:29

Anything that's 801 or above refers to

711:31

clouds. So this ID is 803. We have

711:35

broken

711:36

clouds. Depending on what this ID is, I

711:39

would like to return a certain emoji

711:42

based on the weather. So we need this

711:45

ID. I'll delete our print statement. We

711:47

no longer need it. Let's say before our

711:50

weather description, we will create a

711:52

local variable of weather

711:54

ID

711:56

equals access our data

711:59

object. then access the key of

712:04

weather. The value at weather is a list

712:08

but this list only has one item in it.

712:11

So we need the index of operator at zero

712:15

and then we will access the key of

712:19

ID. The key is ID. So our weather ID is

712:23

going to be a number, a three-digit

712:25

number. Okay everybody, we're near the

712:28

end. So after setting the temperature,

712:30

we're going to set the emoji label

712:35

self.oji

712:37

label and call the set text

712:40

method. Within the set text method, we

712:44

will call

712:45

self.get weather emoji

712:48

method. This will return a string, an

712:51

emoji within a string. But we have to

712:54

pass in our weather ID.

712:56

It's that three-digit number. So now we

713:00

are within our get weather emoji

713:02

method. Depending on the range of that

713:05

three-digit number, we will return one

713:07

of a few emojis. We could use a match

713:10

case statement. I think it's more

713:11

complicated with the match case

713:13

statement. We'll use else if statements

713:15

for simplicity.

713:17

So if our weather

713:20

ID is greater than or equal to 200 and

713:25

our weather ID is less than or equal to

713:30

232. Now we have two conditions here

713:33

linked with the and logical

713:35

operator. There is a shortcut to this

713:38

and actually PyCharm is telling me that

713:40

there is. We can simplify these

713:43

expressions. Instead of two separate

713:45

conditions, we can combine them into

713:47

one. If 200 is less than or equal to our

713:51

weather ID and our weather ID is less

713:54

than or equal to 232, if this one

713:57

combined condition is true, then we will

714:00

return an

714:01

emoji. So to add an emoji on Windows,

714:05

you can hold down the window key and

714:07

press semicolon.

714:10

So 200 to 232, that's for a

714:14

thunderstorm. Depending on the font

714:16

style of your IDE, some of these emojis

714:18

might not display properly. You can

714:21

always just copy them from someplace

714:23

else. I think that's better. It's more

714:27

colorful. Then else

714:29

if 300 is less than or equal to our

714:34

weather

714:35

ID and our weather ID is less than or

714:39

equal to

714:41

321. This is for a partially cloudy

714:44

sky. We will

714:48

return some clouds. A partially cloudy

714:52

sky. And again I don't like that one. So

714:54

let's use this one instead.

714:59

Else if 500 is less than or equal to our

715:04

weather

715:05

ID which is less than or equal to

715:10

531 we will return

715:16

rain

715:19

eh that's

715:22

better 600 to

715:25

622 Else if 600 is less than or equal to

715:29

our weather

715:31

ID which is less than or equal to

715:37

622 we will return

715:45

snow. So 701 to 741 is mist or fog. Else

715:52

if 701 is less than or equal to our

715:56

weather

715:58

ID which is less than or equal to

716:03

741. We will return some mist or

716:09

fog. 762 specifically is for ash like

716:13

from a

716:14

volcano. So else if our weather

716:19

id is directly equal to

716:23

762 we will return let's return a

716:31

volcano 771 is for a squall that's a

716:35

violent gust of wind else if our weather

716:39

ID is directly equal to 771

716:45

one we will

716:49

return. Let's return that. A violent

716:52

gust of wind, a

716:55

squall. 781 is for a

716:58

tornado. Else if our weather ID is equal

717:02

to

717:04

781, return a tornado.

717:12

800 exactly is for a clear

717:14

sky. Else if our weather ID is equal to

717:20

800

717:23

return a sun a sun

717:27

emoji. Else if 801 is less than or equal

717:32

to our weather

717:34

ID which is less than or equal to

717:38

804. We will return some

717:49

clouds. Now, if there are no matches,

717:52

let's return an empty string to not

717:54

display

717:55

anything. Okay, let's do a test

718:00

run. Let's look up

718:03

Miami. We get scattered clouds. It's

718:06

94°.

718:08

Los

718:10

Angeles. Got the weather. We have a

718:12

clear sky and a sun. Now, there's one

718:15

fix we need to make. Let's say that I

718:18

make up a city again. Blah blah blah.

718:22

Got the weather. We should clear our

718:25

emoji label and the weather description.

718:28

But we still get that error message.

718:31

So after we display our error within the

718:34

display error method, after we set the

718:37

text of the temperature label, let's

718:39

take the emoji label self.oji

718:44

label and call the clear method to clear

718:47

it. Then we have to do this with the

718:50

description label self.escription

718:55

label and call the clear method. Now we

718:59

should be able to clear it when we get

719:02

an

719:03

error. Okay, let's look up Houston. Get

719:07

the weather. Few clouds.

719:10

98°. Let's make up a city. Pizza City.

719:15

Get the weather. Not found. City not

719:18

found. And the emoji label and the

719:20

weather description are

719:23

cleared. Okay. What if I type in

719:25

nothing? What happens? Let's get the

719:27

weather. We have a bad request. Please

719:30

check your

719:31

input. That's if we have an HTTP status

719:34

code of 400. We handled this exception.

719:37

Bad

719:38

request. All right, one last city. What

719:42

about Paris? Let's get the weather. It

719:46

is 68 degrees Fahrenheit and there's

719:48

light rain. All right, everybody. So,

719:51

that is a weather app that you can make

719:53

using Python. Add it to your portfolio

719:56

and thanks for watching.

UNLOCK MORE

Sign up free to access premium features

INTERACTIVE VIEWER

Watch the video with synced subtitles, adjustable overlay, and full playback control.

SIGN UP FREE TO UNLOCK

AI SUMMARY

Get an instant AI-generated summary of the video content, key points, and takeaways.

SIGN UP FREE TO UNLOCK

TRANSLATE

Translate the transcript to 100+ languages with one click. Download in any format.

SIGN UP FREE TO UNLOCK

MIND MAP

Visualize the transcript as an interactive mind map. Understand structure at a glance.

SIGN UP FREE TO UNLOCK

CHAT WITH TRANSCRIPT

Ask questions about the video content. Get answers powered by AI directly from the transcript.

SIGN UP FREE TO UNLOCK

GET MORE FROM YOUR TRANSCRIPTS

Sign up for free and unlock interactive viewer, AI summaries, translations, mind maps, and more. No credit card required.