Full Python Course
Full Python Course
In this video, I'm going to teach you everything you need to know to start coding
with Python. I've also included 20 different hands-on projects to help you learn. You can find the entire
list in the description of this video.
Our final project will be a weather app that fetches real-time weather data from an API. Even if you've
never coded anything in your life before, I'll walk you through the basics, the ABCs of programming. If
that sounds good to you, then I encourage you to sit back, relax, and enjoy the show.
This course doesn't cost you anything, but if you would like to help me out, you can help increase its
reach by hitting the like button, leave a random comment down below, and subscribe if you'd like to be
a fellow bro. Thank you. I appreciate it.
I don't like boring introductions, so I say we just jump right in. There's two things we'll need to
download. The first is a Python interpreter to convert our written code to machine code. We're going to
head to python.org, go to downloads, and download the latest version. We will open this executable.
If you're on Windows, you'll want to check this check box, **Add Python exe to PATH**, and we will
install now. The setup was successful. And that's all you need to do to download the Python interpreter.
The second download we'll need is an IDE, an integrated development environment. Basically, a place
where we can write code. For IDEs, there's two popular choices when writing Python code: PyCharm and
VS Code. If you already use VS Code, you can stick with that. Just be sure to download the Python
extension.
I find PyCharm more beginner friendly if you've never coded before. If you would like to use PyCharm,
go to jetbrains.com/pycharm. And we will click this green download button. There's two versions of
PyCharm, the professional version and the community version. The professional version is paid for. I
would not recommend using it only because there's plenty of free IDEs on the market.
We'll use the community edition, the free one, because I don't like to pay for things and I'm sure you
don't either. Select the correct download for your operating system. I'm running Windows. I will
download PyCharm. We will open this executable. Click next. You could select a destination folder. I'll
keep it as is. Next, I'll create a desktop shortcut, but you don't necessarily need to. Click next. Install.
And we'll just have to give it a moment.
Okay, the setup is now complete. I'll check this checkbox to run PyCharm when we close this window.
After opening PyCharm, we're going to create a new project. You can rename your Python project. I'll
keep it as is. You can select a location. Again, I won't change that. You can create a sample welcome
script, but for this tutorial, we won't. Let's select the latest Python version and create our new project.
In the menu to the left, we're going to create a new Python file. File > New > Python File. Let's name this
file **main**. But really you can name it anything and select Python file. Python files end with the `.py`
file extension. We should have our main Python file within our Python project folder.
Now we're going to print something to the console window. Within our main Python file, we're going to
write a print statement. So type `print` add a set of parentheses. Between the set of parentheses, we
will add a set of double quotes to print something or single quotes. Either one. My own preference is
double quotes.
Normally in a programming tutorial, the instructor would tell you to print something such as "hello
world," but we like to be different here. Instead, think of your favorite food. In this case, I like pizza. I
will print:
```python
```
To run our Python program, we will click the screen arrow to run our main Python file. We should have a
console window that displays our output:
```
I like pizza
```
```python
```
```python
```
Comments are used as notes for yourself or for other people reading this code. If I were to run this code
again, this comment is not displayed to the output. We still have:
```
I like pizza
```
All right, everybody. So, that is your very first Python program. And in the next topic, we'll discuss
variables.
---
All right, everybody. We are moving on to variables. A variable is a container for a value. There's four
different data types. We'll discuss strings, integers, floats, and booleans. Yes, I know that's a silly name.
A variable behaves as if it was the value it contains. Each variable should have a unique name. Let's say
we have a variable of `first_name`. To assign a variable, you use the assignment operator of equals:
```python
first_name = "Bro"
```
For text, a string is a series of text. This can be double quotes or single quotes. My own preference is
double quotes. Why don't you type in your first name? This variable of `first_name` will behave as if it
was this value, this series of characters.
print(first_name)
```
So place it within a print statement without quotes. That will print your first name. Now, you don't want
this within quotes because then you're literally printing the word `first_name`.
You could use your variable along with some text by using what is called an **F-string**. That's the
easiest way to display a variable. So, you type `f` then a set of quotes. The `f` means format. So, let's say
the word hello. Then we will add our variable. We will insert our variable into this text when using an F-
string. To do that, you need a set of curly braces. Then insert your variable. So the result is:
```python
print(f"Hello, {first_name}")
```
which outputs:
```
Hello, Bro
```
```python
food = "pizza"
```
Let's print the following. You like add a placeholder. Again, I'm using an F-string:
```python
```
Output:
```
```
Let's create an email. Use your own email or make up one. Let's say:
```python
email = "[email protected]"
```
Output:
```
```
So these are strings. I'm going to add a comment that these are strings:
```python
```
A string is a series of characters. They can include numbers but we treat them as characters.
Now we have integers. An integer is a whole number. An example of this could be somebody's age. How
old are they? According to my YouTube statistics, many of you are between the ages of 18 through 24.
Let's say that I'm 25:
```python
age = 25
```
Your integer should not be within quotes because it would be a string. Then technically if I would like to
work with this variable again I'll use an F-string:
```python
```
Output:
```
```
Another example of an integer could be a quantity. You are buying a certain amount of something.
Maybe I am buying three items. I wouldn't have half an item. This would be a float technically rather
than an integer. We are buying three of something. So let's print the following:
```python
quantity = 3
```
Output:
```
```
Another example of an integer could be an amount of people. Let's say `num_of_students` like a
classroom. There are 30 students in our class:
```python
num_of_students = 30
```
Output:
```
```
Those are integers. They're whole numbers. And again, make sure they're not within quotes because
then technically they would be a string. Integers we can use in arithmetic expressions. If they were
strings, we couldn't.
Then we have floats. Float means floating-point number. A float is a number, but it contains a decimal
portion. An example would be a price. What is the price of something? $10.99:
```python
price = 10.99
```
Output:
```
```
Let's precede our placeholder with a unit of currency. I'll pick American dollars, but feel free to pick
something else.
```python
gpa = 3.2
```
Output:
```
```
What about a distance? A distance can contain a decimal portion. 5.5 kilometers maybe:
```python
distance = 5.5
```
Output:
```
```
Or you could add `mi` for miles, but I'll stick with kilometers.
Okay. Then we have booleans. A boolean is either `True` or `False`. Let's say we're a student:
```python
is_student = True
```
If we are a student, we could say that this is `True`. `True` starts with a capital T. If we weren't a student,
let's say we graduate, we could say that this is `False`. Again, the first letter is capital.
```python
```
Output:
```
```
With boolean values, we really don't output them directly. You're more likely to see them used
internally within a program, such as when working with if statements. This is a topic we'll discuss in the
future, so don't worry.
```python
if is_student:
else:
```
```
```
```
Is something for sale like a car or a product of some sort? Let's say that is `True`:
```python
for_sale = True
if for_sale:
else:
```
```
```
```
One more example. Let's say we have a boolean variable of `is_online`. Is somebody online? I will set
that to `True`:
```python
is_online = True
if is_online:
else:
```
```
```
```
```
All right everybody, so those are variables. A variable is a reusable container for a value. There's four
basic data types for beginners: a string which is a series of text, integers which are whole numbers,
floats which are numbers but they contain a decimal portion, and booleans which are either `True` or
`False`. They're binary.
Your assignment in the comment section is to post four variables. Post a string, an integer, a float, and a
boolean. Try and think of a unique example if you can.
---
All right everybody, so we are moving on to type casting. Type casting is the process of converting a
variable from one data type to another. We have various functions to convert a value or variable to a
string, an integer, a float, or a boolean.
Let's create some variables. We will create a name variable. Type in your full name, an age, make up
some age, a GPA for grade point average, let's say 3.2, and a boolean of `is_student`. Are we currently a
student? Let's say that's `True`.
Now, you actually could get the data type of a variable or a value by using the `type` function. Then pass
in a value or variable. However, when I run this, there's no output. So, I need a print statement. We will
print what is returned by the `type` function.
```python
print(type(name))
```
So our `name` variable is a string `str`. Our `age` variable is an integer `int`. `gpa` is a float. `is_student` is
a boolean.
Using these type cast functions we can convert from one data type to another. Here's how.
Let's start with something simple. Let's convert our GPA to an integer. Currently, it's a float. I will
reassign `gpa`:
```python
gpa = int(gpa)
print(gpa)
```
If we type cast 3.2 to a whole integer, what would the result be? A whole integer of three. We truncate
the decimal portion.
Let's convert our age to a floating-point number. We will reassign our variable of age:
```python
age = float(age)
print(age)
```
Now we'll cover strings. Let's type cast our age to be a string:
```python
age = str(age)
print(type(age))
```
So the result is still going to appear the same `25`. However, it's a string not an integer. And to prove
that I will enclose my age variable with the `type` function. The type of variable `age` is a string.
It would be the same as if we're taking this number and enclosing it within quotes. So this would make a
difference because let's say that I add one to age:
```python
age += 1
```
```
However, if I were to add a string of one to the end, we would be using string concatenation. So let's say
it's my birthday and I add `"1"` to `"25"`:
```python
age += "1"
print(age)
```
```
251
```
So strings and numbers behave differently. With numbers, we can use them within arithmetic
expressions. Strings, not so much.
```python
name = bool(name)
print(name)
```
This has an interesting result. So I'm going to print `name`. Booleans are either `True` or `False`. If I type
cast my string of text into a boolean that gives me `True`.
Now it really doesn't matter what I write here. If I were to change my name to a single character such as
`"B"`, this would still be `True`.
If our string variable was empty, there were no characters within it, that would actually give us `False`.
We could use this to check to see if somebody enters in their name or not. If somebody types in their
name, then we type cast it to a boolean. If somebody skips entering in their name, that would return
`False`. We could reprompt the user to enter in their name again.
All right, everybody. So, that is type casting. It is the process of converting a variable from one data type
to another. This is especially useful with handling user input because user input is always a string. There
may be at times where we want to convert it to an integer, a float, or a boolean.
---
All right everybody, in this topic I'm going to show you how we can accept user input in Python. We use
the `input` function. It's a function that prompts the user to enter in data and it returns the entered data
as a string.
Here's an example. To accept user input, we will call the `input` function. When I run this program, we
need to enter in data to our console window like so, then hit enter.
However, we need a prompt. We need to tell the user what we want them to type in. So, let's ask a
question. Our prompt will be within quotes. Let's say:
```python
```
```
What is your name?
```
I can type in something. Why don't you go ahead and type in your full name, then hit enter.
Now, with this input, we're not quite doing anything with it. The `input` function is going to return some
data as a string. We can assign it to a variable if we would like.
```python
```
Then once we have our name, let's print a message. I'll use an F-string:
```python
print(f"Hello, {name}")
```
```
Hello, Spongebob
```
This time we will ask a user how old they are. Let's assign a variable of `age` equals accept some user
input. We need a prompt within quotes:
```python
age = input("How old are you? ")
```
Once we have our age variable, let's print. I'll use an F-string:
```python
```
What is your name? Type in your name. How old are you? Let's say that I'm 25.
```
Hello, Bro
```
All right. So, let's say that it's our birthday. Before we print our age variable, let's say happy birthday.
Since I'm not inserting any variables within this print statement, this doesn't need to be an F-string.
You'll want to use an F-string if you want to insert variables.
Before we display the user's age, let's take the user's age and increase it by one. We could say:
```python
age = age + 1
```
But there's one problem with this. Type in a name. How old are you? And we have a problem. We have a
type error:
```
```
When we accept user input, we store that input as a string. Before we increment our age by one, we'll
need to convert it to an integer. We can't normally use strings within arithmetic expressions. But we can
do that with integers and floats, though.
After we accept some user input for our age variable, we could take our age variable and type cast it as
an integer, which we talked about in the previous lesson. So let's say:
```python
age = int(age)
age = age + 1
```
```
Hello, Bro
Happy birthday!
```
So strings we can't normally use with arithmetic expressions. We would have to type cast it to an integer
or a float. However, we could condense some of these steps. We're taking up an extra line to type cast
our age as an integer.
What we could do instead is that when we accept our user input, we can enclose the input function
within a type cast to `int`. And that would work the same:
```python
```
Type in your name, type in an age, and this works the same. And it takes fewer lines of code and is more
readable.
I would say when we accept user input, it returns that input as a string data type. Then we just have to
type cast it to another data type if we need to. And in this case for age, we do.
---
Now, we'll go over a couple exercises because it's important to practice what you've learned.
In this first exercise, we're going to calculate the area of a rectangle. We need to prompt the user to
enter in a length and the width of a rectangle.
So we will create a variable of `length`. We will accept some user input using the `input` function. What
is our prompt? Let's say:
```python
```
Let's do this with width. I'll just copy and paste what we have:
```python
```
So we have the length and the width. To get the area of a rectangle, we have to multiply the length by
the width. So let's say:
```python
```
That is the area. I'm going to print our area because I need to test something:
```python
print(area)
```
```
```
When we accept user input, it returns a value of the string data type. We can't use those strings in
arithmetic expressions. We're multiplying the length times the width. We would need to type cast them
as an integer or a float.
Since we're working with basic geometry such as calculating the area, let's do float. So let's type cast our
user input as a float for both length and...
```python
```
Now, let's create an if statement to check which operator the user entered. We'll perform the
corresponding arithmetic operation based on the operator.
```python
if operator == "+":
if num_two != 0:
else:
else:
```
```python
```
This way, the program will perform addition, subtraction, multiplication, or division based on the user's
input, and handle division by zero and invalid operators gracefully.
A float. So, enclose your input functions with a type cast to `float`. Now we should be able to add those
two numbers together. So let's add 10 and 11, and we get 21.0.
Depending on the operator that the user selects, we'll use some if statements to determine that. We
will check if our `operator` variable is equal to a character of plus. For now, I'll write `pass` as a
placeholder. We'll get back to this later.
Else if our operator is equal to minus, we will use subtraction. For now, I'll write `pass`.
Else if our operator is equal to a forward slash for division, we will divide.
```python
result = num1 + num2
```
```python
```
```python
```
```python
```
```python
print(result)
```
Let's test multiplication. Multiply 3.14 times 3.14, which gives us 9.8596.
Then division. Let's divide 69 by 13. And that gives us a really long number.
So you could round a number if you would like. We would enclose our result within the `round` function.
We'll just update each of these print statements. This will round to the nearest whole integer.
Let's say that we would like three digits after the decimal. Within the `round` function, we could add `,
3` for three decimal places.
Enter operator. Let's use division. Divide 420 by 69. So that gives me 6.087.
So, we can round to a given digit after a decimal. In this case, three places.
What if somebody types in an operator that doesn't exist, like the word pizza? Then I will divide two
numbers.
Well, let's add an else statement. If somebody selects some input that is invalid, let's let them know. I'll
use an f-string:
```python
```
```
```
Let's say is not a valid operator instead. That makes more sense.
```
```
All right everybody, so that is a very simple Python calculator program you can make as a beginner.
---
Hey there, it's me again. In today's topic, we're going to create a weight converter program in Python.
This is an exercise that will follow up the lesson on if statements.
We'll convert pounds to kilogram or kilogram to pounds. The user is going to decide.
We will begin by creating a `weight` variable. We will assign some user input:
```python
```
```python
```
We want the user to type in either `K` for kilogram or `L` for pounds. These are capital letters, by the
way.
Using an if statement, let's first check to see if our unit is equal to a capital `K`. That means the current
weight is in kilogram. We need to convert that weight to pounds:
```python
if unit == "K":
unit = "lbs"
```
```python
unit = "kgs"
```
Else the user did not type in something that was valid:
```python
else:
```
At the end of our program, we will print the new weight. I'll use an f-string:
```python
```
Now, we need a unit of measurement. This is what I'm thinking we'll do within our if and else if
statements. Let's reassign our unit. We're reassigning `unit` to be `lbs` for pounds or `kgs` for kilogram in
our results. This way, we will display our new unit.
```
```
```
```
```
```
So, we're still displaying our output. We would want to avoid that if somebody doesn't type in a valid
unit.
So, let's cut this line and then paste it within the if and elif statements. When we exit the else
statement, we're not printing the output.
So, let's make sure that this works.
```
```
All right, everybody. Well, that is a weight converter program in Python. I thought this would be a
helpful exercise now that we have finished the section on if statements. And yeah, that is a weight
converter program in Python.
---
Hey everybody. In this topic, we're going to create a temperature conversion program as an exercise.
```python
```
Then we will ask for the temperature. I'll store the temperature in a variable named `temp` meaning
temperature:
```python
```
If `unit` is equal to `C`, I'll fill this in momentarily. I'm just going to write `pass` as a placeholder.
```python
```
```
```
```python
if unit == "C":
```
```
```
All right, so this section is working.
Else, if our unit is currently in Fahrenheit, we'll convert to Celsius. That formula is:
```python
```
```
```
---
All right people, we're talking about logical operators today. Logical operators allow us to evaluate
multiple conditions. We can link them together. There's three we'll discuss: `or`, `and`, and `not`.
We'll begin with `or`. With `or`, we can check more than one condition. If at least one of those
conditions is true, then the entire statement is true.
Here's an example.
Let's say we have an outdoor event. I will create two variables. One `temp`, meaning temperature. Let's
say that this is in Celsius, 25°C. Pick Fahrenheit if you would like.
And I will create a boolean variable of `is_raining`. I will set that to be `False`. It is currently not raining.
If the temperature is too hot, too cold, or it's raining, then I will cancel this outdoor event.
```python
else:
```
The temperature is reasonable and `is_raining` is `False`. So we print the else clause:
```
```
```
```
```
```
This condition was true. Therefore, we execute the if statement.
```
```
So with the `or` logical operator, at least one of these conditions needs to be true. If one of these
conditions is true, you could consider the entire statement true.
---
Now let's cover `and`. With `and`, we can link two conditions together. Both conditions must be true in
order for that entire statement to be true.
Again, let's say we have `temp` short for temperature and we have a boolean variable of `is_sunny`. I
will set that to be `True`.
We will check if our `temp` is greater than or equal to 28° **and** `is_sunny` is true.
```python
```
Currently, the temperature is 25°C and it's sunny. This condition was false, but this one is true.
With the `and` logical operator, both conditions must be true in order for us to execute this block of
code.
If our temperature was 30°, well, then both conditions are true:
```
It is hot outside
```
```python
```
Let's set the temperature to be 5°. It is cold outside and it is sunny. Both these conditions are true.
```python
```
```
```
---
Now, we have the `not` logical operator. It inverts the condition. We are checking to see if something is
either not false or not true.
```python
```
Basically, `not` does the opposite of what you're looking for. We are checking if `not is_sunny`. If
`is_sunny` is false, then this condition is true.
```
It is hot outside
It is cloudy
```
```
```
```
```
So `not` inverts the condition. If it's true, it's now false. If it's false, it's now true.
All right, everybody. So those are logical operators. They allow us to evaluate multiple conditions.
---
A conditional expression is a one-line shortcut for using an if-else statement. If you're familiar with other
programming languages, this is also known as the ternary operator. It behaves similarly.
Using conditional expressions, we can print or assign one of two values based on a condition.
```
X if condition else Y
```
We will create a variable for number just `num`. Let's say our number is five.
I'm going to print. Then within our print statement, I will write a conditional expression following this
formula.
Let's check to see if our number is positive:
```python
num = 5
```
If our number was `-5`, well, this condition would be false. We would instead print `negative`.
```python
num = 6
print(result)
```
Result: `even`.
```python
a=6
b=7
```
```python
```
Between `a` and `b`, which is the maximum number? That would be `b` of seven.
```python
```
```python
age = 25
print(status)
```
Our age is 25. That's greater than or equal to 18, so we will print `adult`.
If our age was 13, then we are a child. We will instead return `child`.
Let's work with the temperature.
```python
temperature = 30
```
```python
user_role = "admin"
print(access_level)
```
Our user role is an admin. Let's print our access level and we have `full access`.
All right, everybody. Those are conditional expressions. They're a one-line shortcut for the if-else
statement. It's similar to the ternary operator in other programming languages.
Using conditional expressions, we can print or assign one of two values based on a condition. You follow
the formula of return X if our condition is true, else return Y if it's false.
And well everybody, those are a few examples of conditional expressions in Python.
---
Hey everybody, in this topic I'm going to cover a few useful string methods that you may be interested
in. Then at the end of this video, we will work on an exercise where we will validate some user input.
```python
```
The first method I'll show you — well technically this is a function — the `len` function will give us the
length of a string. How many characters is it?
We will find the length of our variable `name` after the user types in some input. This function returns
an integer. I'll store that result within a variable:
```python
result = len(name)
print(result)
```
The length of this string in my example is eight characters. That does include spaces too. 1 2 3 4 5 6 7 8.
If you ever need the length of a string, there is the `len` function.
Let's move on.
If we were to type our variable `name` followed by a dot, we have access to a whole bunch of different
methods.
We have the `find` method. The `find` method will return the first occurrence of a given character, the
position.
```python
print(result)
```
I will type in my full name. The first occurrence of a space, that's what we set, is at position three.
When working with indexes, we always begin with zero. This first character would have an index of zero,
then 1 2 3. That's why the `find` method returned three instead of four.
```python
result = name.find("B")
print(result)
```
If you need the last occurrence, there is a different method, which is `rfind`. `r` meaning reverse.
```python
result = name.rfind("O")
print(result)
```
```python
result = name.rfind("q")
print(result)
```
Python could not find any lowercase `q`s. The `rfind` method will return `-1` if there are no results.
We can capitalize the first letter in a string by using the `capitalize` function:
```python
name = name.capitalize()
print(name)
```
This method will return a string. I will reassign that to `name`. Then we will print our name capitalized.
I'll be sure to type in my name, all lowercase.
Since this is all one string, only the first letter is capitalized, even though I'm including a first and last
name.
The `upper` method will take all of the characters in a string, then make them all uppercase:
```python
name = name.upper()
print(name)
```
Enter your full name. All of the letters are now uppercase.
```python
name = name.lower()
print(name)
```
Now the `isdigit` method will return either `True` or `False` if a string contains only digits. The result is a
boolean, `True` or `False`.
I'll store that within a variable named `result`, then print `result`:
```python
result = name.isdigit()
print(result)
```
So if I were to type in my full name, `isdigit` returns `False`. There are not only digits within that string.
If my string was some combination of alphabetical characters and numbers, this method will still return
`False`. It only returns `True` if my string only contains digits.
```python
result = name.isalpha()
print(result)
```
The `isalpha` method will return a boolean `True` or `False` depending if a string contains only
alphabetical characters.
So, the reason that this came up `False` is because my full name contains a space, which is not an
alphabetical character.
If I typed in my full name excluding any spaces, this would now be `True`.
`isalpha` would also return `False` if my name contained any sort of digits.
```python
```
Let's count how many dashes are going to be in somebody's phone number:
```python
result = phone_number.count("-")
print(result)
```
So, place a character within the `count` method. This method will return an integer.
Honestly, the `replace` method is probably one of the most useful methods of strings.
We can replace any occurrence of one character with another.
```python
print(phone_number)
```
So, here's my new phone number, but we've replaced all of the dashes with spaces.
Even better yet, we could eliminate all the dashes completely by replacing the dashes or another
character with an empty string:
```python
print(phone_number)
```
```python
phone_number = "1-234-567-8901"
print(phone_number)
# If you would like a comprehensive list of all of the string methods available to you,
help(str)
# Rules:
else:
print(f"Welcome {username}")
credit_number = "1234-5678-9012-3456"
# Access first character (index 0)
print(credit_number[0]) # Output: 1
print(credit_number[1]) # Output: 2
print(credit_number[2]) # Output: 3
print(credit_number[3]) # Output: 4
print(credit_number[-1]) # Output: 6
print(credit_number[-2]) # Output: 5
print(credit_number[-3]) # Output: 4
# Negative indexing: fourth last character
print(credit_number[-4]) # Output: 3
last_digits = credit_number[-4:]
print(f"xxxx-xxxx-xxxx-{last_digits}")
credit_number = credit_number[::-1]
print(credit_number)
price1 = 3.14159
price2 = 987.65
price3 = 12.34
print(f"Price 1 is ${price1:.2f}")
print(f"Price 2 is ${price2:.2f}")
print(f"Price 3 is ${price3:.2f}")
print(f"Price 1 is ${price1:.1f}")
print(f"Price 2 is ${price2:.1f}")
print(f"Price 3 is ${price3:.1f}")
# Three decimal places
print(f"Price 1 is ${price1:.3f}")
# Allocate 10 spaces
print(f"Price 1 is ${price1:10.2f}")
print(f"Price 2 is ${price2:10.2f}")
print(f"Price 3 is ${price3:10.2f}")
print(f"Price 1 is ${price1:010.2f}")
print(f"Price 2 is ${price2:010.2f}")
print(f"Price 3 is ${price3:010.2f}")
# Left justify
print(f"Price 1 is ${price1:<10.2f}")
print(f"Price 2 is ${price2:<10.2f}")
print(f"Price 3 is ${price3:<10.2f}")
print(f"Price 1 is ${price1:>10.2f}")
print(f"Price 2 is ${price2:>10.2f}")
print(f"Price 3 is ${price3:>10.2f}")
# Center align
print(f"Price 1 is ${price1:^10.2f}")
print(f"Price 2 is ${price2:^10.2f}")
print(f"Price 3 is ${price3:^10.2f}")
print(f"Price 1 is ${price1:+10.2f}")
print(f"Price 2 is ${price2:+10.2f}")
print(f"Price 3 is ${price3:+10.2f}")
# Thousand separator
price1 = 3000
price2 = 9870
price3 = 1200
print(f"Price 1 is ${price1:,}")
print(f"Price 2 is ${price2:,}")
print(f"Price 3 is ${price3:,}")
price1 = 3009.0
price2 = 9870.0
price3 = 1200.0
print(f"Price 1 is {price1:+,.2f}")
print(f"Price 2 is {price2:+,.2f}")
print(f"Price 3 is {price3:+,.2f}")
# Example 3: Prompt user for food they like until they press Q to quit
print("Bye")
# Alternative version allowing zero values using while True and break
while True:
if principal < 0:
else:
break
while True:
if rate < 0:
else:
break
while True:
if time < 0:
else:
break
```
Hey everybody, in this topic I need to explain **for loops**. A for loop will execute a block of code a
fixed number of times. You can iterate over a range, a string, a sequence, anything that is considered
iterable. I'll have more examples for you in future topics.
There is a lot of overlap where you could use either a while loop or a for loop, but for loops tend to be
better in situations where you have to do something only a fixed number of times.
---
```python
print(x)
```
## Counting Backwards
```python
print(x)
```
- After the loop, print "Happy New Year" outside the loop.
---
## Counting by Steps
Count by twos:
```python
print(x)
```
Output: `1 3 5 7 9`
Count by threes:
```python
```
Output: `1 4 7 10`
---
```python
credit_card = "1234-5678-9012-3456"
for x in credit_card:
print(x)
```
---
```python
if x == 13:
continue # Skip 13
print(x)
```
if x == 13:
print(x)
```
---
```python
import time
seconds = x % 60
minutes = (x // 60) % 60
hours = x // 3600
print(f"{hours:02}:{minutes:02}:{seconds:02}")
time.sleep(1)
print("Times up!")
```
- Uses integer division `//` and modulus `%` to calculate hours, minutes, and seconds.
---
# Nested Loops
```python
```
Output:
```
123456789
123456789
123456789
```
---
```python
for _ in range(columns):
print(symbol, end="")
print()
```
---
```python
```
---
```python
print(fruits[0]) # apple
print(fruits[1]) # orange
print(fruits[2]) # banana
print(fruits[3]) # coconut
```
- Indexing starts at 0.
- Access slices:
```python
```
---
```python
print(fruit)
```
---
fruits.append("pineapple")
```
```python
fruits.remove("apple")
```
```python
fruits.insert(0, "pineapple")
```
```python
fruits.sort()
```
```python
fruits.reverse()
```
---
```python
print(len(fruits)) # e.g., 4
```
```python
```
```python
fruits[0] = "pineapple"
```
---
# Summary
- Lists have many useful methods like `append`, `remove`, `sort`, and `reverse`.
---
Feel free to ask if you'd like me to explain any of these topics in more detail!
```python
fruits.reverse()
# To reverse alphabetically:
fruits.sort()
fruits.reverse()
fruits.clear()
print(fruits) # Output: []
index_apple = fruits.index("apple")
index_coconut = fruits.index("coconut")
count_banana = fruits.count("banana")
count_pineapple = fruits.count("pineapple")
print(f"Pineapples found: {count_pineapple}") # Output: 0
print(dir(fruits_set))
# Length of set
print(len(fruits_set)) # Output: 4
# Check membership
fruits_set.add("pineapple")
print(fruits_set)
fruits_set.remove("apple")
print(fruits_set)
popped = fruits_set.pop()
print(fruits_set)
# Clear set
fruits_set.clear()
fruits_set.add("coconut")
print(fruits_tuple)
print(dir(fruits_tuple))
# Length of tuple
print(len(fruits_tuple)) # Output: 5
# Membership check
# Index of element
index_apple = fruits_tuple.index("apple")
# Count occurrences
count_coconut = fruits_tuple.count("coconut")
print(fruit)
# Summary:
foods = []
prices = []
total = 0.0
while True:
if food.lower() == "q":
break
else:
foods.append(food)
prices.append(price)
print()
total += price
# Accessing elements
print(groceries[0][0]) # 'apple'
print(groceries[1][2]) # 'potatoes'
print()
numpad = (
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#")
print()
# Quiz Game Example
questions = (
options = (
guesses = []
score = 0
question_num = 0
print("\n--------------------")
print(question)
print(option)
guesses.append(guess)
if guess == answers[question_num]:
score += 1
print("Correct!")
else:
question_num += 1
```
```python
# Example runs:
# User inputs: A B C D A
# Output:
#CDAB
#ABCDA
# Your score is 0%
# User inputs all correct:
# Output:
#CDAB
#CDAB
# Output:
#CDAB
#CCCCC
capitals = {
"China": "Beijing",
"Russia": "Moscow"
print(capitals.get("USA")) # Washington DC
print(capitals.get("Japan")) # None
print("Capital exists")
else:
if capitals.get("Russia"):
else:
capitals.update({"Germany": "Berlin"})
print(capitals)
capitals.update({"USA": "Detroit"})
print(capitals)
# Remove China
capitals.pop("China")
print(capitals)
capitals.popitem()
print(capitals)
# Clear dictionary
capitals.clear()
print(capitals) # {}
keys = capitals.keys()
print(keys) # dict_keys([...])
print(key)
values = capitals.values()
print(values) # dict_values([...])
print(value)
items = capitals.items()
print(items) # dict_items([...])
print(f"{key}: {value}")
menu = {
"pizza": 5.00,
"nachos": 3.50,
"popcorn": 4.00,
"fries": 2.50,
"chips": 1.50,
"soda": 2.00,
"lemonade": 2.00
cart = []
total = 0.0
print("Menu:")
print("--------------------")
print(f"{item:15} : ${price:.2f}")
print("--------------------")
while True:
if food == "q":
break
cart.append(food)
else:
print("\nYour cart:")
print()
total += menu.get(food)
print(f"\nTotal is ${total:.2f}")
dice_roll = random.randint(1, 6)
low = 1
high = 100
rand_float = random.random()
choice = random.choice(options)
# Shuffle a list
cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
random.shuffle(cards)
lowest_num = 1
highest_num = 100
guesses = 0
is_running = True
while is_running:
if guess.isdigit():
guess = int(guess)
guesses += 1
continue
if guess == answer:
is_running = False
else:
else:
```
```python
z=x*y
return z
if y == 0:
z=x/y
return z
# Example usage:
z_add = add(1, 2)
z_subtract = subtract(5, 3)
z_multiply = multiply(4, 6)
z_divide = divide(10, 2)
z_divide_zero = divide(10, 0)
```
```python
# Let's invoke our add function. Pass in two numbers, one and two.
z = add(1, 2)
print(z) # After adding these two numbers together, the result is three.
z = subtract(1, 2)
# Multiply.
z = multiply(1, 2)
# Then divide.
z = divide(1, 2)
print(z) # 1 / 2 is 0.5.
# Just imagine that after we finish this function, this function becomes whatever is returned:
first = first.capitalize()
last = last.capitalize()
# Return the user's first name plus their last name with a space in between.
# Using the return statement, you can return some data back to the place in which you call a function.
# To call a function, you type the function's name, add a set of parentheses.
# You can send a function some data, which are known as arguments,
# You also do have the option of returning some data back to the place in which you invoke a function.
# We'll be using functions a lot in the future, but we will get more practice with them.
# ------------------------------------------------------------
# Default Arguments
# Example usage:
print(f"My total is ${net_price(500, 0.1, 0):.2f}") # 10% discount, no tax, output: 450.00
# Default arguments make functions more flexible and reduce the number of arguments you have to
pass in.
# ------------------------------------------------------------
import time
print(x)
time.sleep(1)
print("Done")
count(end=10)
count(15, 30)
# ------------------------------------------------------------
# Keyword Arguments
# Positional arguments:
# ------------------------------------------------------------
print(x, end=" ") # end is a keyword argument, prints numbers separated by space
print("1", "2", "3", "4", "5", sep="-") # sep is a keyword argument, separates with dash
# ------------------------------------------------------------
return f"{country_code}-{area_code}-{first}-{last}"
# ------------------------------------------------------------
# Arbitrary Arguments
# Example: Add function with fixed parameters
return a + b
def add(*args):
total = 0
total += num
return total
print(add(10)) # Output: 10
def display_name(*args):
print()
display_name("Spongebob", "Squarepants")
# ------------------------------------------------------------
def print_address(**kwargs):
# Print type to show it's a dictionary
print(value)
print(key)
print(f"{key}: {value}")
print_address(
city="Detroit",
state="Michigan",
zip="54321",
apartment=100
# ------------------------------------------------------------
print()
# Print street and apartment if present
if 'apartment' in kwargs:
else:
print(kwargs.get('street'))
shipping_label(
apartment=100,
city="Detroit",
state="Michigan",
zip="54321"
# Note: Reversing *args and **kwargs in parameters will cause a syntax error.
```
```python
print()
if 'apartment' in kwargs:
else:
print(kwargs.get('street'))
# Example usage:
shipping_label(
PO_box=10001,
city="Detroit",
state="Michigan",
zip="54321"
```
---
# Iterables in Python
An **iterable** is any object or collection that can return its elements one at a time, allowing it to be
looped over.
```python
numbers = [1, 2, 3, 4, 5]
```
```python
```
```python
print(number, end="-")
```
---
```python
numbers = (1, 2, 3, 4, 5)
print(number)
```
print(fruit)
```
```python
```
```python
print(f"{key} = {value}")
```
---
```python
word = "apple"
if letter in word:
print(f"There is a {letter}")
else:
```
```python
```
```python
if student in students:
print(f"{student} is a student")
else:
```
Example with dictionary keys:
```python
if student in grades:
else:
```
```python
email = "[email protected]"
print("Valid email")
else:
print("Invalid email")
```
---
```python
# Traditional loop
doubles = []
print(doubles)
```
```python
print(doubles)
```
Examples:
```python
# Triples
# Squares
# Uppercase fruits
# Even numbers
# Odd numbers
# Passing grades
```
---
```python
def day_of_week(day):
match day:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
case _:
print(day_of_week(1)) # Sunday
print(day_of_week(7)) # Saturday
```
```python
def is_weekend(day):
match day:
return True
return False
case _:
print(is_weekend("Sunday")) # True
print(is_weekend("Monday")) # False
```
---
# Summary
- Use `*args` and `**kwargs` for arbitrary arguments in functions.
- Membership operators `in` and `not in` test for presence in sequences.
```
In this video, we will call the function `is_weekend` and pass in a day of the week such as Monday. So, is
Sunday the weekend? That is true. Monday? That is false. Saturday? That is true. And we do have a
wildcard case. If there are no matches, is pizza a day of the weekend? That is false.
There is a way we can modify this match case, too. We tend to be repeating ourselves a lot. The days
Monday through Friday all return false. We're going to use the `or` logical operator, which is
represented with a vertical bar. If the case is Saturday or Sunday, return true. If the case is Monday or
Tuesday, or Wednesday, or Thursday, or Friday, then we will return false. We can keep our wildcard
case.
So, is Saturday part of the weekend? That is true. Is Monday? False. Sunday? True. Friday? False. And
pizza? We have our wildcard case that gives us false.
All right everybody, so those are match case statements. They're similar to switches in other
programming languages. They're an alternative to using many else-if statements. We execute some
code if a value matches a case. The benefit is that the code is cleaner and the syntax is more readable.
And well everybody, those are match case statements in Python.
---
Hello friends, it's me again. Today I'm going to explain modules. A module is just a Python file containing
code you want to include in your program. You use the `import` keyword to include a module. You can
use built-in modules or create your own. Sometimes it's useful to break up a large program into reusable
separate files.
For a list of all the modules found within the standard Python library, you can use the `help` function,
pass in the word `"modules"`, and then we would need to print this. Here are many of the different
modules available to you. A few you may recognize would be `math`, `string`, `time`. One of my favorite
names of a module is the `pickle` module. Unfortunately, it doesn't have anything to do with pickles. It's
used for serialization.
To list all of the different variables and functions found within a module, you can place that name of the
module within the `help` function. For example, with the `math` module, here are a few different
variables we would have access to and a few different functions.
```python
import math
```
I now have access to everything found within the `math` module, including those variables and
functions. To access those variables and functions, I would normally type the name of the module dot
the name of the variable or function such as `pi`. Then let's print this:
```python
print(math.pi)
```
```python
import math as M
```
You can give your module a nickname, an alias, whatever you think of such as `M`. `M` short for math.
We would no longer refer to this module as `math`. We would refer to it as our alias `M`. Using an alias
would reduce some of the typing you have to use if you have a very long module name.
```python
from math import pi
```
You would no longer need the module name. `pi` would be included within our namespace. However, I
tend to not use `from import` as much just because it's possible there could be name conflicts.
```python
print(e)
```
What if I was to create a program where we have four variables named `a`, `b`, `c`, `d`:
```python
a=1
b=2
c=3
d=4
```
Then I'm going to print `e` from the math module to the power of `a`:
```python
print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
```
Here are the results.
```python
e=5
print(e ** e)
```
We have imported `e` from the math module. When we have declared all of these variables, technically
what we've done is we have created another version of `e`. We will end up using the second version
rather than the version that we have imported from the math module. All my results are now different
and it's possible you may not realize it.
I like to be more explicit. I'm going to import `math`. If I'm using a variable or function from a module, I
much prefer to prefix that variable name or function with the name of the module in which it's from:
```python
import math
print(math.e ** a)
print(math.e ** b)
print(math.e ** c)
print(math.e ** d)
print(math.e ** e)
```
Now, to create a module, what we're going to do is right click on our project folder, go to new Python
file, think of a module name, maybe `example`, then click Python file. We now have two tabs: `main`
and `example`.
Declare whatever you would like within this module. Let's create our own variable `pi`:
```python
pi = 3.14159
```
Then a few functions. Let's create a function to square an argument that's passed in:
```python
def square(x):
return x ** 2
```
```python
def cube(x):
return x ** 3
```
```python
def circumference(radius):
return 2 * pi * radius
```
```python
def area(radius):
return pi * radius ** 2
```
All right, here is our example module. Within our main Python program, let's import the name of our
module which we named `example`:
```python
import example
```
We now have access to everything within this module. I'm going to declare a variable `result` and set it
to the name of my module's `pi`:
```python
result = example.pi
print(result)
```
```python
result = example.square(3)
print(result) # 9
```
```python
result = example.cube(3)
print(result) # 27
```
Circumference:
```python
result = example.circumference(3)
print(result) # 18.84954
```
Then area:
```python
result = example.area(3)
print(result) # 28.27431
```
That's how to create your own module. It can be useful at times to separate your program into
individual files.
All right, everybody. In conclusion, a module is just a file containing code you want to include in your
program. You use `import` to include a module. You can use built-in modules or create your own. If you
do need a list of the modules available to you, again, you can use the `help` function, then pass in the
word `"modules"`. And well everybody, that's how to get started with modules in Python.
---
Hey friends, it's me again. Today I'm going to explain both variable scope and scope resolution. Variable
scope is where a variable is both visible and accessible. With scope resolution, when we're using a
variable, there is a certain order known as the LEGB rule in which we locate that variable: Local,
Enclosed, Global, Built-in. We'll get to this momentarily.
Let's begin with variable scope. I have two functions, `function_one` and `function_two`. Within
`function_one`, `a = 1`, then we print `a`. Within `function_two`, `b = 2`, then we print `b`.
```python
function_one()
function_two()
```
We would print 1 then 2.
Variables declared within a function have a local scope. Variable `a` is local to `function_one`. Variable
`b` is local to `function_two`.
Within `function_one`, if I were to print `b`, and within `function_two`, if I were to print `a`, we would
run into a name error:
```
```
And the same thing would apply with `a`. Functions can't see inside of other functions.
Imagine that we're `function_one`. This is our house. We can see everything that's going on inside of our
house, but `function_two` is our neighbor's house. We can't see what's going on inside of our neighbor's
house. We have no idea what `b` is with `function_two`. `function_two` has no idea what `a` is.
That's where variable scope comes in. It's where a variable is visible and accessible. Functions can't see
inside of other functions, but they can see inside of their own function. That's why we sometimes pass
arguments to functions so that our functions are aware of them.
Using this concept, we could create different versions of the same variable. Let's rename `a` to be `x`
and `b` to be `x` as well. Then I will print `x`. We have two different versions of `x`: a local version of `x`
found within `function_one` and a local version of `x` found within `function_two`.
Whenever we utilize a variable, we will first look to see if there's any local instance of that variable. If
there isn't, we would move to the enclosed scope.
With an enclosed scope, one example is when you have a function declared within another function. I'm
going to place `function_two` within `function_one`. This is allowed in Python. This is a more advanced
concept. We'll cover this more in the future.
So, I'm going to eliminate this print statement. Let's get rid of `function_two`. At the end of
`function_one`, we will invoke `function_two`. Like I said, it's pretty complex. We won't be using this
until much later.
Within `function_two`, if I was to print `x`, we would use the local version where `x = 2`. If I was to
eliminate this variable declaration, we would use the enclosed version instead where `x = 1`.
There's an order of operations: use any local variables first, then enclosed variables. We're printing `x`
within `function_two`. Since `x` wasn't found within the local scope, we would use `x` within the
enclosed scope. But like I said, that's a more advanced topic. You should at least be aware of it.
Let's move on to the global scope. Global meaning outside of any functions. I will eliminate these
variable declarations. Within `function_one`, we're printing `x` and within `function_two`, we're also
printing `x`. I will declare a global version of `x` where `x = 3`. `x` is outside of any functions.
When I run this program, we're printing 3 twice. Once for `function_one` and once for `function_two`.
There's no longer a local version of `x` for both of these functions. If there were, we would end up using
these local versions instead. `function_one` prints 1, `function_two` prints 2.
If there's no local version as well as no enclosed version, we would move on to the global version where
`x = 3`.
```python
print(e)
```
`e` is an exponential constant. I'm going to print what `e` is. `e` is 2.71. `e` is built-in.
```python
def function_one():
print(e)
function_one()
```
If I was to set `e` to be a different value like 3, what we're doing technically is creating two different
versions of `e`. Variables can share the same name as long as they're within a different scope. We have a
built-in version of `e` and a global version of `e`.
If I was to print `e` now, it would print my global version because using the LEGB order, we would first
look for any local version of `e`, then enclosed version, then global, which we do have one of, then lastly
built-in.
All right, everybody. So in conclusion, variable scope is just where a variable is both visible and
accessible. Python has a scope resolution order LEGB. If we're using a variable, we will first look in the
local scope for that variable. If we don't find that variable in the local scope, we will move over to an
enclosed scope, then global, then built-in. We will have more practice with this in the future. And well
everybody, that is both variable scope and scope resolution in Python.
---
```python
if __name__ == "__main__":
```
When you see this if statement, it's usually followed by a call to a function named `main` or something
similar. A majority of the driving code behind a program is usually found within some sort of main
method.
When you see this if statement, basically speaking, it means that this script can be imported or it can run
standalone. Functions and classes in this module can be reused in other programs without the main
block of code running.
Sometimes you would like the functionality of a program without executing the main body of code. A
good example could be a library. In a Python library, we would like to import some of the useful
functions such as the math module. But if we were to run that library directly instead of importing it, we
could instead display a help page. But if we're importing that library, we don't necessarily want to
display that help page, only if we're running it directly.
In many Python scripts, you'll see the statement:
```python
if __name__ == "__main__":
```
In this example, we're going to delete our main Python script. Be sure to recreate it at the end of this
topic in case I forget to mention that.
We will create two new scripts: go to File > New > Python File, `script_one`, and File > New > Python File,
`script_two`.
We have to add new run configurations for `script_one` and `script_two`. So if you go to the top, go to
Run > Edit Configurations. We will add a new run configuration. Select Python. Select a new script path
to `script_one`. Okay. Apply.
Again, we have to do this with `script_two`. Add Python. Select a script path of `script_two`. Okay.
Apply. Then okay.
Using this drop-down menu, we can select which run configuration we would like. Would we like to run
our main Python file, but we have deleted it? Do we want to run `script_one` or `script_two`?
Within `script_one`, if I was to print, then call the `__dir__` function (meaning directory). Python has all
of these built-in attributes. If you're not familiar with object-oriented programming, for now, think of an
attribute as a variable. `__name__` is a special type of variable. `__dunder__` meaning double
underscore.
If I was to print what's contained within `__name__`, we would receive a string of `"__main__"`. That's
why in a script you may see the statement:
```python
if __name__ == "__main__":
```
If so, then you usually call a function named `main` to start your program.
```python
```
Within `script_two`, I will print `__name__`. And we'll see what's within it.
Within `script_two`, `__name__` is equal to the string `"script_two"`, the name of the Python script.
However, within `script_one`, `__name__` is equal to the string `"__main__"`. This means I am running
`script_one` directly.
```python
import script_one
```
We're now going to change our run configuration from `script_one` to `script_two`. We are running
`script_two` directly.
Now `__name__` within `script_one` is the name of the Python script `script_one`.
`__name__` within `script_two` is now `"__main__"`.
```python
if __name__ == "__main__":
```
If `__name__ == "__main__"`, we will call a function `main` to contain the main body of our program.
```python
def main():
# Our main function will contain the majority of our Python code.
def favorite_food(food):
favorite_food("pizza")
print("Goodbye")
```
Here's the result. From the top down, all of our code is within functions. We skip over it because we're
not calling it quite yet. The first thing we do in this program is check this if statement. If `__name__` is
equal to `"__main__"`. Are we running this program directly? Which we are. We're running `script_one`.
If so, call the `main` method to start the program.
We print:
```
Goodbye
```
Now I'm going to go to `script_two`. Delete our print statement. Change the run configuration to
`script_two` and run it. Nothing should happen. That's good.
Now, if we were missing this if statement of `if __name__ == "__main__"`, then we delete our main
function. Here's what would happen. We're importing `script_one`, but we're running `script_two`. This
is script one. Your favorite food is pizza. Goodbye. I don't want this code to execute. We're not running
it directly. That's why we have that if statement.
If under name is equal to main, I only want to run this code if we're running it directly.
So what we'll do within `script_two` now is define a function of `favorite_drink`. There's one parameter
of `drink`. I will print the following message:
```python
def favorite_drink(drink):
```
```python
```
We will call from `script_one` the `favorite_food` function. Pass in your favorite food. This time I'll say
sushi.
```python
favorite_drink("coffee")
```
```
Goodbye
```
We're running `script_two`, but we're importing the functionality of the `favorite_food` function from
`script_one`.
Sometimes from another Python script, you want to borrow something, but you don't want to run the
main body of code directly. I just want to borrow this function from `script_one`, and that's it.
`script_two` can be run as a standalone program, but I can't import it without this body of code running.
I can add that if statement:
```python
if __name__ == "__main__":
main()
```
So let's call a function `main`, then place our main body of code within it.
So by adding this if statement of `if __name__ == "__main__"`, this script can be run as a standalone
program or it can be imported.
A more practical example of this could be a Python library. You can import the library for functionality,
but if you run the library directly, you could instead display a help page.
It is good practice to include `if __name__ == "__main__"`. It makes your code more modular, helps
with readability, leaves no global variables, and avoids unintended execution.
And well everybody, that is the purpose of `if __name__ == "__main__"` in Python.
---
Hey, what's going on everybody? So in this video, we're going to create a very simple banking program
using Python. This is meant to be more of an exercise to get us used to working with functions.
When creating a project, I like to divide that project into smaller sections, then handle them one at a
time. So, we'll do that by declaring all the functions we'll need first.
With a banking program, we'll need to show a user their balance. We'll define a function to show
balance. For the time being, I'll write `pass` just as a placeholder.
Near the end of this project, we will be creating a main function and placing the main body of our code
within it. We'll handle that near the end just to contain everything.
We have our three functions with our banking program. We'll need to show a balance, make a deposit,
or make a withdrawal.
What are some variables we'll need? Well, we'll need a balance, which I will set to be zero initially. I will
also create a boolean of `is_running`. This will be true. If at any time we set `is_running` to be false, we'll
exit the program.
So with the majority of our code, we'll place it within a while loop:
```python
while is_running:
# You can check to see if this is equal to True, but since this is a boolean, that's not necessary.
print("Banking Program")
print("4. Exit")
if choice == "1":
show_balance()
deposit()
withdraw()
is_running = False
else:
```
---
```python
def show_balance(balance):
print("*" * 30 + "\n")
def deposit():
if amount <= 0:
return 0
else:
return amount
def withdraw(balance):
print("Insufficient funds.")
return 0
return 0
else:
return amount
def main():
balance = 0.0
is_running = True
while is_running:
print("Banking Program")
print("4. Exit")
print("*" * 30)
if choice == "1":
show_balance(balance)
amount = deposit()
balance += amount
amount = withdraw(balance)
balance -= amount
is_running = False
else:
if __name__ == "__main__":
main()
```
```python
# Win. Okay, see I got all bells. It says you won $10.
# Once somebody runs out of money, we want to stop them from playing or if they would like to exit.
if play_again != "Y":
break
# Test run:
if play_again != "Y":
break
# ------------------------------------------------------------
import random
import string
chars = list(chars)
key = chars.copy()
random.shuffle(key)
# Encrypt message
cipher_text = ""
index = chars.index(letter)
cipher_text += key[index]
# Decrypt message
decrypted_text = ""
index = key.index(letter)
decrypted_text += chars[index]
# ------------------------------------------------------------
# Hangman game
import random
# Words list
hangman_art = {
def display_man(wrong_guesses):
print("*" * 10)
print(line)
print("*" * 10)
def display_hint(hint):
print(" ".join(hint))
def display_answer(answer):
print(" ".join(answer))
def main():
answer = random.choice(words)
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
# Input validation
continue
if guess in guessed_letters:
continue
guessed_letters.add(guess)
if guess in answer:
for i in range(len(answer)):
if answer[i] == guess:
hint[i] = guess
else:
wrong_guesses += 1
display_hint(hint)
is_running = False
# Check lose condition
if wrong_guesses == 6:
display_man(wrong_guesses)
is_running = False
if __name__ == "__main__":
main()
```
```python
# We know that that works. Now, we need a win condition if we guess all of the correct characters and
display the entire word.
display_man(wrong_guesses)
display_answer(answer)
print("You win!")
is_running = False
# Let's win this time. I already know that this word is probably pineapple.
# There we go. We have two wrong guesses, but we have correctly guessed the word pineapple.
elif wrong_guesses >= len(hangman_art) - 1: # hangman_art has 7 keys, so 6 is the max wrong guesses
display_man(wrong_guesses)
display_answer(answer)
print("You lose!")
is_running = False
# I'll guess incorrect letters.
# You lose.
# If you would like to import a larger variety of words, we could create a separate Python file for that.
# I'll add a note that these are words for hangman game.
# I recommend looking online for a very large set of words that we can use.
# While browsing online, I found an extensive list of animals that I can use.
# There's an A. No.
# E. I.
# O. There is an O.
# Is it goat? Nope.
# T R bore.
# You win.
# ------------------------------------------------------------
# For example, an attribute of the phone next to me could be version number = 13.
# Objects also have methods, which are functions that belong to an object.
class Car:
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
def drive(self):
def stop(self):
def describe(self):
print(car1.model) # Mustang
print(car1.year) # 2024
print(car1.color) # red
print(car1.for_sale) # False
class Student:
print(Student.class_year) # 2024
print(Student.num_students) # 4
print(student1.name)
print(student2.name)
print(student3.name)
print(student4.name)
# ------------------------------------------------------------
# Inheritance in Python
class Animal:
self.name = name
self.is_alive = True
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
class Dog(Animal):
pass
class Cat(Animal):
pass
class Mouse(Animal):
pass
# Create objects
dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")
# Access attributes and methods inherited from Animal
print(dog.name) # Scooby
print(dog.is_alive) # True
print(cat.name) # Garfield
print(cat.is_alive) # True
print(mouse.name) # Mickey
print(mouse.is_alive) # True
# ------------------------------------------------------------
# Note: If you need to modify a method for a child class, you can override it by defining it in the child
class.
```
It's not too bad if you only have a few classes, but imagine if you have hundreds of classes. That's going
to take a lot of work. It's a lot easier to write the code once and then reuse it. And I only need to make
that change in one place rather than make that change many times.
So, let's change **is sleeping** to **is asleep** and see if that works again.
```python
Mickey is asleep.
```
Let's replace mouse with dog.
```python
Scooby is asleep.
```
Not only that, but with children classes, they can have their own attributes and methods that are
different from one another. So, dogs have all these attributes and methods and they can speak. Let's
create a `speak` method. And I will print a unique message for dogs:
```python
def speak(self):
print("Woof")
```
Cats will also have a `speak` method, but it's going to be different. Cats will meow:
```python
def speak(self):
print("Meow")
```
```python
def speak(self):
print("Squeak")
```
```python
dog.speak() # Woof
```
```python
cat.speak() # Meow
```
```python
mouse.speak() # Squeak
```
All right, everybody. So, that's an introduction to inheritance. Inheritance allows a class to inherit
attributes and methods from another class. Much like in real life, a child can inherit traits from a parent.
These are also known as sub and superclasses which is a topic for another day.
Inheritance helps with code reusability and extensibility. If all of these children classes inherit these
attributes and methods from another class, we only need to write that code once and not copy it for
every single class that needs it. We can write and change the code in one place for better reusability and
extensibility.
---
Hey everybody. So today we got to talk about both **multiple** and **multi-level inheritance**.
We'll begin with **multiple inheritance**. That's when a child class inherits from more than one parent
class. For example, a class `C` can inherit the traits from both class `A` and `B`. In Python, you can have
more than one parent. Multi-level inheritance we'll talk about near the end of this topic.
So in this example, we're going to create two parent classes: `Prey` and `Predator`. We'll create a class of
`Rabbit`, a class of `Hawk`, then class `Fish`. `Rabbit`, `Hawk`, and `Fish` are going to be children classes.
`Prey` and `Predator` will be parents.
If one of these classes, `Rabbit`, `Hawk`, or `Fish`, inherit from `Prey`, they get the ability to flee. We will
define a method `flee`:
```python
def flee(self):
```
```python
def hunt(self):
```
Rabbits will inherit from the `Prey` class. They're typically not predators except that one rabbit in Monty
Python and the Holy Grail. That's the exception. `Rabbit` will inherit the `Prey` class. Then it gets access
to a `flee` method.
Now fish, they will hunt smaller fish and flee from bigger fish. You can consider fish both prey and
predators. So they will inherit both classes. We will use multiple inheritance. They will inherit everything
from the `Prey` class and the `Predator` class.
```python
rabbit = Rabbit()
```
There are no parameter setup. We don't need to send any arguments to the constructor.
```python
hawk = Hawk()
fish = Fish()
```
So, let's take our `rabbit` object and they should have a `flee` method:
```python
```
But they do not have a `hunt` method because they're not predators:
```python
```
```python
```
```python
```
Fish can do both. They inherit from the `Prey` class and the `Predator` class:
```python
```
Children classes can inherit from more than one parent, which is what we did for fish. They are both
prey and predators. Whereas rabbits are just prey, hawks are just predators.
If you need to inherit from more than one parent, you just add that additional class to the inheritance
list.
With **multi-level inheritance**, a parent can inherit from another parent. We will create a class of
`Animal`. And for now, I'll write `pass`.
`Prey` and `Predator` are going to inherit from the `Animal` class. So, we need to add `Animal` to each
inheritance list.
Let's say if you're an animal, you get a method to eat. All animals will eat:
```python
def eat(self):
```
```python
def sleep(self):
```
So think of `Rabbit`, `Hawk`, and `Fish` as children classes. `Prey` and `Predator` are those classes'
parents, and `Animal` is the grandparent.
`Prey` and `Predator` will inherit everything that the `Animal` class has. `Rabbit`, `Hawk`, and `Fish` will
inherit everything the `Prey` and `Predator` classes have.
So now our `Rabbit`, `Hawk`, and `Fish` classes should have the ability to eat and sleep. And we'll test
that:
```python
```
```python
```
Each of our objects is going to have a name. Our rabbit will have a first name of Bugs. Hawk will be Tony
as in Tony Hawk. Our fish will be Nemo.
Within our classes, we don't have any constructor set up. In which class should we assign the `name`
attribute? Let's do so within our `Animal` class.
So, we will define a constructor to assign these attributes. We will receive a name. We'll assign:
```python
self.name = name
```
Now, with these other classes, if you're not assigning any attributes or if you don't need any other
initialization logic, you don't need a constructor. We'll implicitly use the constructor we inherit from the
parent.
Let's convert each of these print statements to an f-string. Replace "animal" with `self.name`.
```python
```
Let's check out our hawk. Hawks don't have a `flee` method because they're predators, not prey.
Let's eat:
```python
```
```python
```
Okay, everybody. That is both multiple and multi-level inheritance.
With multiple inheritance, a child can inherit from more than one parent class. You just add each
additional class to the inheritance list.
With multi-level inheritance, a child can inherit from a parent which inherits from another parent. Class
`C` can inherit from `B` where class `B` inherits from `A`. Think of `C` as the child, `B` is the parent and `A`
as the grandparent. `C` will have all the attributes and methods even available within the grandparent
class of `A`.
And well everybody that is both multiple and multi-level inheritance in Python.
---
Hey everybody. So today I got to talk about the **super** function in Python.
`super` is a function. It's used within a child class to call methods from a parent class. The child class is
the subclass. The parent class is the superclass. Hence why this function is named the super function.
Using the super function, it allows you to extend the functionality of the inherited methods.
Here's an example. We'll create a few shape objects. We'll need to set up the classes though. We'll have
class `Circle`. For the time being, I'll just write `pass`. We'll fill it in later. Class `Square` and class
`Triangle`.
For each of these classes, in order to instantiate objects, we'll need a constructor. We will define our
constructor, our `__init__` method.
When creating circles, what sorts of attributes should a circle have? Let's say a color. What's the color of
the circle? Is it filled or not? `filled` will be another attribute and a radius. Then let's assign these:
```python
self.color = color
self.filled = filled
self.radius = radius
```
Let's do this with the square and triangle. Really, I'll just copy our constructor and paste it.
Squares don't have a radius. With a square, the width and the height are the same. Let's replace radius
with width. We'll also keep the color and filled attributes:
```python
self.width = width
```
Now, with triangles again, let's copy our constructor. We'll need a width and a height:
```python
self.width = width
self.height = height
```
So with programming, we try not to repeat ourselves if we don't have to. What do all of these classes
have in common? They all share the attributes of color and filled. The ways in which they are different is
that circle has a radius attribute, square has a width, triangle has a width and a height.
If we have to make any changes to one of these attributes, we would have to do so manually. For
example, let's replace `filled` with `is_filled`. Now, I need to look throughout my code for any instance of
`filled` and replace it with `is_filled`. It's a lot of work and I might make a mistake such as here and here.
It's better to write your code once and try and reuse it. So, that's where inheritance and the super
function can come in handy.
We're going to take the attributes of color and is_filled and place it within a parent class. These children
classes will inherit those attributes.
So:
```python
class Shape:
self.color = color
self.is_filled = is_filled
```
`Circle` is going to inherit from its parent of `Shape`. That also applies with `Square` and `Triangle`.
```python
self.color = color
self.is_filled = is_filled
```
We don't need to manually assign these attributes within each of these constructors for the children.
Instead what we have to do is within the constructor for each of these children classes we have to call
the constructor for the parent, also known as the superclass of `Shape`.
So we will eliminate these two lines of code. Use the super function, call the constructor of the parent,
that is the `__init__` method. But we need to pass in the color that we receive and is_filled. This will be
a boolean.
And let's do this with the `Square` class and the `Triangle` class.
We still need radius for the circle, width for the square, width and height for the triangle.
We're going to call the super function to take care of whatever attributes all these types of shapes have
in common such as color and is_filled.
We will create a circle named `circle` called a constructor for circle. We have to pass in a color, a
boolean if it's filled or not, and a radius.
So for the color of the circle, let's say red, is_filled is true, and a radius of five.
You could even use keyword arguments for better readability. Although not necessary, but for clarity:
```python
```
```python
print(circle.color) # red
```
```python
print(circle.is_filled) # True
```
```python
print(f"{circle.radius} cm") # 5 cm
```
Let's construct a square object:
```python
```
We don't need a height because squares have an even width and height. If we ever need the height, we
can assume it's the same as the width. In this case, 6.
```python
print(square.color) # blue
print(square.is_filled) # False
print(f"{square.width} cm") # 6 cm
```
```python
```
```python
print(triangle.color) # yellow
print(triangle.is_filled) # True
print(f"{triangle.width} cm") # 7 cm
print(f"{triangle.height} cm") # 8 cm
```
So that's how you can use the super function to reuse the constructor of a parent class. We don't need
to manually assign each of these attributes within each of the children classes. We can do that in just
one place.
When we refer to `super`, imagine that we're replacing this with the parent class name such as `Shape`.
That might be a good way to think of it. Use the constructor of the parent class of `Shape` and pass
these arguments in.
So within our `Shape` class, let's create a method of `describe`. We will describe the attributes of this
shape. We will print using an f-string:
```python
def describe(self):
```
Each of these types of shapes `Circle`, `Square`, and `Triangle` will have access to a `describe` method.
```python
```
What if we create a similar method of `describe` within `Circle`, `Square`, and `Triangle`?
Let's do that.
```python
def describe(self):
```
If I were to call the `describe` method, will we use the parent's version of `describe` or the child's?
```python
```
This is called **method overriding**. If a child shares a similar method with a parent, you'll use the
child's version and not the parent's.
If you would like to extend the functionality of a method from a parent, you can use the super function.
Not only do I want to use the `describe` method of the child, I would also like to use the `describe`
method of the parent.
So within this function we will use the super function to access the `describe` method of the parent.
```python
def describe(self):
super().describe()
```
It is a circle with an area of 78.5 cm squared. The circle is red and it's filled.
```python
def describe(self):
super().describe()
```
I'll copy what we have for the `describe` method within the `Circle` class, but we'll make a different
calculation.
```python
def describe(self):
super().describe()
```
The height and the width are going to be the same if it's a square.
def describe(self):
super().describe()
```
```python
square.describe()
```
```python
triangle.describe()
```
All right, everybody. That is the super function. It's used in a child class to call the methods from a
parent class, also known as the superclass. It allows you to extend the functionality of the inherited
methods within a child class.
You could use it within a constructor to assign any attributes that all of its siblings have in common, such
as color or if that shape is filled.
When used within any other method, you can extend the functionality of that method. Not only are we
printing this message from the parent, we're tacking on another print statement before that.
Polymorphism is a programming concept. It's a Greek word that means to have many forms or faces.
Poly means many. Morph means form.
There's two ways to achieve polymorphism. One is through inheritance. An object could be treated as
the same type as a parent class. There's also duck typing, which we'll talk about in the next topic.
What we'll do in this video is create a class of `Shape`. We'll write `pass` as a placeholder.
We will create a class of `Circle` which will inherit from `Shape`. Again writing `pass`.
```python
circle = Circle()
```
Our circle identifies as a circle. And since our circle class inherits from the shape class, our circle is also
considered a shape. It has two forms. It's a circle and it's a shape.
Those are two possible forms for our square. It's a square and a shape.
```python
shapes = []
```
Let's say that with our `Shape` class, we will define an `area` method:
```python
def area(self):
pass
```
```python
```
Our `Circle`, `Square`, and `Triangle` classes, they're all considered shapes. They inherit from this class.
We need to define an `area` method for each since they're all considered a shape. Every shape has an
area.
```python
self.radius = radius
```
```python
self.side = side
```
Then `Triangle`:
```python
self.base = base
self.height = height
```
All right.
Now let's finish defining these `area` methods for each class.
We will return:
```python
3.14 * self.radius ** 2
```
```python
return self.side ** 2
```
```python
```
Now we have to pass in some arguments.
```python
print(f"{shape.area()} cm squared")
```
If you would like, you can format the output. I'll just use an f-string. I'll add cm squared.
Much better.
To construct a pizza object, we need a topping and a radius. What is the radius of the pizza?
```python
self.author
```
What if the key is number of pages?
```python
return self.num_pages
```
```python
else:
```
```python
print(book2["author"]) # JK Rowling
print(book3["num_pages"]) # 172
```
```python
```
---
These magic methods allow customizing how objects behave with built-in Python operations.
---
Feel free to ask if you'd like me to provide the full class code with all these magic methods
implemented!
```python
if key == "author":
return self.author
return self.num_pages
else:
# Example usage:
book3 = Book("The Lion, the Witch and the Wardrobe", "CS Lewis", 172)
print(book3["author"]) # CS Lewis
print(book2["author"]) # JK Rowling
print(book2["num_pages"]) # 223
print(book3["num_pages"]) # 172
```
---
Magic methods, also known as dunder methods (double underscore), are special methods in Python
that are automatically called by many of Python's built-in operations. They allow developers to define or
customize the behavior of objects when using those built-in operations.
---
The property decorator allows us to define a method as a property, so it can be accessed like an
attribute. It provides getter, setter, and deleter methods to add additional logic when reading, writing,
or deleting attributes.
Example:
```python
class Rectangle:
@property
def width(self):
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
@width.deleter
def width(self):
del self._width
@property
def height(self):
@height.setter
if new_height > 0:
self._height = new_height
else:
@height.deleter
def height(self):
del self._height
# Usage
rectangle = Rectangle(3, 4)
print(rectangle.width) # 3.0 cm
print(rectangle.height) # 4.0 cm
rectangle.width = 5 # Sets width to 5
```
---
# Decorators in Python
A decorator is a function that extends the behavior of another function without modifying the base
function. It takes the base function as an argument and returns a new function that adds extra behavior.
Example:
```python
def add_sprinkles(func):
return wrapper
def add_fudge(func):
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream(flavor):
print(f"Here is your {flavor} ice cream ")
get_ice_cream("vanilla")
# Output:
```
---
Exceptions are events that interrupt the normal flow of a program. Common exceptions include
`ZeroDivisionError`, `TypeError`, and `ValueError`.
```python
try:
print(1 / number)
except ZeroDivisionError:
except ValueError:
except Exception as e:
finally:
```
---
```python
import os
if os.path.exists(file_path):
else:
```
```python
file_path = "stuff/test.txt"
```
---
If you want me to provide code examples or explanations for any specific part, just ask!
```python
import os
file_path = "C:/Users/YourName/Documents/test.txt"
if os.path.exists(file_path):
# Check if it is a file
if os.path.isfile(file_path):
print("That is a file.")
# Check if it is a directory
elif os.path.isdir(file_path):
print("That is a directory.")
else:
file.write(text_data)
abs_path = "C:/Users/YourName/Desktop/output.txt"
file.write(text_data)
print(f"Text file '{abs_path}' was created.")
try:
file.write(text_data)
except FileExistsError:
# Appending to a file
file.write("\n" + text_data)
file.write(employee + "\n")
import json
employee = {
"name": "Spongebob",
"age": 30,
"job": "cook"
json_path = "employee.json"
import csv
employees_data = [
csv_path = "employees.csv"
writer = csv.writer(file)
writer.writerow(row)
try:
content = file.read()
print(content)
except FileNotFoundError:
json_path = "input.json"
import json
try:
content = json.load(file)
print(content)
print(content.get("name"))
except FileNotFoundError:
except json.JSONDecodeError:
csv_path = "input.csv"
import csv
try:
reader = csv.reader(file)
print(line)
except FileNotFoundError:
import datetime
# Create a date object
date_obj = datetime.date(2025, 1, 2)
print(date_obj) # 2025-01-02
today = datetime.date.today()
print(time_obj) # 12:30:00
now = datetime.datetime.now()
current_datetime = datetime.datetime.now()
else:
```
```python
import time
import datetime
import pygame
def set_alarm(alarm_time):
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
is_running = True
while is_running:
current_time = datetime.datetime.now().strftime("%H:%M:%S")
print(current_time)
if current_time == alarm_time:
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time.sleep(1)
is_running = False
time.sleep(1)
if __name__ == "__main__":
set_alarm(alarm_time)
```
---
```python
import threading
import time
def walk_dog(name):
time.sleep(8)
def take_out_trash():
time.sleep(2)
def get_mail():
time.sleep(4)
chore2 = threading.Thread(target=take_out_trash)
chore3 = threading.Thread(target=get_mail)
chore1.start()
chore2.start()
chore3.start()
chore1.join()
chore2.join()
chore3.join()
```
---
```python
import requests
def get_pokemon_info(name):
base_url = "https://pokeapi.co/api/v2/pokemon/"
url = f"{base_url}{name.lower()}"
response = requests.get(url)
if response.status_code == 200:
print("Data retrieved")
return response.json()
else:
return None
if __name__ == "__main__":
pokemon_info = get_pokemon_info(pokemon_name)
if pokemon_info:
print(f"Name: {pokemon_info['name'].capitalize()}")
print(f"ID: {pokemon_info['id']}")
print(f"Height: {pokemon_info['height']}")
print(f"Weight: {pokemon_info['weight']}")
```
---
```python
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
```
```python
# GUI guey. And now we have a new title: My Cool First Guey Graphical User Interface.
# When this window appears, we can set the geometry of where the window appears and the size of the
window.
# Access self.setGeometry method. There's four arguments: X and Y for the coordinates, width, and
height.
# This sets the window to appear at the top-left corner (0,0) with width and height 500 pixels each.
self.setWindowIcon(QIcon("profile_pic.jpg"))
# Set font:
self.label.setFont(QFont("Arial", 40))
self.label.setStyleSheet("""
color: #333333;
background-color: #0000FF;
font-weight: bold;
font-style: italic;
text-decoration: underline;
""")
self.label.setAlignment(Qt.AlignTop)
self.label.setAlignment(Qt.AlignBottom)
self.label.setAlignment(Qt.AlignRight)
self.label.setAlignment(Qt.AlignHCenter)
self.label.setAlignment(Qt.AlignLeft)
self.label.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
self.label.setAlignment(Qt.AlignCenter)
self.image_label = QLabel(self)
pixmap = QPixmap("profile_pic.jpg")
self.image_label.setPixmap(pixmap)
self.image_label.setGeometry(
self.width() - self.image_label.width(),
0,
self.image_label.width(),
self.image_label.height()
self.image_label.setGeometry(
self.width() - self.image_label.width(),
self.height() - self.image_label.height(),
self.image_label.width(),
self.image_label.height()
self.image_label.setGeometry(
0,
self.height() - self.image_label.height(),
self.image_label.width(),
self.image_label.height()
self.image_label.setGeometry(
(self.width() - self.image_label.width()) // 2,
(self.height() - self.image_label.height()) // 2,
self.image_label.width(),
self.image_label.height()
def initUI(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
label1.setStyleSheet("background-color: red;")
label2.setStyleSheet("background-color: yellow;")
label3.setStyleSheet("background-color: green;")
label4.setStyleSheet("background-color: blue;")
label5.setStyleSheet("background-color: purple;")
# Vertical layout:
vbox = QVBoxLayout()
vbox.addWidget(label1)
vbox.addWidget(label2)
vbox.addWidget(label3)
vbox.addWidget(label4)
vbox.addWidget(label5)
central_widget.setLayout(vbox)
# For horizontal layout, replace QVBoxLayout with QHBoxLayout and set layout accordingly.
grid = QGridLayout()
grid.addWidget(label1, 0, 0)
grid.addWidget(label2, 0, 1)
grid.addWidget(label3, 1, 0)
grid.addWidget(label4, 1, 1)
grid.addWidget(label5, 2, 2)
central_widget.setLayout(grid)
# In constructor or initUI:
self.button.setStyleSheet("font-size: 30px;")
self.button.clicked.connect(self.on_click)
def on_click(self):
print("Button clicked")
self.button.setText("Clicked")
self.button.setDisabled(True)
self.label.setStyleSheet("font-size: 30px;")
def on_click(self):
print("Button clicked")
self.button.setText("Clicked")
self.button.setDisabled(True)
```
```python
self.label.setFont(QFont("Arial", 50))
# In the on_click function, update label text to "Goodbye" when button is clicked
def on_click(self):
self.label.setText("Goodbye")
# Initialize UI method:
self.checkbox.stateChanged.connect(self.checkbox_changed)
# Define slot method:
if state == Qt.Checked:
else:
# In constructor:
# Set geometry:
self.setStyleSheet("""
QRadioButton {
font-size: 40px;
font-family: Arial;
padding: 10px;
}
""")
self.button_group1 = QButtonGroup(self)
self.button_group1.addButton(self.radio1)
self.button_group1.addButton(self.radio2)
self.button_group1.addButton(self.radio3)
self.button_group2 = QButtonGroup(self)
self.button_group2.addButton(self.radio4)
self.button_group2.addButton(self.radio5)
rb.toggled.connect(self.radio_button_changed)
# Slot method:
def radio_button_changed(self):
radio_button = self.sender()
if radio_button.isChecked():
print(f"{radio_button.text()} is selected")
# In constructor:
self.lineedit = QLineEdit(self)
self.button.clicked.connect(self.submit)
# Slot method:
def submit(self):
text = self.lineedit.text()
print(f"Hello {text}")
# In initialize UI method:
central_widget = QWidget()
self.setCentralWidget(central_widget)
hbox = QHBoxLayout()
hbox.addWidget(self.button1)
hbox.addWidget(self.button2)
hbox.addWidget(self.button3)
central_widget.setLayout(hbox)
self.button1.setObjectName("buttonOne")
self.button2.setObjectName("buttonTwo")
self.button3.setObjectName("buttonThree")
self.setStyleSheet("""
QPushButton {
font-size: 40px;
font-family: Arial;
margin: 25px;
border-radius: 15px;
QPushButton#buttonOne {
QPushButton#buttonTwo {
QPushButton#buttonThree {
""")
```
I would say that's not too bad. If you're already familiar with CSS, we can apply pseudo-classes such as
when we hover over one of the buttons. Here's how. Let's copy these three blocks, then paste them
again. We can add CSS properties. When we hover over something, we have to use the `:hover` pseudo-
class. After the ID of each of our buttons, we will add `:hover`. We can apply the following CSS
properties when we hover over the buttons. All I'm going to do is increase the lightness, let's say by 20%
each. Then when we hover over one of the buttons, the lightness is going to change. We apply the new
CSS properties.
All right, everybody. So that is a more in-depth explanation of the `setStyleSheet` method in PyQt5.
---
All right, everybody. In today's video, we're going to build a digital clock widget using Python's PyQt5
library.
At the top of our Python file, we will need the following imports:
```python
import sys # sys means system. This module provides variables used and maintained by the Python
interpreter.
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout # Widgets are the building
blocks of a GUI application.
from PyQt5.QtCore import QTimer, QTime, Qt # QtCore provides functionality not related to GUI
components.
```
We will create a class `DigitalClock`. Instead of inheriting from the main window widget, we will inherit
from the base class `QWidget`. `QWidget` is a base class to create our own widgets. Our digital clock will
be a widget.
```python
class DigitalClock(QWidget):
super().__init__(*args, **kwargs)
self.initUI()
```
At the end of the constructor, I like to call a method `initUI` to initialize the user interface.
```python
def initUI(self):
self.setWindowTitle("Digital Clock")
self.time_label.setStyleSheet("""
font-size: 150px;
font-family: Arial;
""")
vbox.addWidget(self.time_label)
self.setLayout(vbox)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_time)
```
Create the `update_time` method to update the label with the current time:
```python
def update_time(self):
self.time_label.setText(current_time)
```
---
As an added bonus, if you would like to download a custom font, here's how:
1. Using Google or another search engine, look up a font of your choosing. One font I like is **DS
Digital**.
3. Move the `.ttf` file to your project folder (next to your main Python file).
```python
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
self.time_label.setFont(my_font)
```
Remove the font-family from the stylesheet when using a custom font.
---
All right, everybody. So that is how to create a digital clock widget using PyQt5.
---
Hey yeah everybody. In today's video, we're going to create this stopwatch program using Python's
PyQt5 library.
```python
import sys
```
We will construct a class `Stopwatch` which will inherit from the base class `QWidget`. Our stopwatch
will be a widget.
```python
class Stopwatch(QWidget):
super().__init__(*args, **kwargs)
self.timer = QTimer(self)
self.initUI()
```
```python
def initUI(self):
self.setWindowTitle("Stopwatch")
vbox = QVBoxLayout()
hbox = QHBoxLayout()
vbox.addWidget(self.time_label)
hbox.addWidget(self.start_button)
hbox.addWidget(self.stop_button)
hbox.addWidget(self.reset_button)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.time_label.setAlignment(Qt.AlignCenter)
# Apply stylesheet
self.setStyleSheet("""
QPushButton {
font-size: 50px;
QLabel {
font-size: 120px;
border-radius: 20px;
padding: 20px;
font-weight: bold;
""")
self.start_button.clicked.connect(self.start)
self.stop_button.clicked.connect(self.stop)
self.reset_button.clicked.connect(self.reset)
self.timer.timeout.connect(self.update_display)
```
Define the methods to start, stop, reset, format time, and update display:
```python
def start(self):
def stop(self):
self.timer.stop()
def reset(self):
self.timer.stop()
self.time = QTime(0, 0, 0, 0)
self.update_display()
hours = time.hour()
minutes = time.minute()
seconds = time.second()
milliseconds = time.msec()
return f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:03}"
def update_display(self):
self.time = self.time.addMSecs(10)
self.time_label.setText(self.format_time(self.time))
```
---
At the end of your file, add the main block to run the application:
```python
if __name__ == "__main__":
app = QApplication(sys.argv)
stopwatch = Stopwatch()
stopwatch.show()
sys.exit(app.exec_())
```
---
This will create a functional stopwatch with start, stop, and reset buttons, updating every 10
milliseconds.
Let me know if you'd like me to provide the full code or any additional explanations!
```python
def update_display(self):
hours = time.hour()
minutes = time.minute()
seconds = time.second()
return f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:02}"
def reset(self):
self.timer.stop()
# Now you can start, stop, and reset the stopwatch as expected.
# ------------------------------------------------------------
import sys
import requests
class WeatherApp(QWidget):
def __init__(self):
super().__init__()
self.initializeUI()
def initializeUI(self):
self.setWindowTitle("Weather App")
# Create widgets
self.city_label.setObjectName("city_label")
self.city_input = QLineEdit(self)
self.city_input.setObjectName("city_input")
self.get_weather_button.setObjectName("get_weather_button")
self.get_weather_button.clicked.connect(self.get_weather)
self.temperature_label.setObjectName("temperature_label")
self.temperature_label.setAlignment(Qt.AlignCenter)
self.emoji_label.setObjectName("emoji_label")
self.emoji_label.setAlignment(Qt.AlignCenter)
self.description_label.setObjectName("description_label")
self.description_label.setAlignment(Qt.AlignCenter)
# Layout
vbox = QVBoxLayout()
vbox.addWidget(self.city_label, alignment=Qt.AlignCenter)
vbox.addWidget(self.city_input, alignment=Qt.AlignCenter)
vbox.addWidget(self.get_weather_button)
vbox.addWidget(self.temperature_label, alignment=Qt.AlignCenter)
vbox.addWidget(self.emoji_label, alignment=Qt.AlignCenter)
vbox.addWidget(self.description_label, alignment=Qt.AlignCenter)
self.setLayout(vbox)
self.setStyleSheet("""
QLabel#city_label {
font-family: Calibri;
font-size: 40px;
font-style: italic;
QLineEdit#city_input {
font-size: 40px;
QPushButton#get_weather_button {
font-size: 30px;
font-weight: bold;
QLabel#temperature_label {
font-size: 75px;
QLabel#emoji_label {
font-size: 100px;
QLabel#description_label {
font-size: 50px;
""")
def get_weather(self):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
try:
response = requests.get(url)
data = response.json()
if data.get("cod") == 200:
self.display_weather(data)
else:
status_code = response.status_code
match status_code:
case 400:
case 401:
case 403:
self.display_error("Forbidden.\nAccess is denied.")
case 404:
case 500:
case 502:
case 503:
case 504:
except requests.exceptions.ConnectionError:
except requests.exceptions.Timeout:
except requests.exceptions.TooManyRedirects:
self.display_error(f"Request error:\n{err}")
self.temperature_label.setText("")
self.emoji_label.setText("")
self.description_label.setText(message)
kelvin_temp = data["main"]["temp"]
self.temperature_label.setText(f"{celsius_temp:.1f} °C")
description = data["weather"][0]["description"].capitalize()
icon_code = data["weather"][0]["icon"]
icon_map = {
self.emoji_label.setText(emoji)
self.description_label.setText(description)
if __name__ == "__main__":
app = QApplication(sys.argv)
weather_app = WeatherApp()
weather_app.show()
sys.exit(app.exec_())
```
```python
# Replace those. One thing I forgot to add, although it's not necessary, I'm going to add a colon after
each initial message.
# I think it'll look better. You don't have to do this, but I'm OCD about the appearance.
# If we encounter one of these exceptions, we'll pass along a message to our display error method and
display it within the app.
# Let's take our temperature label self.temperature_label and set the text to be our message that we
pass in.
self.temperature_label.setText(message)
# Let's do a test run. Let's look up a city that doesn't exist. Get the weather.
# So, we get that error message: Not found. City not found.
# While we're within this method, I'm going to change the font size just so that it's a little bit smaller.
# I will call the setStyleSheet method and pass along a new property.
self.temperature_label.setStyleSheet("font-size: 30px;")
# Let's look up blah blah blah. Not found. City not found.
# I'll just delete one of the digits. Let's look up Los Angeles.
# Within our data object, we are looking for a key of 'main' and that is right here.
# Once we've accessed 'main', we have to access 'temp' to get the temperature.
temperature_K = data["main"]["temp"]
# Then in Fahrenheit.
# All right. So once we have our temperature, let's change the temperature label.
# Add a placeholder.
# Hold alt.
self.temperature_label.setText(f"{temperature_F:.0f}° F")
# So, within the display_weather method, let's set the font size back to 75, what it was originally.
self.temperature_label.setStyleSheet("font-size: 75px;")
# Then, we'll look up a city that does exist, like Miami, and get the weather.
# 95° F.
# In the center, we'll display a picture or an emoji, but we'll handle that last.
# So, after we calculate the temperature, so I'm going to print our data again.
weather_description = data["weather"][0]["description"]
# Then we will set the text and then pass in our weather description.
self.description_label.setText(weather_description.capitalize())
# What is the weather description of Los Angeles?
# We'll add it right to the center between the temperature and the weather description.
# You don't necessarily have to, but I think it'll look cool and that's a good enough reason.
# We will define a method of get_weather_emoji or a picture if you would rather use a picture.
# This method isn't going to rely on any class data or instance data.
@staticmethod
def get_weather_emoji(weather_id):
# Depending on the range of that three-digit number, we will return one of a few emojis.
else:
# I'm going to show you where we can find that weather ID.
# Now, at the key of 'weather', there's a key of 'id', and the value is a three-digit number.
# Depending on what this three-digit number is, that corresponds to a certain group of weather.
# 300 is a drizzle.
# 500 is rain.
# 600 is snow.
# Depending on what this ID is, I would like to return a certain emoji based on the weather.
weather_id = data["weather"][0]["id"]
# Okay everybody, we're near the end.
# So after setting the temperature, we're going to set the emoji label.
self.emoji_label.setText(self.get_weather_emoji(weather_id))
# Depending on the range of that three-digit number, we will return one of a few emojis.
# So if our weather ID is greater than or equal to 200 and our weather ID is less than or equal to 232.
# Now we have two conditions here linked with the and logical operator.
# There is a shortcut to this and actually PyCharm is telling me that there is.
# If 200 is less than or equal to our weather ID and our weather ID is less than or equal to 232,
# So to add an emoji on Windows, you can hold down the window key and press semicolon.
# Depending on the font style of your IDE, some of these emojis might not display properly.
# Then else if 300 is less than or equal to our weather ID and our weather ID is less than or equal to 321.
# 600 to 622
# Else if 600 is less than or equal to our weather ID which is less than or equal to 622 we will return
snow.
# Else if 701 is less than or equal to our weather ID which is less than or equal to 741.
# So else if our weather id is directly equal to 762 we will return let's return a volcano.
# Else if 801 is less than or equal to our weather ID which is less than or equal to 804.
# Now, if there are no matches, let's return an empty string to not display anything.
# It's 94°.
# Los Angeles.
# let's take the emoji label self.emoji_label and call the clear method to clear it.
self.emoji_label.clear()
# Then we have to do this with the description label self.description_label and call the clear method.
self.description_label.clear()
# Few clouds.
# 98°.
# Not found.
# And the emoji label and the weather description are cleared.
# Okay.
# What happens?
# Bad request.
# So, that is a weather app that you can make using Python.
```