Introduction to Python Programming
- Start coding with no prior experience
- Hands-on projects including a weather app fetching real-time data from a public API
Setting Up Your Environment
- Download and install Python from python.org
- Choose an IDE: beginners may prefer PyCharm Community Edition or VS Code with Python extension
- Create Python projects and files for your scripts
Python Basics: Variables & Data Types
- Variables as containers for values (see Основы работы с переменными и типами данных в Python)
- Data types: strings, integers, floats, booleans
- Using print statements and comments to output and document code
- Introduction to f-strings for string formatting
Type Casting and User Input
- Convert between data types using int(), float(), str(), bool()
- Handling user input using input() returns strings
- Casting user input for arithmetic or logical operations
- Exercises: area calculator, shopping cart
Control Flow: If Statements and Loops
- If, elif, and else for decision making
- Logical operators: and, or, not
- While loops and for loops for repetition and iteration
- User input validation with loops
Functions and Arguments
- Defining reusable code blocks with functions
- Arguments: positional, default, keyword, arbitrary (*args, **kwargs)
- Return statements to send results back
Collections in Python
- Lists, sets, tuples: creation, properties, methods
- Dictionaries: key-value pairs, methods for access and updates
- Nested and 2D collections, iteration techniques
Object-Oriented Programming
- Classes and objects: attributes and methods
- Constructors (init), self parameter
- Class vs instance variables
- Inheritance: single, multiple, multi-level
- Super() function for parent method calls
- Polymorphism: method overriding and duck typing
- Magic methods (str, eq, etc.) for customizing object behavior
- Property decorator for controlled attribute access
Exception Handling
- Using try, except, finally blocks
- Handling common errors (ZeroDivisionError, ValueError, HTTP errors)
File Handling
- Detecting files with os module
- Reading and writing plain text, JSON, and CSV files
- Using with statement for safe file operations
Working with Dates and Times
- datetime module: creating, formatting, and comparing dates and times
Multi-threading
- Running multiple tasks concurrently using threading module
- Creating threads for IO-bound tasks
Working with APIs
- Using requests to fetch data from the web
- Parsing JSON responses
- Handling HTTP status codes and errors
- Example: querying the PokeAPI for Pokemon data
GUI Development with PyQt5
- Creating windows, labels, buttons, images, layouts
- Handling events: signals and slots
- Widgets: checkboxes, radio buttons, line edits
- Styling GUIs with CSS-like syntax
- Building projects: digital clock, stopwatch, weather app
This series guides learners from fundamental programming concepts through advanced applications, culminating in practical projects like a weather app. It’s ideal for beginners and those looking to build a solid foundation in Python programming and GUI development.
For an in-depth dive into data handling techniques useful across many of these topics, consider the Comprehensive Guide to Python Pandas: Data Inspection, Cleaning, and Transformation. Also, if you're interested in exploring detailed project-based learning paths, check out the Comprehensive Python Course: From Basics to Advanced Mega Projects.
What's up everybody? 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 IDEES, 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 IDE 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 parenthesis. Between the set of parenthesis, 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 I like pizza.
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 or whatever your favorite food is. Let's print another line of code.
Let's print it's really good. By adding a second print
statement, we are printing a second line of code. Now we'll discuss
comments. The Python interpreter doesn't output comments. To write a comment, you use a pound sign. I like to call this a
hashtag. My comment will be this is my first Python program. 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. It's really good. 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. 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. So to demonstrate this, I'm going to print my first name
variable. 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 hello, whatever your first name is. In my case,
bro. Let's create another variable. Let's say we have a variable of food. Food equals think of your
favorite food. For me, I will type pizza. Let's print the
following. You like add a placeholder. Again, I'm using an F string. Our variable of food. Hello,
bro. You like pizza. Let's create an email. Use your own email or make up
one. Let's say my email is [email protected]. Then let's print our
email. Your email is add a placeholder. Display our email variable. Your email is
[email protected]. So these are strings. I'm going to add a comment that these are strings. 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. Let me zoom in a little. 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. Let's say you are add a
placeholder display our age variable years old. You are 25 years old.
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. You are
buying. Add a placeholder. display our quantity
items. You are 25 years old. You are buying three items. 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. Then we will print your class has add a
placeholder students. We will display the number of students. Num of students. Your class has 30
students. 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 floatingoint 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. Let's print our price. Print. I'll use an F string. The price is add a placeholder. display our
price. The price is $10.99. Let's preede our placeholder with a unit of currency. I'll pick
American dollars, but feel free to pick something else. The price is $10.99. So, floats contain a decimal
portion. What about a grade point average GPA? Let's say my GPA is 3.2.
Then I will print your GPA is display our GPA. Your GPA is
3.2. What about a distance? A distance can contain a decimal portion. 5.5 kilometers maybe.
Then I will print you ran. Add a placeholder. Display our distance. Then I'll add km
for kilometers. Or you could add mi for miles, but I'll stick with kilome. You rand 5.5
km. Okay. Then we have booleans. A boolean is either true or false. Let's say we're a student. is
student equals. 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. Booleans only have
two options, true or false. So, let's say that I am a student. Then I will
print are you a student? Then we will display our boolean value of is
student. Are you a student? That is true. 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. You may see if is student. If this variable is true, then we will
print the following. Now, we don't need to use an string. We're not going to insert any
variables. You are a student. If this were false, we can add an else clause where we will
print you are not a student. Our variable of is student is true. We will print the if statement.
You are a student. If this were false, we will print whatever is within else. You are not a student. Let's think
of a few more examples. Is something for sale like a car or a product of some sort? Let's say
that is true. I'll write another if statement. If for sale, if this variable contains true, we will do the following.
Let's print that item is for sale. Else if it's false, we will print
something else. That item is not available. For sale is set to
true. This variable is true. We will print that item is for sale. else if it were
false we print that item is not available. One more example. Let's say we have a
boolean variable of is online. Is somebody online? I will set that to true. If is online. If that's true, we
will print you are online. Else we will print you are
offline. Is online is set to true. We will print you are online. else if it were false we print you're
offline. 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. And well everybody, those are variables in
Python. All right everybody, so we are moving on to type casting. Typ 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 minus
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. Get the
type of our name variable, then print it. So our name variable is a string
str. Our age variable is an integer and 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. Use the int function to type cast to an integer. Then pass in my GPA. At the end, we will print our
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 floatingoint number. We will reassign
our variable of age. Use the type cast function a float. Then insert our age
variable. Let's print our age variable. And it should be a floating point number
25.0. Now we'll cover strings. Let's type cast our age to be a string. age equals call the type cast function of
string str pass in our age variable. 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.
Age plus equals 1. Well, we would get a type error. Can only concatenate strings, not integers
to a string. 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. Well, since we're working with strings
now, the result would be 251. I am 251 years old. So strings and numbers behave
differently. With numbers, we can use them within arithmetic expressions. Strings, not so much. We will take our
name variable and type cast it to a boolean. name equals call the typcast function of
bool pass in our name variable. 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. And well everybody that is type casting in Python. 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 enter 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, "What is your
name?" Let's try this again. 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. Let's create a
variable of name. Name equals our user input. Then once we have our name, let's print a message. I'll use an fstring. We
will print hello. Add a placeholder. Then insert our name variable within that
placeholder. Let's try this. What is your name? Type in your name. Hit enter. Hello. Whatever your
name is. Let's try a different name. I will pick Spongebob. Many people are familiar with Spongebob. 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. How old are you? Once we have our age variable, let's
print I'll use an f string. You are add a placeholder our variable age years
old. What is your name? Type in your name. How old are you? Let's say that I'm
25. Hello. Whatever your name is, you are whatever your age is. Years old. 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 age equals age +
one. But there's one problem with this. Type in a name. How old are you? Type in an
age. And we have a problem. We have a type error. Can only concatenate strings, not integers, to
strings. 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 age equals our age after we
type cast it then increment it by one. So type in your name type in an
age and we get this message hello your name happy birthday you are whatever your age is years
old. 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. Type in your name, type in an age, and this works the
same. And it takes less 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 enter the
length. Let's do this with width. I'll just copy and paste what we have. Width equals enter the
width. 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 area equals our length variable. Now to use multiplication you use an asterisk.
We'll discuss different arithmetic operators in the next lesson. So we have length time width. That is the
area. I'm going to print our area because I need to test something. Enter the length. Let's say five 5 in 5 cm.
Doesn't matter. Enter the width. six, we get a type error. Can't multiply sequence by non-int non- integer of type
string. 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 width. Okay, let's try this again. Let's say 5 * 6. The area that's returned to
us is 30. 30.0. This result contains a decimal. It's a floating point number, a
float. So when we print the area, I'll use an f string this time. The area is I'll add a placeholder. Display our area
variable. Let's add a unit of measurement afterwards. I'll pick centimeters. Now, since we're working
with areas, if we would like to technically be accurate. So, we could say to the power of two or we could add
a superscript. So, if you would like superscript 2 and you're on Windows, make sure num lock is on, hold alt, then
type on the numpad 0178. So, we have a superscript of two. Again, it's not really necessary for
this lesson. I just think it'd be cool to include it because then it's technically
accurate. All right, let's say that the length is 6.1 and the width is 7.2.
The area is 43.92 cm squared because we're working with areas. Let's cover a second
exercise. This time we will create a shopping cart program. Exercise two, we're going to create a shopping cart
program. We need three variables. An item, a price, and a quantity of those items. We will create a variable of
item. We will accept some user input. What item would you like to buy? What are we trying to purchase?
We'll keep the data type of the user input as a string. Then we need a price. What is
the price of each item we're buying? Use the input function. What is the
price? A price should be a floatingoint number. For example, we might have dollars and cents. We need a decimal. So
let's type cast our input as a float. Then a quantity. We will accept some user
input. Our prompt will be how many would you like? Quantities. They should be whole
numbers. Let's type cast our input as an integer. Then we will have a total. What's the total that we have to pay?
So, let's take the price of each item. Use an asterisk for multiply our quantity. Then, let's do a test run.
Let's print our total. What item would you like to buy? Let's say a pizza. What is the price?
$10.99. How many would you like? I would like five pizzas. and our total is
54.95. Let's say that before we display the total, let's print the following. I'll use an F string. You have
bought insert a placeholder. Display our quantity X item or items. I'll add slash
S. Then we will print I'll use an F string again. Your total
is display our total. What item would you like to buy? I would like to buy a pizza. What is the
price? $10.99. How many would you like? I would like nine pizzas. They're all for me.
I'm going to eat all of them. You have bought 9 x pizzas. Your total is 98.91.
Let's add a unit of currency before this. Pick unit of currency before displaying the total. I'll pick American
dollars. I would like to buy pizza. What is the price? $9.99. How many would you like? I would
like a dozen pizzas. 12. You have bought 12 x pizzas. Your total is
$119.88. All right, everybody. That is how to accept user input in Python. And we've covered a few exercises. In the
next topic, we're going to create a Mad Libs game. And that is how to accept user input in
Python. All right, everybody. In this video, we're going to create a game of Mad Libs. Not because we have to, but
because I want to. It would be a good exercise for us, just so we're more comfortable with accepting user input.
If you're not familiar with Mad Libs, Mad Libs is a word game where you create a story by filling in the blanks with
random words. So, we're going to create a story template. The story is going to be missing some components. We will fill
in those components with random words that we type in. Here's a story that I've written myself. Print. Use an F
string. Today, I went to a insert a placeholder zoo. For our placeholder, we'll insert an
adjective. We'll insert a variable named adjective. Adjective. Adjective one. You're going to get an English lesson
today, too. An adjective is a description of something. So, for our zoo, adjective one could be
expensive, large, dirty. An adjective describe something. We'll fill this in when we
accept user input. For our second print statement, let's print the
following. In an exhibit, I saw a placeholder. We'll include a noun. Noun one. A noun is a
person, place, or thing in English. Maybe a gorilla. A gorilla named Harambe, for
example. Print. Use an F string. Let's say our noun one whatever this is we can reuse
variables was we will create a second adjective adjective 2 we will be describing
whatever noun one is this person place or thing and we will insert a verb verb one a verb is an action such as running
or eating. Then for our last statement, let's print I was add a placeholder. We'll create adjective
three. Adjective 3 will describe us. Now we're going to fill in these variables by accepting user input. We're going to
fill in adjective one. We'll accept user input using the input
function. Enter an adjective. I'm going to add a reminder that an adjective is a description of
something. Then we need noun one. Noun one equals input. Enter a noun. A noun is a person,
place, or thing. Then we have adjective two. I'll just copy adjective one. Paste it.
Change one to two. Then a verb. Verb one equals input. Enter a verb. I want verb one to
be in current tense. I'll ask the user to end the verb with ing. Enter a verb ending with
ing. Then it's current tense. our person, place, or thing of noun one is currently doing something such as
eating. And then adjective three. And I'll just copy one of these adjectives. Adjective 3 equals input.
Enter an adjective. Okay. And then we are ready to run this. Enter an adjective. An adjective describes
something. I will say suspicious or some kids like to say sussy or sus even. I've also heard of
kids nowadays using the word skipy. Feel free to type in whatever you would like. It is your story after all. I'm going to
say suspicious. Enter a noun, a person, place, or thing. I like to poke fun at
Mark Zuckerberg. So, I'm going to say my person is Mark
Zuckerberg. Enter an adjective. That is a description. Angry. Enter a verb ending with ing. So,
it's current tense. Uh, screeching. Enter an adjective. Happy. Here's my story. Today I went to
a suspicious zoo in an exhibit. I saw a Mark Zuckerberg. Mark Zuckerberg was angry
and screeching. I was happy. That's our game of Mad Libs. It's a word game where you create a story by filling in the
blanks with random words. Also, post the output of your Mad Libs game in the comment section down below because I
really want to read them. I want to see what you guys came up with. And well everybody, that is a Mad Libs game using
Python. Hey everybody, in this video I'm going to show you all of the different math that we'll need throughout the rest
of the series. I have a lot to cover and I'll split this video into different sections. We'll cover some basic
arithmetic operators, built-in math functions, a few functions from the math module, and then a few exercises. Be
sure to look at the timestamps if you would like to skip ahead to another section. Let's begin with some really
easy stuff. We're going to cover some basic arithmetic operators. Let's say we have a variable
friends. Currently, you have zero friends. If you need to increment a variable by one, you could say friends,
the name of the variable equals the name of the variable again + 1. So, the plus sign is the addition operator. And I
think we do have a little bit of experience with that already. So if I were to print my variable
friends, guess what? You now have one friend. We could also shorten this line of
code. You could say friends plus equals 1. That would do the same thing. This is known as an augmented assignment
operator. That will give you the same result. I prefer to use augmented assignment operators just because they
take less text and I think they're easier to read. Now let's use subtraction. Friends equals
friends minus 2. So of course minus is the subtraction operator. Uh you have -2 friends. I guess if you were to use the
augmented assignment operator that would be friends minus equals 2. There you still have -2 friends.
Okay. Multiplication. Let's change friends to how about five. Friends equals
friends time 3. You now have 15 friends. Then the augmented assignment operator version of
this would be friends time= 3. So again you have 15 friends. Let's cover
division. Friends equals friends divided by two. So we have 2.5 friends. Somebody
was cut in half. We have half a friend. Maybe it's just their legs or torso or something. Then the augmented assignment
operator would be friends / equals 2. And the result is still the same.
Now exponents friends equals friends to the power of two. So friends is currently five. Friends to the power of
two would be 5 * 5 which is 25. The augmented assignment operator version of this equation would be
friends exponent equals 2 and again friends is 25. Then we have modulus. Modulus gives
you the remainder of any division. Suppose we have 10 friends instead of five. I will assign a new variable
remainder. Remainder equals friends. The percent sign is known as the modulus operator. It will give us the remainder
of any division. If I were to divide my group of friends by three, we will have one remaining. I'll store the remainder
within a separate variable. We would have a remainder of one. It's kind of like in class when the teacher says for
everybody in the class to go into groups of three, then there's always that one kid that's by themselves. That's kind of
the same concept. We're dividing our friends into groups of three. then the modulus will give you the remainder. If
we divided our group of friends into groups of two, well 10 divides by two evenly, so there is no remainder. So
that is the modulus operator. It's fairly popular to use this operator to find if a number is even or odd because
it will divide by two evenly if that number is even. If the remainder is one, that means that the original number is
odd. Okay, so yeah, those are some basic arithmetic operators. addition, subtraction, multiplication, division,
exponentiation, then modulus. Now what we're going to do is cover some built-in math related
functions. Suppose we have three variables x= 3.14, y =
4, z = 5. It doesn't matter if these are floating point numbers or whole integers. The first is the round
function. We have a variable named result. I'm going to round x. So there is a built-in round
function. After the set of parenthesis, we can add some value or variable to be rounded. So we will round x to the
nearest whole integer. Then print the result. So our result is three. So that's the round
function. With the absolute value function, we can find the absolute value of a number. Uh let's change y to be -4
instead of four. We'll take result equals abs which means absolute value of y. The absolute
value is the distance away from zero as a whole number. The absolute value of -4 is
4. Let's change y back to four. There's a built-in power function. result equals
pow. Then we'll need a base and an exponent. What's y to the power of 3? That would be 4 * 4 * 4, which is 64.
That's the power function. You can raise a base to a given power. The next two are really useful.
Using the max function, we can find the maximum value of various values. What's the maximum value between x, y, and z?
Then I'll just need to store this value. Uh results equals the max between x, y, and z. Well, the maximum value is
five. Otherwise, there's min. What's the minimum value between X, Y, and Z? That would be
3.14. Now, in this next section, we do have some very useful constants and functions from the math class, but we'll
need to import the math module at the top of our text editor. So, import math. If you need the value of pi, you'll type
the name of the math module.py. And I'm just going to print this. print
math.py. The value of pi is 3.14159 and a bunch of digits that come after. If you're working with physics, I
do know that people use the constant e a lot. We won't be using e in this video series, but if you ever need access to
it, just type math. E, and that will give you e, which is 2.71 something something something. I believe e is
known as the exponential constant. If you need the square root of a number, let's say result
equals math. SQRT, we can place a variable or a value within the square root function. Uh
let's say we have x again. x= 9. What is the square root of x? Then I will print whatever the result
is. The square root of 9 is three. That is the square root function. There's a ceiling function.
Result equals math dot seal. Seal will always round a floatingoint number up. Suppose x is
9.1. So 9.1 rounded up is 10. Otherwise there's floor which will always round a number down. result
equals math.f floor. Let's change x to 9.9. 9.9 rounded down is 9. Those are some useful math functions. Let's go
over some exercises. Okay, this first exercise we are going to calculate the circumference
of a circle. We'll need the help of the math module because there's some good functions in there. To calculate the
circumference of a circle, the formula is 2 *<unk> * r. Let's ask a user for a radius because that's what r is. We'll
accept some user input. Enter the radius of a circle. We will type cast the input as a
floatingoint number to calculate the circumference. Again the equation is 2 * pi. We can get
that from the math module times whatever the radius is. And the user is going to type that in. Then we will print
whatever the circumference is. Print. We'll use an fstring the
circumference is our variable circumference. Enter the radius of a circle. I'll enter
10, actually 10.5. Their circumference is 65.97. If you want to round and truncate
some of these numbers, we can use the round function. Round circumference, then round to a given
decimal place. I'll round to two digits. Again, 10.5 rounded is 65.97. You could add a unit of
measurement, too. Let's say centimeters 10.5 is 65.97 cm. All right, that is the first
exercise. For this next exercise, let's calculate the area of a circle. We'll import the math
module. We'll ask for a radius. Much like before, radius equals input. Enter the radius of a circle.
We'll cast our input as a floatingoint number. The equation for the area of a circle
is pi time radius squared. We could easily use the built-in power function to raise
our radius to the power of two. Then we will display the area. print. I'm using an F string. The
area of the circle is our area to some unit of measurement. Let's say centime
squared. Enter the radius of a circle 10.5. The area of the circle is 346.36. But I would like to round this
number to two decimal places. I'll use that round function and I'll place area and the
number of digits to round to within this function. Let's try that again. 10.5. The area of the circle is
346.36 cm squared. That is the second exercise. For this last program, we're going to find the hypotenuse of a right
triangle. The formula to calculate the hypotenuse of a right angle triangle is C equ= the square<unk> of A^2 + B^2.
We'll begin by importing the math module. We'll ask the user for the lengths of side A and
B. A equals input. Enter side
A. We'll cast the input as a floatingoint number. We'll do the same thing with
side B. B equals enter side
B. Now this part's going to be confusing. We'll calculate C. We'll need A^2 + B ^ 2. We'll take A to the^ of 2
plus B to the^ of 2. Then we'll need the square root of all of this. Whatever the result is, I
will surround this equation with math. Square root and that should give us our answer. Let's
print using an F string. Side C equals whatever C
is. So, enter side A three. Side B will be four. side C is five. All right, everybody. So, that was everything
related to some arithmetic operators and math related functions in Python. And in the next video, we're going to cover a
few things involving string [Music] formatting. Hey everybody, in this topic
I'm going to explain if statements. An if statement is used to do some code only if some condition we set is true.
Else we could do something else. It's a basic form of decision-m. If it's true, we do something. If it's not true, we
don't do it. Let's ask a user for their age. Age equals input. Enter your age. I will type cast
the input as an integer. Depending on what the user's age is, we can do one of a few things.
Let's pretend that the user would like to sign up for a credit card, but in order to do so, their age needs to be
greater than or equal to 18. Well, we can check that. To use an if statement, type if, then some condition. What would
we like to check? Let's check to see if the user's age is greater than or equal to 18. Then add a colon, then hit enter.
Any code underneath the if statement should be indented. Make sure to pay attention to that because that's easy to
miss. If the user's age is greater than or equal to 18, let's print you are now signed
up. If I were to run this code, I'll type in my age. I'll type 21. Hit enter. This statement is true. Therefore, we
will execute any code found within the if statement. You are now signed up. What if this condition was not
true? Let's say my age is 13. Well, nothing happens. If the condition we check is instead false, we skip over
this code. If you need to take a different course of action, you could add an else
statement. If this is true, do this. Else, we can do something else. Let's print a different
message. You must be 18 plus to sign up. I'll type in my age again. I'll say that I'm 13. Hit enter. You must be 18
plus to sign up. That's basically an if statement. Do some code only if some condition is true. Else you can do
something else entirely. It's a basic form of decisionm. The else statement is kind of like a last resort. We can check
more than one condition before reaching the else statement. We can add an else if statement which we just shortened to
e l i if meaning else if. else if let's check if age is less than zero then we'll print a different
message you haven't been born yet. Now if I run this code I'll say that my age is negative one.
This condition is false. We skip this code. This condition is true. Therefore, we will execute this code and we skip
the else statement. You haven't been born yet. Let's add another else if statement. You can add as many else if
statements as you want. Let's check to see if somebody's age is greater than or equal to 100. We'll print a different
message. Let's print you are too old to sign up. If I were to say my age is 111 years
old, well, it states you are now signed up. The reason that we didn't reach this part of our else if statement. That's
because this condition is still technically true. You do need to pay attention to your order of if and else
if statements. If I want to be sure that nobody over 100 is signing up, I should probably move this to the
beginning. If age is greater than or equal to 100, then else if age is greater than or equal to 18, we'll do
something else. Enter your age. I am 111 years old. You are too old to sign up. So
those are if statements. If some condition is true, do something. else if you can check something else. If no
above conditions are true, you could do something else entirely. It's kind of like the default. Here's another
example. We'll ask a user if they would like some food. Response equals input. Would you like
food? We'll have the user type in Y for yes or N for no. If our
response now to check to see if two values are equal, you would use double equals. If the response is equal to y,
then we will print have some food. The doubles equal sign is the
comparison operator. It will check to see if two values are equal. You don't want one equals because that's the
assignment operator. Python in this case thinks we're attempting to assign the character y to response. So for
comparisons use double equals else we can print no food for
you. So would you like food? I'll type y. Have some food. Let's try it again. I'll type no
and for no. No food for you. Here's a third example. We'll have a user type in their name. Name equals
input. Enter your name. If our name is equal to an empty string, that means they didn't type in
anything. So, let's yell at the user. You did not type in your name. Else we will print using an
fstring hello whatever the name is. Enter your name. I'm just going to hit enter. You did not type in your
name. Let's run this again. I'll type in my name. And we have executed the else
statement this time. Hello bro. So one important thing that you should know is the use of booleans with
if statements. Suppose we have some boolean variable named for sale. I'll set this to be true. Now using an if
statement you can just use the boolean variable in place of a condition because a condition would evaluate to be true or
false. We could just say if for sale if that's true then let's
print this item is for sale. Else we will print. This item is not for sale. For
sale is set to be true. This item is for sale. If this variable were
false, well then the item is not for sale. Let's try a different variable. How about
online? If online, the user is online. Else the
user is offline. So the user is offline. I'll change the boolean to
true. the user is online. So with if statements, you can either write a condition or you could
use a boolean. All right, everybody. So those are if statements. Do some code only if
some condition is true. Else you can do something else. It's a basic form of decision-m and those are if statements
in Python. Hey everybody, this is a remake of my Python calculator program for
absolute beginners. All you need to know to complete this exercise is just if statements and how they work. So let's
get started. For this exercise, a user is going to select an arithmetic operator. Operator equals input. We will
ask the user to enter an operator. This will be plus for addition, minus for subtraction,
asterisk for multiplication, and a forward slash for division. You could enter more than this, but I don't want
to make this exercise too complicated. We will create a variable of num one to contain our first number. Let's say we
would like to add two numbers together. What is the first number going to be? Enter the first
number. And let's do this with the second number. Num two. Enter the second
number. Let me show you something. I'm going to add num one and num two together. Num one plus num two. We'll do
a test run. Enter an operator. I would like to use addition. Enter the first number 10
and 11. Well, the result is 1,1. When we accept user input, they are string data types. What we've ended up
doing is string concatenation. We've concatenated the string of 11 to 10. That's why we ended up with 1,1. We'll
have to convert these two strings to be floating point numbers by type casting them as a
float. So enclose your input functions with a type cast a float. And now we should be able to add those two numbers
together. So let's add 10 and 11 and we get 21.0. 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. And 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. And for now, I'll write pass.
Else if operator is equal to an asterisk for multiplication, we will multiply. Else if our operator is equal
to a forward slash for division, we will divide. If our operator is addition, let's create a variable of
result. Result equals num 1 + num 2. For subtraction, it's going to be num 1
minus num 2. Multiplication would be num 1 * num 2. Then division would be num 1 / num 2.
Then we just have to print the result. Print our result. Be sure to do this with each of
the else if statements as well. And let's see what we have. Let's add 5.5 +
6.9. That gives us 12.4. Let's subtract
420 minus 0.69. That gives us 419.31. Let's test
multiplication. Multiply 3.14 times 3.14, which gives us 9.8596.
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. And we'll just update each of these print
statements. This will round to the nearest whole integer. So let's divide 420 by
13. Let's say that we would like three digits after the decimal. Within the round function, we could add comma 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 fring. Let's say that the operator that the
user has selected is not valid. And let's try this again. Enter an operator pizza.
Enter the first number 420 and 69. Pizza is not valid. Let's say is not a valid operator instead. That makes
more sense. Pizza will be my operator. First number is 420. Second number is
69. Pizza is not a valid operator. 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 kilog or kilog to pound. The user is going to decide. We will begin by creating a weight variable. We will
assign some user input. Enter your weight. We will convert this input into
a floatingoint number. So add that cast. Then we will ask for a unit. Is this weight in
kilogram or pounds? Input kilogram
or pounds. We want the user to type in either K for kilogram or L for pounds. And 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.
Let's reassign weight equal to our weight times
2.205. Else if unit is equal to L, we need to convert to kilogram. Weight equals weight divided
by 2.205. Else the user did not type in something that was valid. Let's
print using an fstring unit was not
valid. At the end of our program, we will print the new weight. I'll use an fstring. Your weight
is our new weight after it's reassigned. 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. Else if unit equals kgs for kilogram in our results, we will display our new unit. Let's take a look. Enter
your weight. Actually, I'm just going to make one change. I'm going to add colon space there. That's much better.
Enter your weight. Let's say I'm 180 lb. This is in pounds. I'll type capital L. Your weight
in kilog is 81.63. I think I'm going to round this. I will enclose the weight variable
within a round function. We will round to one decimal place. Let's try this again. Enter your
weight. Maybe I'm 81 kg. I'll type k for kilogram. Your weight is 178.6 lb. Let's make sure
that this else statement works, too. Enter your weight. 180
pizzas. Pizzas was not valid. 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. Then, paste each within the if and else if
statements. When we exit the else statement, we're not printing the output. So, let's make sure that this
works. Enter your weight. I am 180 pizzas. Pizza was not valid. 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. We'll begin by asking what the current unit of
measurement is. Unit equals will accept some user input. Is this
temperature in Celsius or Fahrenheit?
C slashF then we will ask for the temperature. I'll store the temperature
in a variable named temp meaning temperature. temp equals input enter
the temperature. Then we should cast our user input as a floatingoint
number. If unit is equal to C, I'll fill this in momentarily. I'm just going to write pass as a
placeholder. Else if unit is equal to F, we will do something else. Else, let's print something. Just
an error message of some sort using an F string. unit
is an invalid unit of measurement. Let's test this else statement. Is the temperature in Celsius
or Fahrenheit? What if I were to type K for Kelvin? I'll make up some temperature like 100. K is an invalid
unit of measurement. All right, we know the else statement works. Let's convert Fahrenheit to Celsius using this
formula. We will take our temperature equals 9 * our
temp / 5 + 32. I'll take all of this and use the
round function. We'll round to one decimal place. Then we will print the current
temperature in Fahrenheit. I'll use an F string. The
Temperature in Fahrenheit is our temp
variable degrees Fahrenheit. Let's test this if statement. Is the temperature in Celsius
or Fahrenheit? It is currently in Celsius. What is 33° in Celsius converted to
Fahrenheit? The temperature in Fahrenheit is 91.4°. All right, so this section is working.
Let's work on the else statement. Else, if our unit is currently in Fahrenheit, we'll convert to
Celsius. That formula is temp equals our temperature minus 32 * 5 /
9. Then I will round the result to one decimal place. Then we'll print the temperature in
Celsius. The temperature in Celsius is temp° C for Celsius. Is the temperature in Celsius
or Fahrenheit? It is currently in Fahrenheit. Enter the temperature. 91.4. The temperature in Celsius is
33.0°. Well everybody that is a simple temperature conversion program in
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 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. And 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. We'll write an if statement to check that. If our
temp short for temperature is greater than let's say 35 35° C then I'll use the or logical operator or if our temp
is less than zero or if is raining is true. If one of these conditions is
true, we're going to cancel our outdoor event. So let's print the following. The outdoor event is
cancelled. Else we will print something else. The outdoor event is still
scheduled. The temperature is reasonable and is raining is false. It's not raining. So we print the else clause.
The outdoor event is still scheduled. What if the temperature was really hot, like
36°? Well, the outdoor event is cancelled. What if it's cold? -5°. The outdoor event is canled. This
condition was true. Therefore, we execute the if statement. Or what if the temperature is reasonable, but it's
raining? Is raining is true. Well, then the outdoor event is still canled. 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. So 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 it sunny. Is
sunny if it's hot and if it's sunny. If this is true, let's print the following. It is hot
outside. For fun, I'm going to add an emoji, but you don't have to. I just think it's more entertaining that way,
but you do you. And I will print it is sunny. Sometimes these emojis are
formatted differently. I'm just going to copy it from somewhere else. That's better. Currently, the temperature is 25
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 and it is sunny. Let's write a few more. Let's add else
if. Else if the temp is less than or equal to zero and is
sunny. We will print something else. It is cold outside. I'll change the
emoji and it is sunny. Let's set the temperature to be5°.
It is cold outside and it is sunny. Both these conditions are true. So we do this
instead. You can link as many conditions together as you would like. Let's see if our temperature is within a certain
range. Else if temp is less than 28 and our temp is greater than zero and is sunny. to check to see if something is
within a certain range. There is a shortcut too. PyCharm is recommending this. We can simplify chain
comparisons. So this effectively does the same thing. If 28 is greater than our temp and our temp is greater than
zero and it's sunny, then we will print it is warm outside rather than hot. and it's still sunny. So, let's say
our temperature is 20° C and it's sunny. It is warm outside and it is sunny. 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. So, let's
check to see if it's not sunny. Really, I'll just copy what we have and paste it.
else if not is sunny then that means it's cloudy and let's use a cloud
emoji. So basically not does the opposite of what you're looking for. We are checking if not is sunny. Is sunny
is false. Then this condition is true. Okay. Let's say our temp is 28. Is sunny is now
false. It is hot outside. It is cloudy. What if our temperature was zero? It is cold outside. It is cloudy.
What if the temperature was reasonable like 20°? It is warm outside. It is cloudy. So not
it 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. With or, at least one condition must be true.
With and, both conditions must be true. And not. Not does the opposite. It inverts the condition. We check if
something is not false or not true. And well everybody, those are logical operators in
Python. Hey everybody. So today I got to explain conditional expressions in Python. A conditional expression is a
oneline shortcut for using an if else statement. If you're familiar with other programming languages, this is also
known as the trinary operator. It behaves similarly. Using conditional expressions, we can print or assign one
of two values based on a condition. Here's the formula. Return X if our condition is true. Else return Y. Here's
a basic example. 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. I'll just copy and paste
it. Let's check to see if our number is positive. Let's print the text positive if our condition. What are we checking?
Let's check to see if num is greater than zero. That means it's positive. If this condition is false, we will instead
print whatever comes after else. Else negative number is five, that will print positive. If our number was neg 5,
well, this condition would be false. We would instead print negative. Let's go over another. Let's check to see if our
number is even or odd. Let's set num to be six. This time I will assign the result
to a variable. Our result equals take our formula. Let's
assign even if our num modulus 2 is our number divisible by
two. Does that equal zero? Else return odd. Then let's print our result. R
result number is six that is even. If it's five then it's odd. assign even if our number is divisible
by two. Else return odd. Let's create variables A and B. A will equal 6. B will equal
7. Let's create a variable of max num equals. Follow our formula again. return variable a if a is greater than b
else return b between a and b which is the maximum number that would be b of seven let's find the minimum this
time min num a if a is less than b else return b the minimum number between 6 and 7 is
This time we'll take an age. Age equals 25. We will create a variable of status equals. Use our formula
again. Return a string of adult. If our age is greater than or equal to 18. Else return a string of child. Then we will
print our status. Our age is 25. that's greater than or equal to 18, 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. Temperature equals 30°
C. So that's hot. Let's create a variable of weather. assign a string of hot if our
temperature is greater than 20. Else we will return a string of cold. What's the weather outside today? Based on the
temperature it is hot. If our temperature was 20 then the weather is cold. Okay, last
example. We will work with a user role. I will set this to be admin. We will define a variable of access
level equals again follow our formula return the text of full access
if our condition of user ro is equal to a string of admin else we will return limited
access. Our user role is an admin. Let's print our access level and we have full access. But what if we were a
guest? Well, then we have limited access. All right, everybody. Those are conditional expressions. They're a
oneline shortcut for the if else statement. It's similar to the turnary 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. As we know a string is just a series of characters. Let's ask a user for their full name.
Name equals input enter your full name. The first method I'll show you
well technically this is a function. The length 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. Uh let's just say result. Then I will print whatever the result
is. Why don't you go ahead and type in your full name. 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 length 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. Let's find any spaces. I'll store the result within a variable
named 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 in place of four. Let's
find the first occurrence of a capital B. See, it's zero. How about O? For me, that would be two. So
remember, it's always the first occurrence. If you need the last occurrence, there is a different
method, which is R find. R meaning reverse. We will find the last occurrence of an
O that has a position of five. 0 1 2 3 4 5. If Python isn't able to locate a given character, it will return negative
1. Let's find any I don't know uh Q's. Python could not find any lowercase Q's. The rfind method will return
negative 1 if there are no results. We can capitalize the first letter in a string by using the capitalize function.
Name dot capitalize. 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. Follow your variable that contains a string followed byupper. Then I will reassign the result
to my name variable to overwrite it. Enter your full name. All of the letters are now
uppercase. There is also lower to make all of the characters lowerase. Name equals name dot
lower. Yep. All the characters are lowercase. Now the is digit 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. So if I were to type in my full name, is digit 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. I'll just type in 1 2 3. See that's true. That is the isdigit method. Otherwise, we have is alpha name
is alpha. The is alpha method will return a boolean true or false depending if a
string contains only alphabetical characters. I'll type in my full name. 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. Is alpha would also return false if my name contained any sort of digits.
Bro 1 2 3. And that is also false. That is the is alpha method. Now let's ask for a phone
number. Phone number equals input. Enter your phone number. With the phone number, they
typically contain dashes. Let's count how many dashes are going to be in somebody's phone
number. Phone number dot count method. Let's count the amount
of dashes. So, place a character within the count method. This method will return an integer. Let's store that
within a variable. Result equals phone number. Method. So, type in some phone
number. 1-23 4-56- 8901. We have three dashes within the
string. 1 2 3. That is the count method. We can count how many characters are within a
string. We also have the replace method. Honestly, the replace method is probably one of the most useful methods of
strings. We can replace any occurrence with one character with another. Replace. Let's replace any
dashes with maybe a space. This method will return a new string. I'm going to reassign this to our phone number
variable. Then print the phone number. Enter your phone number.
1-234-567-8901. 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.
1-234-567-8901. Here's our new phone number without any dashes. We've replaced all dashes with an empty
string, no characters. If you would like a comprehensive list of all of the string methods available to you, you can
use the help function. Type in the data type string string. Then I will print whatever the result
is. Here's a bunch of methods you might be interested in in the future. Capitalize,
case, fold, center, count, encode, ends with, just to name a few. All right, everybody. Here's an exercise for you.
We will validate some user input. We would like a user to enter in a valid username. However, there's a couple of
rules. The username can be no more than 12 characters long. The username must not contain any spaces and the username
must not contain any digits. Let's assign a variable named username equals
input. Enter a user name. First, let's check to see if our user input is more than 12 characters
long. We can do that using the length function. we will find the length of our username. The length function returns an
integer. Let's check to see if the length of our username is greater than 12 characters. If it is, we'll print a
message. Your username can't be more than 12 characters.
else we will print using an fstring welcome whatever our username variable
is. Let's try it. I'll type in my first name, last name, then add a whole bunch of characters
afterwards. Your username can't be more than 12 characters. Let's type in something
that's under 12 characters. Yep. And that appears to work. Okay, so we have accomplished task
number one. Our username can't be more than 12 characters. Next, our username must not contain any
spaces. We can use the find method of a string. Username.find. We will find any spaces.
That's a character. If no spaces are found, this method will return -1. Using an else if
statement I'll add not if the find method of username
equals1. If the result is not -1 meaning we found a space we will print your username can't contain
spaces. I'll type in my first and last name. You might need to think of something that's underneath 12
characters. Your username can't contain spaces. So, we have accomplished rule number two. Three. Username must not
contain digits. We can use the is alpha method of
strings. The is alpha method returns a boolean if a string only contains alphabetical characters. So, let's copy
that. I'll add another else if statement not username is alpha. Then we will
print your username can't contain numbers. I guess
technically is alpha would check for spaces too, but I'd rather have that be handled within a different if statement.
All right, I'll type in a username. I'll include some digits. Your username can't contain
numbers. All right, I think we've accomplished this. Let me make up a username following these three rules.
Yep, it seems to check out. All right, everybody. And that is a few useful string methods that you may be
interested in. Hey everybody. In this topic, I'm going to explain string indexing.
Indexing allows us to access the elements of a sequence using a set of square brackets, also known as the
indexing operator. Using this set of square brackets, following a string, there are up to three fields that we can
fill in. We can access a starting point in the string, an ending point, and a step. Here's an example. Suppose we have
a credit card number. credit number equals and I'll just make up some number 1 2 3
4-5678-9012 dash 3456. Good enough. If I need the first character within the string, I can type the name of my string
variable followed by the indexing operator which is a set of square brackets. The first position has an
index of zero. Computers always start with zero. So that's why the first index is zero. Then I'm going to go ahead and
print this. Print credit card number at index of zero. That would be one. If I were to
change the index to be one, 0 1, that should be two. Index two would technically be
three. Then four is the dash within our string. As you can see here with the indexing operator, there's up to three
fields that we can fill in a start, end, and a step. If you have just one field listed without any colons, it's assumed
you're filling in the starting position. So now, what if you would like the first four digits of the
string? Well, we would type the name of our string variable indexing operator.
We'll need a starting index colon then an ending index. The first four digits would be zero colon 4.
Then I will print this. And I'm just going to turn this first line into a
comment. Yeah, there we go. We have the first four digits of our credit card number. 1 2 3 4. Just so you know, with
the ending index, this index is exclusive. This first number would be zero 1 2 3 4. So we did not include that
dash within the number. The starting index is inclusive. The ending index is exclusive. So you can omit the zero in
the beginning. You could just say colon 4. Python assumes the starting position will be the beginning of the string. So
that would work too. Let's get the next set of digits. 5678 credit number indexing operator.
Let's find where the starting index would be. 0 1 2 3 4 5 5 colon 6 7 8 9. Then we will print whatever is
here. The next set of digits is 5 6 7 8. Maybe we need the last 12 digits. Well, what we could do in that case, we will
take our string variable credit number. Set the starting index to be let's see 0 1 2 3 4
5 5 colon. If you need everything up to the end of the string, you don't need to list an ending index. Just be sure to
add that colon. Python then assumes you need everything up to the end of the string. So, I will print whatever we
have. Then we should have everything besides the first four digits. Yep. 5 6 7 8 9 0 1 2 3 4 5
6. You could also use a negative index. Credit number. If you need the last character in a string, you would
set the index to be -1. Then I will print this. Print credit number at index of
-1. That would be six. -2 is five. -3 is
four. -4 is three. And then5 would be that dash right here. Yeah, you can use negative indexes too. Let's talk about
step. Using the step field, we can access the characters in a string by a given step. We can count by twos or we
can count by threes. So here's an example. So let's take our credit number. If we're not filling in these
starting or ending fields, but we need a step, we would need two colons. Then Python is assuming everything from the
beginning of the string to the end. Then our step will be two. This will print every second
character within our string. Yeah, here we are. We have 1 3 dash 6 8 9 1 so on and so
forth. If I were to change the step to three, we would count every third character beginning with 1
4 6 dash 1 36. All right, here's a practical
example. Let's create a program to get the last four digits of a credit card number. I'm going to assign this to a
new variable. Last digits equals our credit
number indexing operator. So, we need the last four digits. Where would the starting index begin? Well, we could use
negative indexing. This last digit is -1, -2, -3,4. We will begin at -4 colon. We can omit the ending index.
Python assumes we need the rest of the string. Then really, that's all we need. So, let's
print. I'll use an fstring. Uh maybe some x's. Maybe we're hiding somebody's credit card number
except the last four digits. Okay. then variable last
digits. All right. And here's our credit card number where only the last four digits are visible. Hey, you know what?
Let's add one more exercise. Let's reverse the characters in the string. I'm going to reassign credit
number equals credit number. If we need the entire string, we don't necessarily need a starting index
or an ending index. But for the step, this will be negative. Negative -1 will reverse a string. Then let's print
whatever our new credit card number is. Print credit number. And yeah, there is our credit
number backwards. To reverse a string, you set the step to be -1. So yeah, everybody, that is string indexing in
Python. We can access elements of a sequence using the indexing operator which is a set of straight brackets. You
can list a starting position, ending position and even a step if you need to skip over characters. But yeah, that is
string indexing in Python. Hey everybody, in this topic I'm going to explain format specifiers.
Format specifiers when used in the context of an string, they allow us to format a value based on what flags are
inserted. Following your value, you would type a colon and then some flags. Depending on what flags you insert, it
will format your output a certain way. You could add decimal point precision, allocate space, zero pad values, left
justify, right justify, center align, all sorts of things. Let's have some practice. I'll create
three prices. Price one, price two, price three. Price one will be
3.14159. These values aren't in dollars and cents yet, but they will be. Price two will be
987.65. As you can see, I'm just making up numbers here. Price three is 12.34. Let's display our prices using
some fstrings. Price one is placeholder price 1. Then we will do this for price two
and price three. Price two is price two. Price three is price three. Within our placeholder following the value, we can
add a colon. Then some flags. Those flags are the format specifiers. They will format our value a particular way
depending on what we insert after the colon. To add decimal point precision, you would type after the colon dot then
the amount of decimals to be displayed maybe two then f meaning floatingoint number. Let's do that with price two and
price three colon.2f. Price one is now 3.14. Price 2 is987.65. Price three is
12.34. I think I'm going to add some dollar signs before the placeholder. Yeah, that's much better.
For less precision, maybe one decimal place, you can change the two to a one. So.1
F. Each number only displays one decimal. 0.1 6.3 whereas in 3F would display three
decimal places.142 650.340 even though price 2 and price 3
only have two decimal places in the original numbers we will concatenate some additional zeros to allocate space
to display a value after the colon add some number some number for that many spaces how about
10. Each value now has a total of 10 spaces to display the output. 1 2 3 4 5 6 7 8 9
10. If you were to preede a number with zero, well, these numbers would be zero padded. Each number is now zero padded.
To left justify a value, you would use a left angle bracket. All these numbers are now left
justified. Then we have all of the space after. They're all uniform. Right justify would be a right angle
bracket. And I believe that's the default. Center align I believe is the carrot symbol.
Yep, our numbers are now centered. If you have any positive values and you would like to display a
plus sign, just use plus. Any positive number is preceded with a plus sign. Any negative number is
preceded with the negative sign. Or you could use a space for any positive numbers. So, colon space
These numbers are lined up evenly even though we have a negative number in here. There is a thousand separator
which is a comma. We should probably increase the value of our
prices. 3,00 9,870
1,200. Each thousand's place is now separated with a comma. We could also mix and match flags. I would like a
thousand separator along with decimal point precision of two decimal places. And why not? I will preede each
number with a plus sign if it's positive. Yep, here we are. So based on what you're looking for, you can add
some combination of flags. So yeah, those are format specifiers. everybody. Within your
placeholder, insert your value, a colon, then certain flags based on what you're looking for
exactly. But yeah, those are just a few format specifiers in Python. Hey everybody, in this topic,
I'm going to explain while loops. A while loop will execute some code while some condition remains true. Here's an
example. We'll use an if statement first. We will ask a user for their name. name equals
input. Enter your name. If our name is equal to an empty string, that means the user didn't type
in anything. Let's print a message. You did not enter your name. Else, we will
print using an string, hello, our user's name. If I were to skip this
prompt, we would execute this if statement. Then we continue with the rest of the program. What if I would
like to continually prompt the user to type in their name? We can't continue until they type in something. Well, we
could replace this if statement with a while loop. While this condition is true,
continue to execute this code. within the while loop. I'm going to reprompt the user to type in a
name. Then if we were to exit the while loop, then we will print hello. Whatever your name is. So let's run this. Enter
your name. I'm going to hit enter. You did not enter your name. Enter your name. No. No. No. Okay, I give up. I'll
type in my first name. Hit enter. Hello. Whatever your first name is. while this condition remains true, execute this
code potentially forever until this condition is no longer true. So that's one of the main benefits of a while
loop. If it's not true, then you exit out of the while loop. And that's why we're able to continue then print our
name. Hello name. You do want some way to escape out of the while loop. Otherwise, you'll run into what's known
as an infinite loop. So let's say while name is equal to an empty string, we will print you did not enter your
name. So I'm going to hit enter. So we are stuck in an infinite loop. We can't actually escape this loop. We didn't
give ourselves an exit strategy. That's why previously we reprompted the user to type in
something. We're giving them a chance to escape. In a way, it kind of works like an if statement, but instead of
executing some code once, it's potentially infinite. Here's another example. This time, let's ask for a
user's age. Age equals, and I will convert the input to an integer. Enter your
age. We'll need the user to type in a positive number. While age is less than zero, let's print a message to let the
user know that they can't do that. age can't be negative. Then we need some strategy to escape. Let's reprompt the
user to enter in their age. Once they type in something that's valid, we can escape out of the while
loop. So let's print using an fstring you are age years
old. So enter your age. I'm going to say negative one. Age can't be negative. -21 million. Okay, I give up. How about
21? You are 21 years old. So, that was another example. While our age variable is less than zero, repeat this code
forever. Let's go over example three. I'm going to introduce some logical operators. We will have the user
type in a food they like. food equals input enter a food you like. But in order to escape, they need to press Q to
quit. While food is equal to the letter Q, continue this while loop. However, I'm going to make one change. We want to
exit the while loop when they press Q. So you could say while not food equals Q. So within this while loop, let's
print the food that they stated that they like. I'll use an F string. You like your variable food. Then we will
prompt the user to enter in another food that they like. Enter another food you like. Q to
quit. Then once we escape the while loop, we will print just buy. Okay. Okay. Enter a food you like.
Q to quit. I like pizza. You like pizza. I like sushi. You like sushi. I like ramen. You like ramen. Okay, this
program is kind of lame. So, I'm going to press Q to quit. And we escape the wild loop. We have printed by. So, you
could do something while something is not true by using the not logical operator. All right, last example.
Example four. We will use the or logical operator. We'll ask a user to type in a number between 1 and
10. Let's say num equals input enter a number between 1 through 10. Then I will type cast the input as
an integer. While our number is less than one or our number is greater than 10, let's
reprompt the user. Let's print using an fstring our variable num is not valid. Then we will reprompt
the user. Enter a number between 1 and 10. Once we escape the while loop, then
we will print our number using an fring. Your number is our variable num. Enter a number between 1 through
10. 0. Zero is not valid. Negative 1 100. Nope. Uh five. Your number is five. That's an example of how you can
add logical operators to wild loops. while this condition is true or this condition is true, execute this code
forever. All right, everybody. So, those are while loops. A while loop will execute some code while some condition
remains true. It's fairly useful for verifying user input. If a user types in some input that is not valid, you can
reprompt them. And there's many other uses that we'll discuss in the future. But yeah, those are while loops in
Python. Why hello everybody. In today's video, we'll be creating a compound interest calculator in Python. For those
that don't know, interest is a charge for the privilege of borrowing money to some individual or organization. When
you place money in a bank account, you typically acrue interest. We'll create a program to tell you what your new
balance will be after acrewing interest for so many years. But the user is going to decide the initial principle. That's
the investment, the rate of interest, and the time in years that this balance has been acrewing interest. So let's
begin. Let's declare three variables. A principle, a rate, that is rate of interest, and time. Time will be in
years. We've recently learned about while loops. I would like to include those within this program just so we get
the hang of using them. We will ask the user to type in an initial principal investment. We will continue to prompt
the user to type in a principle that's above zero. Our condition will be while principal is less than or equal to zero.
We will take our principal assign it some user input. Enter the principal
amount. Then we would like to type cast our input as a floatingoint number. If our user input principle is less than
or equal to zero, we need to inform the user principle can't be less than or equal to
zero. So I'm going to test my program by printing the principal at the end. Just temporarily enter the principal amount.
I can't type a negative number and continue. What if my investment was negative
$1,000? Principal can't be less than or equal to zero. How about zero? Nope. Can't do that either. Is a,000. Okay?
Yep. A,000 works. That is for the principal. Let's copy this while loop. Paste it. Replace principal with rate.
This is the rate of interest. Enter the interest rate.
interest rate can't be less than or equal to zero. Then let's copy this again. Paste
it. Change rate to time. Let's type cast our input as an integer because we're working with whole
years. Enter the time in years. time can be less than or equal to zero. I'm going to print my principal,
rate, and time. We have principal, rate,
time. Okay, we know that principle works. Enter the interest rate. Can my interest rate be -1? No, it can't. Can
it be zero? Nope. How about 10? 10%. All right, that works. Time. Can time be zero? No, it can't. Can my time be
negative 1? No, it can't. What about 3 years? All right, so we know that our while loops are working. Now, here's the
formula to calculate interest. Let's say our total, that's our total balance equals our principal
times 1 + our rate divided by 100. I'm going to enclose this function with the set of
parenthesis. This portion of our function will take our interest rate, which is a whole number, then create a
decimal. Enclose this function within the power function. raise this function to the power of time
and that is how to calculate compound interest then we will print the new balance I'll use an
fstring balance after our variable time the word years I'll add a placeholder we will add
our total then I'll include a dollar sign maybe this will be in dollars but pick
any unit of currency you would like. I will format this variable with the format specifier. We will display two
decimal places 2F. Okay, let's try this. Enter the principal amount. I invest $1,000 into maybe the stock
market. The interest rate is maybe 10% this year. The time in years will be 1. So, after one year at 10% interest, my
new balance is $1,100. Let's try it one more time for good measure. Maybe $500 with an
interest rate of 7 over 2 years. Your new balance would be $57245. All right. Now, there is another
way of writing this program. What if we would like to allow the user to enter in values that are equal to zero while
principal is less than zero? If principal is less than zero, principal can't be less than zero. Let's do that
for rate. Interest can't be less than zero.
Time can't be less than zero. Here's what happens to our program. Remember that we're declaring our variables at
the top. Uh nothing happens. We go straight to the results. So the reason that this
is happening is that when we reach the while loops, this condition is false from the beginning. We never end up
entering these while loops. We skip over them because these three conditions are all false. We can write a different
variation of this while loop where we could say while true. True is a boolean. That means this while loop will continue
forever unless we explicitly break out of the while loop. We're going to add an else
clause. Else we will break. Break will break out of a loop. With our second while loop, change
rate is less than zero to while true. Then we will add an else clause. Else break out of the
loop. While true. Else break out of the loop. We should be
able to enter zero values in now. Enter the principal amount. 0 0 0. Balance after 0 years is
$0. This should work the same as before, but we should be allowed to enter in zero values.
$1,000. Interest rate of zero after one year is still $1,000. Well, okay then everybody. I
thought that would be an interesting project to create now that we know how while loops work. You could write either
a standard while loop with a condition such as principle is less than or equal to zero or you could say while true.
This loop would continue forever. You would need to explicitly break out of the while loop using this break keyword
which we'll cover again in four loops. But yeah, that is a compound interest calculator in Python.
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.
Here's an example. Suppose we need to count to 10. If we were to use a for loop, we could write something like
this. We would type four, then we would need some sort of counter. Typically, you see people write x. 4 x in, then we
will use the range function. What number would we like to start at? I would like to start at 1, then count to 10. But the
second number is exclusive. So really, we're going to write 11 if we want to count to 10.
So then colon then hit enter. Whatever code you would like to repeat a certain number of times you will list underneath
the for loop and make sure the code is indented too. I will print whatever our counter x is. When I run this code we
will begin at 1 then stop once we reach 11. So yeah there we are. We have begun at one and we have counted all the way
to 10. So that's the basic syntax for a for loop for some counter. Really, you can name this anything. Sometimes you'll
see people name this as counter and that would work too, but let's stick with X in some range. Where
would we like to begin? Where do we stop? Okay, now let's count backwards. Let's start at 10, then count down to
zero. When we escape the for loop, let's print happy new year. When we print happy new year, we are
outside of the for loop. To count backwards, you can enclose your range function within the reversed
function reversed. So we begin at 10, count down to one, then print happy new year. In
this case, to count backwards, you would enclose the range function within the reversed function. There is an
additional parameter too you could add. That is the step. If you would like to count by twos, you would add comma
2. So I'm going to get rid of happy new year. Let's print the numbers 1 through 10, but we will count by
twos. And this does begin at 1, though. So 1 3 5 7 9. If you were to change the step to three, you would count by threes
beginning at 1 4 7 10. So the range function isn't the only thing you can iterate over. You can iterate over a
string. Let's say we have a credit card number. Credit card equals I'll make up some credit card number with
dashes. That is good enough. For x in credit card print x will hold our current position. At first it'll be one
then 2 3 4 dash. So on and so forth. So here's our credit card number. 1 2 3 4 dash 5 6 7 8. I think you get the idea.
So you can iterate over a string with a for loop as well. We'll have a few projects involving that. There are two
useful keywords as well. These aren't exclusive to for loops. You can use these within while loops as well. They
are continue and break. Suppose we going to count to 20. For x in range, we will begin at one, stop at 21. I think this
is kind of a dumb example, but it gets the point across. 13 is considered an unlucky number, right? What if our
counter reaches 13? I would like to skip over it. Well, we can do that with the continue
keyword. If x is equal to 13, we will continue and skip over that iteration. Else, we will print whatever
our counter is. So, let's take a look. Yeah, we have the numbers 1 through 20, but we have skipped the number 13. To
skip over an iteration, you can use the continue keyword. Whereas the break keyword, we will break out of this loop
entirely. If x is equal to 13, then break. So yeah, we have only counted to 12. Once we reach 13, we have escaped
the loop. So yeah, everybody, those are four loops. You can 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. There is a lot of overlap
where you could use either a while loop or a for loop. While loops tend to be better if you need to execute something
possibly infinite amount of times, such as when you're accepting user input, for example. But yeah, everybody, those are
for loops in Python. What is going on everybody? In today's topic, we're going to be
creating a countdown timer in Python. We'll be using what we learned in the previous topics. Let's begin. We'll need
to import the time module. There's a pretty cool function within the time module. That is the sleep function. Type
time do sleep. Add a set of parenthesis. Within the set of parenthesis, our program will essentially sleep for a
given amount of seconds, like three. After three seconds, let's print something. This is just a
demonstration. Times up. When I execute this code, nothing happens for 3 seconds, but after 3
seconds passes, it displays our message times up. So, you can use the sleep function of the time module to sleep for
a given amount of time. We will ask the user how long would they like to set the timer for. We will create a variable.
Let's say my time my time will be in seconds. We will create a prompt. Enter the time in
seconds. Then we should type cast our input as an integer. We'll need to create a loop. We
could use either a while loop or a for loop. There's a lot of overlap where you could use either one. I'll use a for
loop in this case. Four. We'll need some sort of counter X in our range zero
through my time. After each iteration, we will sleep for 1 second. Let's test what we
have so far. I would like to sleep for 3 seconds. I think that's approximately three. But now we are going to print
whatever x is. Print x. x is our counter. 0 1 2 times up. We're getting somewhere. But I would like to count
backwards. What we could do is enclose our range function within the reversed function. But another technique that we
can use is by using a step. Let's replace zero with my time. Then end at zero. But we will set
the step to be - 1. Then we can increment backwards using this function. That's another technique too to count
backwards. So let's wait for 3 seconds. 3 2 1. Times up. Now let's display a digital clock of some sort. But we would
have to calculate how many hours, minutes, and seconds there are. So let's calculate seconds. Seconds equals x. X
is our counter. Remember modulus 60. Within our print statement, we'll
use an f string. We are displaying hours, minutes, and seconds. I'll add some placeholders for each of these
fields. We have seconds. With our digital clock, we can't go above 60 for either seconds or minutes. That's why
I'm using modulus 60. The modulus operator gives you the remainder of any division. Let's begin at 11. So 11 10 9.
So it is counting down, but I would like to add some zero padding and we can do that with the format
specifier. After seconds, I will add colon. I need to display two digits. Then zero pad those digits. Let's try
that again. I will wait for 11 seconds. 11 10 9. Yeah. And we do have some zero padding. So that's looking more and more
like a digital clock. Let's add minutes then. So to calculate minutes, let's assign variable minutes equal to x / 60
because there's 60 seconds within a minute. But then I'm going to type cast the result as an
integer modulus 60. We would not like this field of minutes to go above 60. So let's add a placeholder. We're
displaying minutes. Format specifier 02. Now I'm going to wait for 65 seconds. That is 1 minute and 5
seconds. Then I just want to be sure that we go below a minute. Yep, it's working. Then let's calculate
hours. Oh, by the way, to stop your program from running, hit this red square up in the corner. Let's calculate
hours. Hours equals x / 3,600. There's 3,600 seconds in an
hour. Then we will type cast the result as an integer. within our fing we will
display ours format specifier 02. Then I will run this program. Let's wait for
3,65 seconds. That is 1 hour and 5 seconds. And I just want to be sure that we go below 1 hour. Yeah. All right. So
that works. So the reason that I didn't add modulus 24, I don't have days within my fing. We
can display any amount of hours. I will exclude modulus 24. All right, everybody. Well, I
thought that'd be some good practice with working with loops. We should try and do as many exercises as we can. And
yeah, that is a countdown timer program in Python. Hey everybody. So I guess in
today's topic, I'm going to be explaining nested loops. It looks like so a nested loop, think of it as a loop
found within the code of another loop. You have a loop, right? Any code within that loop is indented underneath that
loop. Well, you could have a looping structure found within the code of another looping structure. The loop on
the outside is the outer loop. The internal loop within the outer loop is known as the inner loop. Where you'll
encounter nested loops, it's really situational. You could have a while loop inside of a while loop, a for loop
inside of a for loop, a for loop inside of a while loop, a while loop inside of a for loop, etc. So, here's a
demonstration. Let's begin by displaying the numbers 1 through 9, but we'll use a loop for x. X is our counter in
range 1, 10. Remember that the second number in this case 10, that's exclusive.
Then I will print our counter X. This program will print the numbers one through nine. Now we have an exercise at
the end of this topic. I should probably explain this feature. So with a print statement, we end each print statement
with a new line character. If I need all of these numbers on the same line, at the end of my print statement, I can add
comma end equals an empty string. Normally with a print statement, each ends with a new line character, but we
can set that to be something else. So when I run this again, all of these numbers are on the same line. Or
you could add a different symbol like dash or a space. Each of these characters is now
separated with a space. But let's stick with an empty string. Okay, so we have used a loop to
count the numbers 1 through nine. What if I would like to repeat this three times? Well, I could create another
loop for x in range. You could say 1, 4, or you could just say three. Either way, whatever code is within this loop
will be executed three times. Let's cut our original for loop, then place it within the code of our new loop. Our
outer loop will have this code repeat entirely three separate times. Uh but we do have one thing we need to pay
attention to. We have two counters with the same name. You'll want to be sure that they're different. Let's rename the
counter of the inner loop to be y instead of x. And be sure to change that here as
well. Now when I run this code, we're completing let's see 27 iterations. To exit this for loop, we need to count the
numbers 1 through nine. Once we do so, that is one iteration of the outer loop. But our outer loop is saying, "Hey, we
still need three total iterations." Now, if you would like these on separate lines, let's make this look a little
different. Let's add each iteration of the outer loop onto a new line. So, within the outer loop, but not
within the inner loop, I'm going to create just a blank print statement. This will just print a new line. Let's
try this again. With the inner loop, we count the numbers 1 through nine. After we exit
the for loop, we will print a new line. Then repeat this all over again until our outer loop is satisfied. So that's
basically a nested loop. It's just a loop that's inside of another looping structure. So let's create a project.
We're going to print a rectangle made of some symbol that we set. We'll have the user type in how many rows and columns
this rectangle will have. We'll reuse this code that we have already written. So this time let's accept some user
input. Rows equals input. Enter the number of rows. Then we should type cast this input as an
integer. Let's copy this line. Paste it. Change rows to columns. For the second line, enter the number
of columns. Then let's create a symbol. Symbol equals
input. Enter a symbol to use. We already have this rectangle structure, right? Think of it as the
outer loop is in charge of the rows. Let's change in range three to in range rows.
The inner loop will be in charge of the columns. For y in range
columns, we will print our symbol whatever the user chooses. So let's try this again. Enter the number of rows.
How about four rows, 10 columns? I'll use a dollar sign. So here's our rectangle.
We have four rows, then 10 columns. 1 2 3 4 5 6 7 8 9 10. Let's try it one more
time. Three rows, five columns, and I'll use an asterisk. Yep, three
rows, five columns. So, yeah, that's a nested loop. Really, it's just a loop that's inside
of another loop. The type of loop really doesn't matter as well as what's within each loop. It's just a situation where
you have a loop inside of another loop. And yeah, those are nested loops in Python. Well, hello everybody. Today I
will be explaining a few different types of collections in Python. There's four general purpose collections. Three of
them are lists, sets, and tpples. There are also dictionaries, but I'll save that for the next topic because they can
be kind of tricky. A collection I would think of them as a single variable and I'm saying that within quotes that is
used to store multiple values. That's how I would explain a collection to a beginner. For example, let's say we have
a variable variable fruit. Fruit equals some value like apple. And then I can print this fruit which is apple. I could
turn this variable into a collection by surrounding my values with either a set of square brackets for a list, curly
braces for a set, or parenthesis for a tuple. Let's begin with a list. If I would like to store more than one value
in this variable, I will surround my values with a set of square brackets. This variable is now a list. I can store
multiple values separated with a comma. Not only do we have an apple in this variable, but we have an orange
a banana and coconut. One naming convention that I
like to use, if I declare a collection such as a list, set or tpple, I like to take the variable name and make it
plural just so that it's more obvious that this is a collection of values. Technically, in the English language,
fruit would still be plural. English is a weird language. We now have a list of fruit named fruits. If I were to print
my list, this is the result. We have all of our values enclosed with a set of square brackets. To access one of these
elements found within your list, you can use the index operator, much like what we can do with strings. The first
element would have an index of zero. That would print my value apple. Index of one would be my orange.
Two is banana. Three coconut. What about four? We don't have a value there. List index out of range. Each
value in a collection is also known as an element. If we attempt to access an element that's not found within our
collection, you'll run into an index error. With the index operator, you could set a beginning index, an ending
index, and a step. I would like the first three elements. You could say zero colon
three. That would give me apple, orange, banana. Technically, you don't even need the zero. You need that colon, though.
We can even use a step. I would like every second element, apple, banana. It's every
second element beginning from index zero. Maybe I would like my fruit backwards. I'll set the step to be
negative 1. Coconut, banana, orange, apple. You can use the index operator with collections much like you can use
with strings. Another cool thing you can do too with collections is that you can iterate over them with the for loop for
x in my collection fruits. What would we like to do? I will print whatever x
is. So we have iterated over our list. Apple, orange, banana, coconut. Now x isn't really too descriptive. What
you'll see some people do is that with their collection name, it's plural, their counter will be the singular
version of that word. If our collection name is fruits, let's rename x as fruit. Singular. It's not mandatory, but that's
a common convention. It's more readable that way. For every fruit in fruits. If this were cars, you could say for car in
cars. Our counter is storing whatever value is within our collection. So what are all the different methods that we
can use with collections? To list the different methods that are available to a collection, you can use the dur
function. Within this function, add your collection fruits. But we would need to print this.
Let's surround this function with a print statement. These are all in alphabetical
order. We have attributes, which I have not explained yet, but I will in a future topic. But if we scroll to the
end, we have a bunch of different methods that this list can perform. Append, clear, copy, count, extend,
index, insert, pop, remove, reverse, and sort. If you would like a description of each of these methods, there is a help
function. Help. Add your collection to the parenthesis. Then we would need to print
this. Here's the description of all the methods and attributes. For example, we have our sort method. And here's a
description. Sort the list in ascending order and return none. And then a bunch of other stuff. If you ever forget what
you're capable of with a list or other collection, you can always use the help function to print a description of the
attributes and methods available. If you need the length of how many elements are within a collection, there is the length
function. Return the length of my list fruits. Then let's print it. There's four elements within my list. The length
function returns four. If I were to add an extra element like a pineapple, then that number would be
five. Let's remove that. Using the in operator, we can find if a value is within a
collection. Is our value apple in fruits? But then we would need to print this.
This operator will return a boolean. So let's print whatever that is. Is apple in fruits? That is true.
But is pineapple? Pineapple is not. It's false. You can use the in operator to find if a
value is within a list. And that applies for your other collections, too. With lists, they're ordered and
changeable. Duplicates are okay. We can change one of these values after we create our list. Let's take fruits at
index of zero. I will set this equal to be a pineapple. Then let's iterate over our
fruit. Using a for loop. Okay, the first element is no longer an apple. It's a pineapple. Then
orange, banana, coconut. Using an index, you can reassign one of the values. If I were to change zero to one, well, now we
have an apple, pineapple, banana, coconut. Let's cover some of the methods that are found within a list. We can
append an element. Type the name of the list dot append. What would we like to append to the end of this list? Let's
append a pineapple. I'm going to get rid of this for loop. I'm just going to display my
list. There we have an apple, an orange, banana, coconut, pineapple. To add an element to the end of a list, use the
append method. To remove an element, you can use the remove method.
Fruits. Let's remove our apple. Our apple is no longer there. We have an orange, banana, coconut. Using
the insert method, we can insert a value at a given index. Fruits
do.insert list an index. Zero would be the beginning. Then a value. pineapple. Now we have a pineapple,
apple, orange, banana, coconut. The sort method will sort a list. Fruits do.sort. These are all in alphabetical
order now. Apple, banana, coconut, orange. To reverse a list, you would use the reverse method.
Fruits.reverse coconut, banana, orange, apple. However, these are not in reverse alphabetical order. These elements are
reversed based on the order in which we place them. If you would like reverse alphabetical order, you can first sort
and then reverse. Now we have orange, coconut, banana,
apple. To clear a list, use the clear method. Fruits. All of the elements are
gone. We can return the index of a value. Let's return the index of apple. Fruits do index list an
element. Then we will need to print this. Let's print the index that is returned. The index of apple is
zero. Coconut that would be three. What if we don't find a value like a pineapple?
Well, we have an error. Pineapple is not in list. You could count the amount of times that a value is found within a
list because duplicates are okay. Fruits doc count. Let's count how many bananas are in this list.
Banana. Then print it. One banana is found within this list. How about pineapples?
There are zero. Now those are lists. Surround your values with a set of square brackets. These values are
ordered and changeable. Duplicates are okay. Now let's talk about the next collection which is a set. To create a
set, surround your values instead with a set of curly braces. Our collection of fruits is now a set. A set has different
benefits. The values are unordered and immutable, meaning we can't alter these values. However, we can add and remove
elements. A set does not include any duplicates. I'm going to delete these methods, then print
fruits. We have all of the same values, but they're not in the same order as they were originally. A set is
unordered. If I were to run this again, they will likely be in a different order. See, now we have a banana, apple,
coconut, orange. To display all of the different attributes and methods of a set, you can use the dur
function. And here's all of them. Some of these methods are a little more advanced, but there's a few we might
recognize, like add, clear, copy. For an in-depth description of these methods, you can use the help
function. Much like what we did before, to find the length of our set, we can use the length function, which is
four. We can use the in operator to find if a value is found within this set. Unfortunately, pineapples are not within
our set. Now, if I was to use the index operator of my set, this is what would happen. We have an error. Set object is
not subscriptable. We're not able to use indexing on a set because they're unordered, much like what we can do with
a list or a string. We can't change the values of a set, but we could add or remove
elements. Let's use the add method to add guess what? A pineapple. That is okay. Orange, apple,
pineapple, coconut, banana. We can remove an element fruits. Let's remove our
apple. Our apple is gone. Coconut, orange, banana. We can
pop. The pop method will remove whatever element is first. But it's going to be random
though. Orange, coconut, banana, apple, coconut, banana, apple, banana,
coconut. You can clear fruit. The elements of our set are gone. Those are a few of the more useful methods for
beginners. As a summary, a set is a collection that is unordered and immutable. You can't change the values,
but adding and removing elements is okay. No duplicates are allowed. Let's try that real quick. I'm going to add a
second coconut. Yeah, see, we only still have one coconut. Sets may work well if
you're working with constants. Maybe colors for example. You need to find if a color is within a set. All right. Now
lastly, let's talk about tpples. A tpple is a collection that is surrounded with a set of
parenthesis. Tpples are ordered and unchangeable. Duplicates are okay. One benefit of a tpple over a list is that
tpples are faster than lists. If you're working with a collection, and it's okay if the collection is ordered and
unchangeable, you might as well use a tpple because it's faster. When I print our tpple, all of these values are
surrounded with a set of parenthesis. Again, we have the dur function to display the attributes and methods.
There's not as many for a tpple. For methods, we only have count and index. Again, there's also
help to display a description of these attributes and methods. You can find the length of a tpple with the length
function. We have five elements within here. Using the in operator, we can find if a value is found within our
tpple. Our pineapple is not within our fruits. So there's only two methods we have access to. Let's find the index of
apple. Fruits.index apple. Then I will print whatever is
returned. Apple is found at index zero. There is also count fruits.ount how many coconuts are found
within our tpple fruits. Count the coconuts. Then print this. How many coconuts? We have two
coconuts. And then again with any of these collections, they're iterable. So you can iterate over them using a for
loop. Four fruit and fruits. Yep. Apple, orange, banana, coconut, coconut. All right, everybody.
So, those are collections. Think of them as a single variable used to store multiple values. There's four general
purpose collections for beginners. Lists, sets, tpples, and then dictionaries, which we'll talk about
next. Each of them has unique benefits. Lists are ordered and changeable. Duplicates are okay. A set is unordered
and immutable, but adding and removing elements is okay. No duplicates allowed. A tpple is ordered and unchangeable.
Duplicates are okay and they are faster than lists. Use tpples if you can over a list. But yeah, those are a few
collections in Python. Hello everybody. Today we will be creating a shopping cart program.
This program will be an exercise to follow the previous lesson on lists, sets, and tpples. The more that we
practice with those collections, the better we'll be at using them. So, I thought we'd create an exercise to get
the hang of it before moving on. In this program, we will have two lists. Foods. These lists will be empty. We'll declare
them, but not use them quite yet. And prices, then a total. Total equals zero. The reason that I'm not using tpples is
that tpples are unchangeable. We're going to ask a user what food they would like to buy. We can't append any
elements to a tpple. We're not using sets because sets are unordered. I mean, I guess technically you could, but at
the end of this program, I'm going to print our shopping cart in order. So, I think lists would probably be the best.
We have an empty list of foods and an empty list of prices. We'll use a while loop. While
true. If our condition is set to true, we'll need some way to break out of the while loop. We'll need a break statement
somewhere. We'll get to that later. We will ask the user what food would they like to buy.
Let's declare variable food equal to input enter a food to buy. To exit the while loop, you need to
press Q to quit. Then let's check if food is equal to Q lowercase Q then we will break. We're
not done with the program but let's at least test it.
Pizza hamburger hot dog Q to quit. Okay, it looks like it works. Now, what if
somebody types in uppercase Q? Pizza hamburger uppercase Q. Well, we
can't actually quit. After accepting our user input, if food lower method, this will take our input, make it lowercase
just for a comparison. Let's try that again. Pizza hamburger.
I'll type capital Q to quit and that is valid. Follow food with the lower method to temporarily make the user input
lowercase just in case they type in capital Q. If the user doesn't want to quit, let's add an else
statement. Else, let's take our foods, use the append method, then add whatever food the user typed in. We'll also need
a price. Let's ask a user for the price. price
equals input enter the price of let's use an F string
a whatever food the user types in pick a unit of currency I'll pick dollars we are working with numbers we
should type cast our input as a floatingoint number since we're working with
prices so we will accept a price. Add our food item to our list of foods. Do the same thing with prices.
prices.append whatever the price was. And that is the while loop. Let's test this program again to be sure that
everything's working. Pizza. Pizza will be $5.99. Enter a food to buy. Hamburger.
Hamburgers will be 350. Hot dog. Hot dogs will be 175. I would like to quit. I will type either
capital Q or lowercase Q. Both will work. And we have escaped the while loop. So the while loop is now complete.
Outside of the while loop, let's display our shopping cart. Let's print some decorative
text. Maybe five dashes your cart. Then another five dashes. I will then iterate over all of the
elements found within my foods list. For every food in my list of foods, let's print each food item. Let's
take a look so far. Again, we have a pizza. The price was $5.99. Hamburger, the price was
350. Hot dog 175. Q to quit. Okay, your cart that will display the individual list items. If you would rather have
these list items arranged horizontally in one line, you can add this keyword end
equals. This end keyword will replace the new line character at the end of a print statement with some other
character like a space. Let's try that again. I'll try not to take too much time.
Pizza 5.99. Hamburger
350. Hot dog 175. Q to quit. Yeah, that's much
better. We are horizontally listing all of the different items within our list. You could revert back to the vertical
list if you'd prefer that. I'll keep my output like this. Then we will need to iterate and add up all the prices. For
every price in prices, we do have a total variable that we declared. Let's utilize that. Total
equals total plus price. Otherwise, we could shorten this to plus equals price. That would do the same
thing. Then we will display the total. Print. I'll use an fstring. Your total
is I'll add a unit of currency. I picked the dollar sign. Whatever the total is. Okay, let's run this program one
last time. Enter a food to buy. Pizza, which was
$5.99. Hamburger, which was 350. Hot dogs, they are 175. Q to
quit. Here's your shopping cart. I'm just going to add one new line real quick right before we display the total.
Just an empty print statement. Here are the results. Your cart, pizza, hamburger, hot dog. Your
total is $11.24. All right, everybody. Well, that is a shopping cart program. I thought
this would be a fun exercise to follow the previous lesson on lists, sets, and tpples. And well, yeah, that is a
shopping cart program in Python. Hey, what's going on everybody? So, today I'm going to be explaining 2D
lists. 2D meaning two-dimensional. You do also have the capability of creating 2D tpples. I thought today we would use
2D lists just because they're pretty flexible. A two-dimensional list is just a list made up of lists. It's really
useful if you ever need a grid or matrix of data, kind of like an Excel spreadsheet. Let's create three lists. A
list of fruit, vegetables, and
meat. I'm going to speed up this video. Feel free to pause if you need to catch up.
Here I have three lists. A list of fruit, vegetables, and meat. Each of these lists is a one-dimensional list.
To create a two-dimensional list, well, you would begin by creating a one-dimensional list. Let's create a
list of groceries. All I would need to do is add my individual lists as elements to the
outer list, the 2D list. We have fruits, vegetables, and meats. Normally, to print a list or your
other collections, you would print the name of the list. In my list, fruits, I have apple,
orange, banana, coconut. To access or change one of the elements, you would type the name of the list, then use the
index operator. So fruits at index of zero is a pineapple. Again, with a 2D list, it's a little
different. If I were to print my 2D list of groceries, we would lay out the entire
2D list flat. We have individual lists separated with a comma, all enclosed within a set of square brackets. Taking
the elements found within our 2D list, I'm going to line these up kind of like this. It kind of represents a grid or
matrix with rows and columns. Each individual list resembles a row. Each element resembles a column. If I were to
print groceries at index zero in place of returning one element found within one of the lists, that would return an
entire row. So groceries at index zero is my fruits list. Groceries at index one is my vegetables list. groceries at
index 2 is my meats list. For one of the elements found within one of the rows, you would need two
indices. If I need the apple from the first row within my 2D list of groceries, that would be row 0, column
0. It's kind of like coordinates. Row 0, column 0. That would be my apple. 01, which is an orange.
02 is banana, 03 is coconut. For the next row, I would set the first index to be
one. Row one, column zero, that would be celery. I'm going to speedrun this real quick just to show you all the different
elements. 1 one is carrots, one two is potatoes. If we try to access 13, that index is out of range because
we only have three elements within this row. So then the next row would have an index of two. Column 0 would be
chicken. 2 1 is fish. 2 is turkey. 2 3 is out of bounds. To access
an element from a 2D list, you would need two indices in place of one because using just one would return the entire
row like so. Now, when you declare a 2D list, you don't need to necessarily give each inner list a name. We could do
something like this. I'm going to replace these names with the
rows. I'm just going to put these on a new line to make it more readable. There, that would work, too.
Just separate each inner list with a comma, then enclose everything with a set of square brackets. If you ever need
to iterate over the elements of a 2D list, you can use nested loops. If I were to use a single for loop, let's say
for every uh maybe collection, for every collection in
groceries, let's print what our collection is. Using a single for loop would
iterate over the rows. But to also iterate over the elements found within each row, we would use a nested loop.
for every food in our collection. Let's print what our food is. Using nested loops, we can iterate
over all of the elements found within our 2D list. But I'm going to make this more organized like that grid structure
we have. I'm going to replace the new line character at the end of a print statement with a space.
Then when we exit the nested loop, I will print a new line by using just an empty print
statement there. That kind of resembles our grid structure, we have rows and we have columns. With
two-dimensional collections, you're not limited to just lists. You could create a list of
tpples. So the inner rows will be surrounded with a set of parenthesis. You know, this is also
valid too. Or you could make a 2D tpple. It's a tpple that's made up of tpples. You could make a tpple made up of
sets. Sets are enclosed with a set of curly braces. Here we have a tpple made of
sets. Use whatever is best for your own programs. Let's go over an exercise. Let's create a two-dimensional keypad
that you would normally find on a phone. We have three data types. a list, a set or a tpple. The elements in a set are
unordered, so we can't use that. These numbers need to be in order. If we have the option, a tpple is faster than a
list. A tpple is ordered and unchangeable, so we should use it if we can, and that's perfectly fine. Let's
create a 2D tpple this time. I will name this 2D tpple numpad. We have an outer set of
parenthesis, then an inner set of parenthesis for each row. We will have four
rows. The first row will be 1 2 3. The second row, I'm going to put this on a new
line. 4 5 6. The next row will be 7 8 9. Then the last row will be an asterisk character.
Then zero. Then the pound sign. So numpad in this case is a 2D tpple. Let's use a for
loop to iterate over every row. This will be the outer loop. For every maybe row for every row in
numpad, let's begin by printing our row. So we're printing every row in our numpad, but I'd like to remove the
parenthesis. Let's create a nested loop for every maybe num for num in
row. Print whatever that num is. We have one long vertical line. Let's replace the new line character at
the end of our print statement with a space. Then when we escape the nested loop, let's print a new line.
And there is our telephone number pad. You can see it's a grid made up of rows and columns. So yeah, that's a 2D list.
Well, a 2D collection. It's a collection that's made up of collections. Then with our numpad, we made a 2D tuple. If you
ever need a grid or matrix of data, a 2D collection would work perfect. And there you have it, everybody. Those are 2D
collections in Python. Hello again everybody. So today we're going to create a quiz game in Python.
Let's declare all of the different collections and variables that we'll need. First we will need a tuple of
questions, a 2D tuple of options. My quiz will have five questions, but you can add more or less
questions. Then a tuple of answers. A list of guesses. We will be appending guesses to our list. That's why we're
using a list rather than a tpple. A score variable, which I will set to be zero. Then question
number. This variable will keep track of what number question we're on. All right, let's begin with our questions. I
have five. Here are my questions. They're all
science related. Feel free to choose your own. This is what I have. How many elements are in the periodic table?
Which animal lays the largest eggs? What is the most abundant gas in Earth's atmosphere? How many bones are in the
human body? Which planet in the solar system is the hottest? These are the questions, but we'll need options. Let's
add four options for every question. That's why we're using a two-dimensional tpple. Each inner tpple will consist of
four elements. They will be options A,
B, C or D. Let's copy these elements then paste them within each
tpple. This first element corresponds to my first question. How many elements are in the periodic table? I'll come up with
some answers. I'll add some answers for the rest of these tpples, too.
We have a tuple of correct answers. The orders are C, D, A,
A, B. If you come up with your own options, your answers may be different. Now that we have all of our different
collections and variables taken care of, let's display each question. I will iterate over our tpple of questions.
They are iterable. For every question in questions, I'm going to print some decorative
text. I think that's probably good. Then I will print each question we're iterating over. So let's see what
we have so far. There's all five questions. After we display every
question, I need to display every option for every option in options. Our options options is a 2D
tuple. Let's add the index operator. The index is going to be our question number variable. It's a number. So at first
we're accessing options at index of zero. Then 1 2 3 4 5. We will print every option in
options. Add a given row number. Let's test this. Okay, we have some options. But all of these options are for the
first question. We will need to increment our question number. So let's do that. Maybe here.
question number plus equals 1. That is much better. Before iterating the question number, we will ask the
user for a guess. Guess equals input enter A B C D.
In case the user types in something that's lowercase, I will follow this input with the upper method to make the
user input uppercase. We will take our list of guesses, use the append method, add our
guess to that list. If our guess is equal to the answers tpple at index of question
number that means the user guessed the right answer. Let's increase the user score. Sc score score plus equals 1.
Then print the word correct. Correct. Else we will
print incorrect. I'll use an fstring. Our
answers at index of question number is the correct answer. All right, let's answer
some of these questions. C. Correct. Which animal lays the largest eggs? Um, definitely the
whale because the whale is the largest creature, right? Incorrect. D is the correct
answer. What is the most abundant gas in Earth's atmosphere? Nitrogen. Correct. How many bones are in the human body? D.
That is incorrect. A is the right answer. Which planet in the solar system is the hottest? Mercury, because it's
closest to the sun, right? Wrong. Incorrect. B is the correct answer. We're keeping track of
our answers successfully. Once we complete all the questions, let's print the
results. I'm going to add some decorative text. Not necessary, but I think it would look
cool. I will display the results. We will iterate over all of the answers and the
guesses. Print answers. I'm going to set the ending character to be an empty
string for every answer in answers.
Print each answer. I will set the ending character to be a space to separate each answer.
Then I'll add a new print line. Let's do this with guesses. Change answers to guesses for
every guess. In guesses, print each guess. Okay, I'm going to run this again. I'm just going to make up some
answers. A B C D A. Here are the correct answers. Here are the guesses. I guess none of them right. Then we will print a
score. Score equals take our score divided by I'm going to use the length function. Then pass in our questions.
How many elements are within our questions tuple then I will multiply all of this by 100 to give us a percentage.
Then type cast this whole formula as an integer. So, we're basically just reassigning our
score variable. Then, let's print using an fring, your score
is our score variable. Then add percent. I'm going to intentionally get all the answers
right. C D A B. Here are the answers. Here are your
guesses. Your score is 100%. This time I'll try and get a few incorrect intentionally. C
C. Your score is 20%. All right, everybody. Well, that is a quiz game. Feel free to add more or
less questions or come up with your own questions. And that is a quiz game written in
Python. Hey everybody. In today's video, I'm going to explain dictionaries. A dictionary is one of the four basic
collection types for beginners. A dictionary consists of key value pairs. They are ordered and changeable. No
duplicates allowed. A few examples of key value pairs could be an ID and a name, an item, and a price. But in
today's example, we'll create a dictionary of countries and capitals. Let's name our dictionary capitals.
Capitals equals enclose your dictionary with a set of curly braces, much like what you do with sets. The first country
will be the USA. To add a value to this key, type colon then some other value. The capital of the USA will be
Washington DC. Separate each key value pair with a comma. Then we can add another key value
pair. So the capital of India that will be New Delhi. We'll add two more.
China. The capital is Beijing. Russia, the capital is Moscow. I think
that's good enough. Just as a reminder, if you would like to see all of the different
attributes and methods of a dictionary, you can use the dur function. Pass in your dictionary capitals. Then we'll
need to print this. Here's all the different attributes and
methods of a dictionary. If you would like an in-depth description of all these attributes and methods, you can
use the help function. Uh, that's herp help. There we go. So, yeah, that's just a
reminder. All right, let's go over a few of the methods. To get one of the values from a dictionary, you would get the
key. Type the name of the dictionary. Capitals.get. Let's get the capital of the
USA. Then we'll print it. The value associated with this key, the USA is Washington DC. If I picked a
different country like India, well then we would get that associated value which is New Delhi.
Another thing, if Python doesn't find a key, this is what will be returned. Let's get Japan which is not in our
dictionary. This method would return none. We can use this within an if statement. If capitals
get Japan if a value is returned then we will
print that capital exists else we will print that
capital doesn't exist so Japan is not in our dictionary that capital doesn't exist but Russia
is that capital does exist. That's how to check to see if a key is within our dictionary. You can use the get
method. All right, moving on. Let's update our dictionary.
Capitals.update. So within a set of curly braces, I will add a key then a value.
Germany followed by Berlin. Then let's print our dictionary. I'll use a print statement.
Print capitals. Yeah. And there's Germany right there. Using the update method, we
can insert a new key value pair or update an existing key value pair. Let's also change one of the existing values
with our key USA. Let's update the capital to be Detroit. Yeah, see the value has been
updated. The capital of the USA is now Detroit, Michigan. To remove a key value pair,
you can use the pop method. Then pass in a key. Let's remove China. China no longer exists within our
dictionary. It's gone. You can remove the latest key value pair within a dictionary by using the pop item method.
Capitals do pop item. With pop item, you don't need to pass in a key. Pop item will remove the latest key value pair
that was inserted. Then we have clear capitals.clear. That will clear the dictionary. It's pretty
self-explanatory. The next few methods are a little tricky to explain. To get all of the keys within the dictionary,
but not the values, there is a keys method. Capitals. I think I'm going to insert this within
a variable keys equals capitals keys. Let's see what happens when we print this. The keys method will return all of
the keys within our dictionary. Technically, keys is an object which resembles a list. I haven't discussed
object-oriented programming yet. This is a little bit above our level. If you ever need the keys in a dictionary, you
can use the keys method. One use is that we can use that within a for loop. They're iterable. For every key in
capitals keys method, let's print every key. If at any time you need to iterate
over all the keys, you can use a for loop to iterate over every key that is returned from the keys method of your
dictionary. There is also the values method to get all of the values within your dictionary. There is a values
method. Values equals capitals do values method. Then let's print our values. Like before with the keys
method, the values method will return an object which resembles a list. Let's iterate and print over every value
within our dictionary. for every value in capitals do values. Print every
value. Here are all the values within our dictionary. This next one is probably
the most tricky. It is the items method. Capitals do items. I will assign what is returned to a variable named items. Then
we will print items. items returns a dictionary object which resembles a 2D list of tpples. It's
really complicated. How might this be useful? This time we're going to use a for loop to print every
key, value in capitals do items method. We have in essence two counters. This time I will print using an fstring
every key value pair. I will print every key as well as every value in our print statement. So there's our dictionary
laid out. We have iterated over every key value pair. It's kind of an advanced topic, but I thought I would at least
bring it up now. So yeah, that's a dictionary, everybody. It's a collection of key value pairs. They are ordered and
changeable. No duplicates allowed. You have a bunch of different methods such as get, update, pop, pop item, clear.
Then you can get the keys, the values, or both, which is the items method. We'll be using dictionaries in a few
game programs we'll be making in the future. And well, yeah, those are dictionaries in
Python. Hey everybody. Today we will be creating a program to mimic a concession stand, much like what you would see at a
movie theater. We will be utilizing a dictionary to keep track of a menu item and an associated price. More or less,
this is just a program to help us get used to working with dictionaries. Let's begin. We'll create a dictionary named
menu. What items are on the menu? We'll need an item and a price. I'll think of some. I'm going to speed up this video.
Feel free to pause if you need more time. and here's my menu, everybody. I thought
of a few food items you might find at a movie theater concession stand. Pizza, nachos, popcorn, fries, chips, soft
pretzels, soda, lemonade. Movie theater popcorn is really expensive for some reason. Okay, we have our menu. A user
is going to select specific keys from this menu. Depending on what the key is, we can get the associated value to
calculate a total. To keep track of the user selected items, I will create an empty list named cart. I will also
declare a variable named total to keep track of the total. We need to lay this dictionary down flat to display it to a
user. Well, we do have the items method of a dictionary which we covered in the last video. for every key value in our
dictionary menu dot items method. The items method of our dictionary will return a key and a value during each
iteration. I'm simply going to print every key and value. I'll use an fstring. I will print every key colon
space then a value. Let's take a look so far. Here's our menu. I'll make a few
changes. The price will be in dollars and cents, but feel free to pick your own unit of currency. I'll preede my
value with the dollar sign. Then using a format specifier, I will display two decimal places
2F. That's better. I will line up all the keys. After the key, I will add a format specifier. then allocate 10
spaces. Yeah, look at that. It's all lined up. Now before and after displaying our menu with this for loop,
I will add some decorative text. Let's say menu. Then outside of the for loop, I'll
display a bunch of dashes. Yeah, look at that. Let's move on to the next
step. We will ask a user for some input. What item would they like to buy from the menu? While our condition will be
true. If our condition is set to true, we'll need to break out of this loop one way or another. We will ask for some
user input. food equals input select an
item Q2 to quit. If food is equal to a lowercase Q, then we will
break. Let's test it. Select an item. Pizza, nachos,
soda, Q to quit. Yeah, it works. Okay. What if the user types in capital Q? Well, we can't escape the while
loop. If a user types in capital Q, we're assuming that they would like to quit. When we accept our user input, I'm
going to add dot lower method. This will take our user input and make it all lowercase. So, we should be able to
acknowledge any uppercase letters. Yeah, it works. Cool. Let's add an else- if statement. What if a user types in an
item that's not on our menu? Well, there is a get method of dictionaries. If menu
get pass in our food which is user input. If the user selection is not within our menu as a key it will return
none. So we can use that else if menu.get food is not none then we would like to append that
food item to our cart. cart.append append our food
item. So, outside of the while loop, I'm going to print our cart temporarily just to test
it. Okay, select an item. Pizza, soda, pretzel. How about a potato? Q to quit. We have our pizza,
soda, and pretzel, but not our potato. We don't want that in our cart because that's not on the menu. Yeah, you can
just add that line. Else if menu item get food is not none. That will complete our while loop. Let's calculate a
total for every food in our cart. Let's take our total variable. Set this equal to total plus. Then we need a value
associated with a key plus menu. Get method get the food item found
within our cart. But I'm going to shorten this to total plus equals menu.get the value associated
with this food in our cart. I will also display that food item. Print food. I'm going to avoid printing our food item on
every line. I will set the ending character in our print statement just to be a space. Okay, let's see what we have
so far. I would like popcorn,
soda, pretzel. Q to quit. Popcorn, soda, pretzel. Then we will display the total.
I will print a new line. print I'll use an fstring total
is add a unit of currency total I'll add a format specifier 2F to display two decimal
places I'm going to add one line of decorative text let's copy maybe
this. All right, let's test it out. Select an item.
Popcorn, pretzel, soda,
potato. Q to quit. All right, here's our cart. Popcorn, pretzel, soda. We did not include the
potato. That was not found within our dictionary. The total is $12.50. Well, there you have it,
everybody. That is a concession stand program. The point of this program was to help us get used to working with
dictionaries. A dictionary is a collection of key value pairs such as an item and a price. And yeah, that's a
concession standard program in Python. Well, hello again everybody. It's me. In today's topic, I'm going to show you how
we can generate some random numbers in Python. Then at the end of this video, as an exercise, we're going to create a
number guessing program. Let's begin. We will be importing the random module. Type import random. The random module
gives us access to a lot of useful methods involving random numbers. For a comprehensive list, you can use the help
function. pass in the random module and then we would want to print this. Here's what we all have access to.
We have a shuffle method, set state, seed, sample, random range, random, random int, random bytes, and there's a
ton of others, but we'll discuss a few of the more useful methods for beginners. For a random whole integer,
maybe you're rolling a six-sided dice. You would type the name of the random module dot then a method. For a random
whole integer, type rand int add a set of parenthesis. Within the set of parenthesis, you will list a range. If
I'm rolling a six-sided dice, I would like the numbers 1 through 6, 1, 6. Then I will assign what is returned to maybe
a variable. print whatever my number is. My random number is a four, three,
one, four. All right. I tend to play a lot of Dungeons and Dragons. We use polyhedral dice that have more or less
than six sides. There is a 20sided dice. For a random number between 1 and 20, I would set the range to be 1, 20. Here I
rolled a 16 and a seven and an eight. Within the rand int method, you can place variables as well as long as they
contain numbers. I will create a variable named low. I'll set that equal to
one. And a variable named high. I will set that to be 100. I will replace the numbers with my variables that behave as
numbers. Give me a random integer between my low variable and high variable. So between 1 and 100 in this
example, I have rolled a 75. Now in 88, if you need a random floatingoint number, you can use the
random method. Random.random. Then let's assign this to a
variable. Number equals the random method of the random module. That would return a random floatingoint number
between 0 and 1. You can pick a random choice from a sequence. In the future, we're going to
create a game of rock paper scissors. Let's say we have a tpple of options. Options
equals rock paper
scissors. We are accessing the random module. Dot. Then use the choice method. Place your sequence within the choice
method. give me a random choice from options. I will store this within a variable. Let's say option equals random
choice from my options. Then I will print the option. Our computer has generated
scissors, paper, rock. So the choice method is a great use for games if you ever need a
random element. Now there's also shuffle. This time maybe we have a deck of cards.
cards equals I guess I'll use a list this time. I have a list of cards that you
would normally find within a deck of playing cards. Well, besides the suit 2 through 10, Jack, Queen, King, Ace.
Using the shuffle method, I can shuffle this sequence. Access the random module.
Shuffle. Pass in your sequence. In my case, it's cards. Then I will print
cards. Yeah, look at that. My cards are now shuffled. In the future, we'll be creating a game of blackjack. The
shuffle method will be used then to shuffle our deck of cards. Those are a few methods found within the random
module. For some practice, let's create a number guessing game as an exercise. Hey everybody. So today we're
going to create a number guessing game using Python. This is a project meant for beginners. By completing this
project, it will help us reinforce our understanding of previous topics. Let's begin. We will import the random module.
We'll need to pick a random number. The random module is going to handle that for us. What is the range of random
numbers for our number guessing game? We'll store those as variables. We will have one variable named lowest
number. I'll set that to be one as well as a variable for highest number which I will set to be 100. Feel free to pick a
different range if you would like. I'll set the range to be 1 through 100. A random number will be selected between
this range which will be stored within a variable named answer. What is the correct answer? So to choose a random
number between these two values, we will access the random module called the rand int method. We
will choose a random integer between these two values. The two arguments will be lowest
num, highest num. For the second argument, let's perform a test run. I will print my answer.
the number is going to be between 1 and 100. Okay, we know that that works. Here's a few more
variables. We need to keep track of the number of wrong guesses which I will store as a variable named
guesses. We want the user to keep guessing as long as our application is running. We will create a boolean
variable of is running which we will set to be true. Once the user wins the game, we will set is running to be
false. We will print a welcome message. Let's say Python
number guessing game. We will prompt the user. I'll use an
fstring. Select a number between. I'll add two placeholders. Select a number between
our lowest number and our highest number. Python number guessing game. Select a number between 1 and 100. Now,
if I was to change the range of these variables, that should be reflected temporarily. I changed the
lowest number to be 10 and the highest number to be 1,00. But let's set that back. Between one and 100 is
good. We'll need a while loop to continue the game each round. We will say while is
running. Since is running is a boolean, we don't need to say while is running equals true. We can just say while is
running while this value remains true. Continue playing the game. We will ask the user for some input. We
will create a local variable of guess. Guess equals use the input function. Then
enter a prompt. Enter your guess. There's one thing we want to check. Python number guessing game.
Select a number between 1 and 100. Enter your guess. What if somebody doesn't type in a number like they type in the
word pizza? We should let the user know that that's an invalid
guess. We'll write the following if statement. If our guess use the is digit method. If our guess is a digit a
number, then we will execute any code underneath this if statement. For the time being, I'll write pass. We'll get
back to that later. Else we will do something else. Let's print the following. print
invalid guess. Let's copy this print statement because I'm lazy and I don't feel like
typing it out. Please select a number between our lowest
number and our highest number. Let's try that again. I will guess pizza, which isn't a
number. And we get the message invalid guess. Please select a number between 1 and 100. All right, that works.
Underneath our if statement, we'll write the following. Once we get a guess that is a
digit, we need to convert it to a number because when you accept user input, it's a string. We will reassign our guess
equal to type cast our guess as an integer. Then increase the number of guesses by
one. Guesses plus equals 1 because we have already made one guess. Here's another
scenario. What if somebody guesses a number outside of this range like one cajillion? Well, we should give a
warning that that guess isn't valid. If our guess is lower than the lowest number or our guess is greater than the
highest number, we will print the following. That number is out of
range and I will reprompt the user. Please select a number between the lowest number and the highest
number. Let's perform a test run. I will guess one cajillion. That number is out of range.
Please select a number between 1 and 100. We'll add an else if statement. Else if our
guess is less than our answer, we will print the following. too low. Try
again. Else if our guess is greater than our answer, we will
print to high. Try again. If our guess isn't less than our answer and our guess isn't greater than our answer, that
means we must have the correct answer. within an else statement we will print. I'll use an F
string. Correct. The answer was insert our answer, our answer
variable. Then print the number of guesses it took. Number of
guesses. Add a placeholder. Place in our guesses within the placeholder. Now to escape the while
loop, we will take our boolean variable of is running, which is normally true, and set that to be false to
escape. And that should be all we need. Let's run this one last time. Python number guessing game.
Select a number between 1 and 100. Let's select a number right in the middle. 50. Too low. Try again. So the number is
between 50 and 100. 75. Too high. It's between 50 and 75.
Then 62. Too high.
56. 53. 55. Correct. The answer was 55. Number
of guesses. It took me six. All right, everybody. That is a Python number guessing game you yourself
can create as a mini project. Hey everybody. In today's topic, I thought we would create a game of rock
paper scissors. Now that we know how the random module works, let's begin by importing the random module. We will
create some options. We will use a tpple. We're not going to be changing the options. So a tpple would be better
than a list. We have three options. Rock, paper, or scissors.
I'll create a variable named player to store the player's choice. For now, I'm going to set this to be none as well as
a computer. Our computer is going to pick a random choice from these options. Rock, paper, or scissors. In order to do
so, we can use the choice method of the random module. Random.choice. Pick a random choice from
options. Let's have the player enter in some input. Enter
a choice. Rock,
paper, scissors. Then we will display the player's choice and the computer's
choice. I'll use an fstring player colon space the variable
player. Let's copy that. Paste it. Then change player to computer. Let's see what we have so
far. Enter a choice. Rock, paper, scissors. So, I pick rock. The computer picks scissors. Let's try it again just
for good measure. I pick paper. This time the computer picks scissors. I pick scissors. The computer
picks paper. Okay, we know that the computer is successfully picking a random choice from our options. Now,
what if the player picks something that's not within this tpple such as the gun? Well, we would want to stop that,
right? We need the user to pick a valid option. Only rock, paper, or scissors. I think what we'll do is that when we
accept the user input, let's place it within a while loop. So indent this line while this condition is going to be
kind of weird. While our player variable is not in our tpple options. Let's try this again to see what happens. I pick
the gun. Enter a choice. All right. Well, if I can't pick a gun, how about a sponge?
Well, I can't pick that either. Rock. That works. Our condition is while the player variable is not found within our
options. If the player doesn't pick one of these options, this while loop will continue forever. Once we pick something
that's within our options, we then escape the while loop. Let's check some win conditions. Now if the player is
equal to computer that means it's a tie. I will print it's a
tie. I'll add a few else if statements. Else if the player is equal to rock I'll use the and logical
operator and the computer is equal to scissors. That means you win.
Let's print you win. Let's add another condition. Else if the player picks paper and the
computer picks rock, then you also win. You win. L if the
player picks scissors and the computer and the computer picks
paper then we will print you win. else. If the player's choice is not the
same as the computers and we don't meet any win conditions, that must mean we lose. Print, you
lose. Let's see if this works. Enter a choice. Rock, paper, scissors. I pick the gun. Nope, I can't pick that. I pick
rock. I pick rock. The computer picks scissors. You win. Let me see if I can lose. I'll pick
paper. You win again.
Scissors. I need to stop winning. I need to see if the lose condition works. Okay, it's a tie at least. But I
need to lose. All right, there we go. I pick rock. The computer picks paper. You
lose. What if the user would like to play again? Let's place all of this code within a while loop. Let's do so right
about here. Now I'm not going to write while true like I normally do. This time I'm going to create a variable. Let's
say running. Is our game running? I will set that to be true. While running equals true or we
could shorten this to just while running. That's simpler. I will place all of this code
within the while loop. To mass indent some code, just highlight all of the code, then press tab. Hey everybody,
this is Bro from the future. I forgot to explain something. The reason I'm not setting the condition of my while loop
to be true is that if you have a lot of code within a while loop, it can be really difficult to find where the break
statement is. If I set my condition to be a boolean variable such as running, it's a lot easier to find any instance
where I use this variable. If I were to highlight it, we can see that running is found down here. If I need to change any
instance of this variable and rename it to something, you can refactor. Let's rename running as maybe playing. Then I
will refactor. So my variable running is now playing. And that change was made down here too. So it's a coding
preference. Every time we start a new game, I will reset the player as well as the computer. Let's move these two lines
into the while loop at the beginning. So when we start a new game, we will reset the player. The computer
will pick a new random choice. So let's see what we have so far. Rock. I pick rock. The computer
picks rock. It's a tie. Then we have to play again. So paper, you lose. Scissors. It's a tie. Now what if we
would like to escape the while loop after our win conditions? I'm going to create a temporary variable. Let's name
this play again. Then we will ask for some user input. Play
again. Y slashn meaning yes or no. If the user types in something that's capital, I'm
going to use the lower method to make it lowerase. So if our play again variable is equal to
Y, we would like to escape. What I would like to do is I would like to see if the player types in something that's not Y.
I will preede this condition with the not logical operator. If the user does not want to play
again, then let's take our boolean variable running. Normally it's true. and set that to be false. Running equals
false. That means we will escape the while loop. Once we escape the while loop, I will
print. Thanks for playing. Now, I'm going to change this momentarily. I just want to test it.
Rock. Play again. Yes. Paper. Play again. Yes.
Scissors. You lose. Play again. Nope. Thanks for playing. This is entirely optional. I try and create as few
variables as possible. I would personally rather avoid creating a variable here. Another way in which I
could write this is that I can get rid of this variable. Let's move if not in front of
the input and follow our input here. Then use the comparison operator.
Then add a colon. If the user's input after making it lowercase does not equal a Y for yes,
set running to be false. So that should work the same. Rock play again. Yes. Enter a
choice. Paper. Play again. No. Thanks for playing. This line would work the same, but it's a little more complex for
beginners to read. or you can use the other method that I showed you. All right, everybody. Well, that's a game of
rock, paper, scissors. Hello everybody. Today, we will be creating a dice roller program
in Python. We will be utilizing some ASI art. I'll post all of the ASI art that we'll need in the description of this
video. You can copy and paste it to save time if you'd like. All right, let's get started, everybody. We will begin by
importing the random module because we will be rolling some random numbers between 1 through six. If we're going to
create some ASI art, we'll be utilizing Unicode characters. To enter in a Unicode character, it really varies
depending on your operating system. I think the easiest way would just be to use Python. To enter a Unicode
character, type a forward slash, then a given code for each character. Here are all of the codes that we'll need.
After writing these seven unic code characters, let's run this program. These symbols that are output, let's
copy them. I'll add them to a comment. Then we can delete this line. These are the unic code characters we'll need to
build some ASI art, some dice. Each die will be made out of five lines. Let's begin with the first. We'll need a
left corner, nine dashes, then the right
corner. For the second line, copy this vertical bar. Add nine spaces. Then a vertical bar. We can copy
this whole line. Paste it two times. Let's use the left bottom corner. Add a nine of these
dashes. Then the bottom right corner. And here's a basic box shape. Depending on what the number die is, we
can add one of these bullet points. For a one, we can add that right to the middle. So that's good for now. We'll
delete this later. Let's create a dictionary. I will name this dictionary dice art. Our dictionary is made out of
key value pairs. So the keys will be the numbers 1 through six beginning with one. The value will be a tpple. It's a
dictionary made out of key value pairs where the value is a tpple. Within the tpple, let's add these lines each
separated with a comma. I'm going to format these so they form a box
shape. Let's take our bullet point, place it right in the middle, then add a comma to the end of this key value pair.
That is the first key value pair. Let's copy all of this. Paste it again. Change one to two.
Let's move this bullet point. We need two bullet points about right here and here. Let's repeat this process for keys
three through six. Be sure to get rid of the comma at the end. And here is our dictionary of dice
art. Each key is a number. Each value is a tuple made of strings. Let's create a list of dice.
Our dice will be numbers randomly generated between 1 and six. a total to calculate the total. I'll set
that to be zero. Then we will ask a user for a number of
dice. This will be some input. How many dice? Then type cast the input as an
integer. We don't want somebody to write, you know, 2.5 dice. You can't roll half a dice. To generate a random
number, you can use the rand int method of the random module. We need a random number between
one and six. Then we need to append this number to our list of dice. dice.append. Then we can move this line
to within the append method. We need to do this a number of times depending on how many dice the
user enters in. We can place this line within a for loop for
every die in our range number of dice. This will be a number. Let's print our list of dice to
see what numbers we have in here. How many dice? I would like five dice. 5 3 3 4
6. Okay, we know that that works. Let's calculate a total. We'll need to iterate and sum all of the elements within our
list. We can do that with the for loop. For every die in our list dice, take our total variable plus equals the
current value within our dice. Then we will print a total. I'll use an fstring total colon
space. Our total variable. Let's see what we have so far. How many dice? I would like five
dice. Our total is 19. Now between these two for loops, we will display our ASI art. The easiest way would be to create
some nested for loops. The outer for loop will be in charge of the number of dice for every
die in our range number of dice. The inner for loop will be in charge of
printing every tpple. For every line in then to get a value in our dictionary, we would type
the name of the dictionary dice art then use the get method. What are we getting? We're
getting a value at a given key. Let's take our list of numbers dice at index of die our
counter. Depending on what the user types in for the number of dice, die will begin at one then
increment within the inner for loop. We will print the line. So let's take a look. How many dice I would like? Three
dice. And here's our asky art. 6 + 2 + 4 that equals 12. If you would prefer, we can display
all of these dice on a single horizontal line instead of one vertical line. It's a little more tricky though. If you
would prefer that approach, let's turn this chunk of code into comments. We will write this nested loop
a little different. So each tpple is made up of five elements, right?
So, if we're printing a horizontal line, let's say we roll the numbers 1 through three, we would first need to
display this line of the first dice, then the first line of the second dice, then the first line of the third dice.
During the next iteration of the outer loop, we would display the second line of the first dice, the second line of
the second dice, the second line of the third dice. So, it's a little more complex.
Let's create an outer loop that will iterate five times. For every line in range
five, then the nested loop will be for every die in dice. How many dice do we have within
our list? We will print. We're going to get one of the values found at one of the
numbers that we roll. take our dictionary of dice art. Get then a number 1 through
six. That will be the value found within our list of dice. Get the current die. Remember that this is a number 1 through
six. We would then need one of the elements found within our tpple. So get the first line, then the second line,
third, fourth, fifth. So let's add the index operator. Place our counter of line
within the index operator. Let's see what we have so far. We need to add one more thing. How
many dice? Three. This is an abomination. There's one more change we need to
make. At the end of our print statement, let's set the ending character to be an empty
string. And that should fix that. How many dice? Three. Okay, we're getting better results. Then when we escape the
inner loop, we will print a new line. How many dice? Three. And there we are. 3 + 6 + 1 is
10. All right, everybody. So, that is a dice roller program. It is kind of complex, but I thought this might be a
good exercise. If you would like a copy of this code, I will post all of this in the comment section down below. And
well, yeah, that's a dice roller program in Python. Hey everybody, today I need to
explain functions. Think of a function as a block of reusable code. To invoke a function, you place a set of parenthesis
after the function name. To invoke it, here's a scenario. I need to sing happy birthday three times. I know it's a
weird example, but it makes a lot of sense. Just trust me on this. If I need to sing happy birthday three times, I
would write something like this. I'm going to create my own version of the happy birthday
song. This is one verse. If I need to repeat this code three times without using functions, I could either repeat
this code or maybe place it within a loop. So, here's my happy birthday song three times. But there's a better way of
handling this that doesn't involve repeating our code or using loops. What if I could write this code once then
reuse it whenever I need to? That's where functions come in. To define a function, you would type def then a
unique function name. Let's name this function the happy birthday function. Add a set of parenthesis a colon. Any
code that belongs to the function you'll want to indent underneath. Then to invoke this function, I would type the
name of the function, happy birthday, add a set of parenthesis, and that's
it. When you invoke this function, you will execute this code once. If I need to execute this code three times, I
would just call it two more times. Happy birthday. Happy birthday. Happy birthday. To invoke a function,
you type the function name, then add a set of parenthesis. I like to think of the parenthesis as a pair of telephones
talking to each other. You call a function to invoke it. Hey, happy birthday function. Execute your code.
With functions, you are able to send data directly to a function using what are known as arguments. You can send
values or variables directly to a function. Place any data within the set of parenthesis. I'll send my function a
first name. Any data you send a function are known as arguments, but you need a matching set of parameters that are in
order. What exactly is the data we're sending in? Well, it's a name. I will add one parameter to my happy birthday
function. I will name this data name. A parameter is kind of like a temporary variable that's used within a function.
I'm going to replace this instance of u with a name. I will use an fstring. Replace U with a placeholder. I
will add my parameter name. So, happy birthday to bro. We could pass in some other names. What about
Steve and Joe? Here we are. Happy birthday to bro.
Happy birthday to Steve. Happy birthday to Joe. When you invoke a function, you can send more than one argument. Let's
send an age this time. I'll send 20, 30, and 40. But when I run this, we have an error. We're passing in two
arguments, but our function is set up only to take one. I would need a matching number of arguments. To invoke
this function, we will need two parameters. We have a name and we have an
age. Then let's use this age. You are. Let's make this line an F string. age years old. Let's try that
again. Happy birthday to bro, you are 20 years old. Happy birthday to Steve, you are 30 years old. Happy birthday to Joe,
you are 40 years old. When you invoke a function, you can pass in some data. Those are known as arguments, but you'll
need a matching set of parameters. The order does matter. Let's see what happens when I switch these two
parameters. age then name. Happy birthday 220, you are bro years old. Happy birthday 230, you are
Steve years old. Happy birthday 240, you are Joe years old. So the position of the parameters does matter. Same thing
goes with the arguments. You also could name these parameters something unique. Maybe X and Y. Happy birthday to X. You
are Years old. That's also valid. Let's try another example. I'm going to create a function
to display an invoice. There will be three parameters, a
username, an amount, and a due date. Let's print hello. I should make this an F string.
username. We'll use another fing your bill of
amount. Let's precede this placeholder with the unit of currency. I will also add a format
specifier 2F is due on our due date. whatever that
parameter is. To invoke this function, we will type the function's name, add a set of parenthesis, a username, an
amount, and a due date. Let's make up some username, an amount, I guess
$42.50. I'm just making up a number here. Then a due date, the 1st of January, I guess. Here's my invoice.
Hello, bro code. Your bill of $42.50 50 cents is due on January 1st. Let's change these arguments. Joe Schmo is the
username. He owes $100 and one penny. Due on the 1st of February or January 2nd, depending on how you read dates in
your region. Hello, Joe Mo. Your bill of $1001 is due on 1/2. That's another example. Now, we need to explain the
return statement. Return is a statement that is used to end a function and send a result back to the caller. Here's an
example. We have a variable Z. Z will equal we'll invoke a function to add two numbers together such as the numbers 1
and two. When we invoke a function, we can send some data back. After adding 1 and two, we will send the result which
would be three. Then this value can be assigned to a variable. then we can print whatever Z is. So let's create
some functions. Let's create a function to add two numbers together. The parameters will be X and
Y. Let's say Z equals X + Y. Then we will return our value Z. So I'm not going to
print Z directly right now. Let's subtract X and Y. Subtract Z = X - Y. Return
Z. Multiply X * Y then
divide. X / Y return Z. Let's invoke our add function. Pass in two numbers, one and two. Then I'm going to print the
result. After adding these two numbers together, the result is three. What about
subtract? Subtract 1 and two. The result is -1.
Multiply. The result is two. Then divide. 1 / 2 is 0.5. After we resolve
this function, a value is returned. Just imagine that after we finish this function, this function becomes whatever
is returned three. This function becomes -1. This function becomes two. This function becomes
0.5. Let's write something a little more complex. We will create a function to create a full name.
Create name. We'll need two parameters for a first name and a last name. I'll name these first and
last. What do we want to do within this function? Let's capitalize the user's first name. First equals first dot
capitalize method. Then do the same thing with the last
name. Last equals last. capitalize. Then I'm going to return the user's first name plus their last name. Then
I'll add a space in between their first and last name. This is also valid. Outside of the
function, let's create a full name variable. Then invoke the create name function. So this function is going to
capitalize the first and last name for us. I'll type in my first name all lowercase. Same thing with my last name.
Then let's print our full name. And here is my full name variable. We sent our function some arguments. We
have some parameters set up. We took those values, made them uppercase, then concatenated these strings together,
then returned them as a single string. Let's try this with a different name. Spongebob
Squarepants. Spongebob now has a full name. The first and last names are now capitalized. Using the return statement,
you can return some data back to the place in which you call a function. Well, everybody, that's a function. It's
a section of reusable code. To call a function, you type the function's name, add a set of parenthesis. You can send a
function some data, which are known as arguments, but you'll need a matching set of parameters. 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. And those are functions in
Python. Hey everybody, today I'm going to explain default arguments. Default arguments are a default value for
certain parameters. The default is used when that argument is omitted when you invoke a function. In the last topic, we
discussed positional arguments. Today, we will be examining default arguments. Then in future topics, we'll examine
keyword and arbitrary arguments. Let's begin. Let's define a function to calculate net
price. There will be three parameters. An original list price, a discount if there is one, and
sales tax. We will return a net price. And here's the
formula. List price times 1 minus our discount percentage times 1 + our sales tax.
Maybe I'm buying a PlayStation 5 for $500. I will pass in 500 for the list price. Well, I can't actually execute
this function without also passing in an argument for discount and tax. Perhaps the discount is zero and the sales tax
is 5%. 0.05. Well, this would work. And I should probably put this within a print
statement so you can see it. There we are. My total is $525. The list price of $500, no
discount, and 5% sales tax. Now suppose that maybe 90% of the time when we're executing this function, most of the
time discount is zero and our sales tax is almost always the same. What we could do to make this function a little more
flexible is to set these two parameters to have a default value. In place of sending in three arguments, we can pass
in one. Then set our discount and our tax to have a default value. So I will set discount to be zero and tax to be
0.05 meaning 5%. So this function would work. Our total is 525 and that's assuming that our
discount is zero and our tax is 5%. The nice thing about using default arguments is that let's say that somebody has a
discount. Well, this function would also accept up to two additional arguments. So, let's
print our net price 500 and our customer has a coupon for 10% off. I'll add a second argument
of 0.1. If we're passing in an argument for our discount, we'll use whatever is
passed in rather than the default. Our total now is $472.50. Or maybe this
time they are not paying sales tax. I will set the sales tax to be zero. Now the customer's total is
$450. So that's kind of the nice thing about default arguments. It makes your functions more flexible and it can
reduce the number of arguments, especially if the arguments that you're passing in tend to be consistent. Most
of the time people don't have a discount and almost everybody is paying 5% sales tax. Why pass in arguments we don't have
to? Let's cover an exercise. We'll create a count up timer. We will import the time module. We will define this
function. Define count. There will be two arguments start and end. For X in
range, start comma end. Within the range function, the second argument is
exclusive. So I'm going to add one to the end of our time. Then I will print x. To make this
thread that's running the program sleep, you can access the time modules sleep method. Pass in one for 1 second. Then
outside of the for loop, let's print the word done. To invoke this function, I need to
pass in two arguments, a start time and an end time. I'll set the start time to be zero. the end time to be 10. 10
seconds. So, we start at zero, then we will increment by one every second. I'll speed up the video. I think you get the
idea, but we'll stop at 10. Let's assume that most of the time a user would like to begin at zero. Well,
we don't necessarily need to pass that in as an argument. Let's set our start parameter to have a default value of
zero. We only need to pass in one argument. But we do have a problem. Non-default
arguments should follow default arguments. So if you use any default arguments, you'll want to be sure that
they're after any positional arguments. So let's reverse these. And that should
work. So now when I run this program, it's assuming we'd like to start at zero, but we'll need to pass in an
ending amount of seconds. When do we want to stop? That works the same, but now we do
have the option of starting at a different number. This time let's end at 30, but we will begin at
15. We're beginning at 15. Then we will count to 30. I'll speed up the video. There we are. All right,
everybody. So in conclusion, default arguments they are default values for certain parameters. The default value is
used when an argument is omitted. They can make your functions more flexible and reduce the number of arguments you
have to pass in especially if those arguments are consistent most of the time. So those are default arguments and
in the next topic we will discuss keyword arguments and well yeah those are default arguments in Python.
Hey friends, it's me again. Today I'm going to explain keyword arguments. A keyword argument is an argument preceded
by an identifier. It has a few benefits. It helps with readability and the order of the arguments doesn't matter if
they're keywords. Keyword arguments are one of four basic styles of arguments. We discussed positional, default, then
next we'll discuss arbitrary, but today we'll be focusing on keyword. Suppose I have a function to display a message
like a greeting. I will name this function the hello function. We will need a
greeting, a title, Mr., Mrs., doctor, a first name, then a last name. All I'm going to do within this function
is print anstring. I will print my greeting the user's
title, first name, last name. Then to invoke the hello function,
I will need to pass in four arguments. A greeting, a title, a first name, and a last name. So for my greeting, let's
say hello. The title will be mister. The first name will be Spongebob. Last name
Squarepants. So you know this does work. We're currently using positional arguments. The position of these
arguments does matter. So what if I were to switch these around? We have hello Spongebob Squarepants followed by
mister. Hello Spongebob Squarepants mister. An optional feature when sending arguments to a function is that we could
turn these into keyword arguments. Prefix any arguments with the name of the parameter followed by equals. Title
equals mister first equals Spongebob. Last equals Squarepants. Then
with these keyword arguments, the order really doesn't matter. Maybe we move the first name to the
end. And the still would print out is the same thing. We have title, first name, last name. If you're mixing and
matching positional arguments and keyword arguments, you want to be sure that the positional arguments are first.
So if I was to move the string, our greeting to the end, well, this technically wouldn't
work. We have a syntax error. Positional arguments follow keyword arguments. So, make sure any positional arguments are
first before using any keyword arguments. Two helpful benefits of using keyword arguments is that it helps with
readability and the order of the arguments doesn't matter. We know what this argument is as well as these two
title, last name, first name. Let's say we have a first name and a last name. John James.
These two names kind of sound like first names. Is our first name John or is it James? We could use keyword arguments to
clarify which is which. You thought John was the first name, but it's actually the last name and the first name is
James. Then our title is still the same. Hello, Mr. James John. Let's cover another example.
I'm going to print the numbers 1 through 10 using a for loop for x in range 1, 11 because the second argument is
exclusive. Then I will print x. After each print statement, we print a new line. Do you remember in previous
topics how we would follow our print statement with comma and then a new character such as a space? While end is
a keyword argument found within the built-in print statement, in place of ending each print statement with a new
line, we are using this keyword argument of end and sending it to be a space. Another one is separate that's
found within the print statement. Maybe we have some numbers. They're all separate
strings. The numbers 1 through 5. I can use the separate keyword argument then separate each of these strings with a
given character or characters. I will separate each of these strings with a dash. A lot of built-in functions such
as the print function. They have some keyword arguments you can use. Let's go over an exercise
now. We're going to create a function to generate a phone number, but we'll need to pass in a country code, area code,
the first three digits, and the last four digits. Let's define this function as define get phone to get a phone
number. We have a country code area code first meaning first few digits then
last meaning last few digits. We will return an fstring. We will place our country code
first dash then our area code dash the first few digits dash the last few
digits my phone number phone num equals I will invoke the get phone number function we just created but we'll need
a country code an area code. First few digits, then last few
digits. And remember, the order doesn't necessarily matter. Usually, I try and be consistent with the order of the
parameters. Make up a phone number. I'm in the United States. My country code is 1. Area code 1 2
3. The next few digits will be 456. The last few will be 7890. Then let's print this phone
number. print phone num and here is my phone number. Although you can change it up based on
how you do phone numbers in your country. This is typically how you would see a phone number in the United States.
All right, everybody. So those are keyword arguments. They are just arguments preceded by an identifier that
matches the name of a function's parameters. It does help with readability and the order of the
arguments doesn't matter. When invoking a function, it could be helpful to identify some of these arguments. And
well everybody, those are keyword arguments in Python. Hello friends, it's me again.
Today I need to explain arbitrary arguments. Arbitrary meaning a varying amount of arguments. We don't know how
many arguments the user is going to pass in when they invoke a function. To accept a varying amount of arguments,
developers tend to use these parameters of args and quarks. Args means arguments. Quarks means keyword
arguments. You would want to prefix each of these parameters with the unpacking operator, which is an asterisk. When you
invoke a function that has args or quarks as parameters, you will pack all of those arguments into a tpple if it's
args or a dictionary if the parameter is quarks. Let's go over an example. I will create a function to add two numbers
together. define add function there will be two parameters a comma b all I'm going to do
is return a + b I will invoke this function pass in two arguments because we have two
parameters set up one 2 then I'm going to print the result big surprise there my function
return three all right well what if I would like to pass in three parameters this time. Well, I can no longer use
this function. The add function takes two positional arguments, but three were given. I could modify this function so
that it could accept a varying amount of arguments, any amount. I'm going to replace the parameters with asterisk
then the word args meaning arguments. So when we use the unpacking operator, what's going to happen now is that with
the arguments that we pass into this function, we will pack them all into a tpple. And if you don't believe me,
let's test it. I'm going to print the type of args. Then I'm going to remove this print statement for
now. My parameter args is a tpple that I could work with. We can use the built-in methods of this tpple or we could
iterate over it. I'm going to iterate over this tpple for every arg in args for every argument in
arguments. What we'll do is create a variable named total to keep track of the
total. Total plus equals the current arg that we're iterating over. Then at the end I will return the
total. Let's print the result. Print. Add these three numbers together. There we are. My total is six. Then we can
pass in any amount of arguments. Four this time, maybe five or even
one. With my parameter args, you can change this name to something else like nums meaning numbers for every num in
nums. Total plus equals num. This would work too. The name of the parameter isn't as important as the unpacking
operator. Just by typical naming conventions, people tend to stick with args. But the parameter name can vary.
Let's try a different example. Let's create a function to display somebody's name. Display
name. We will accept a varying amount of arguments. Use the unpacking operator. Then follow the unpacking operator with
the unique parameter name. For every arg in args, let's print each
argument. Then replace the ending character of my print statement with a space. Now sometimes people can have a
varying number of names in their full name. There can be a first name, middle name, last name, maiden name, a title,
etc. So, I'm going to pass in just a first name and a last name.
Spongebob Squarepants. If I need to add a middle name, I can do that. Spongebob Herald
Squarepants or a title Dr. Spongebob Herald Squarepants. The third
Yeah, as I was saying with the unpacking operator followed by a unique parameter name, you can pack all of these
arguments into a tuple which you can use within this function. Now let's discuss quarks. You use two unpacking operators.
Then typically people follow this with the word quarks meaning keyword arguments. It allows you to pass
multiple keyword arguments which we discussed in the last topic. I think this would be great for an address.
Define print address function. Use double asterisks. Then we can add a parameter name, but people
usually stick with quarks, meaning keyword arguments. Just as a placeholder, I'm going to type pass.
Pass doesn't do anything. I want this program to be able to run. We'll get back to this function momentarily. I'm
going to invoke this function. print address. Then pass in multiple keyword arguments. With an address, you would
typically have a street, a city, state. Depending on what country
you live in, you may have more or less of these keyword arguments. I live in the United States. We have a state. Then
a zip code. Okay. My street will be I'm just making something up here. One, two,
three. Fake street. City will be Detroit, state,
Michigan. Zip code 5 43 2 1. Just to make this look better, I'm going to place each of these
keyword arguments on a new line. For me, that's just more readable, but you do you. When I pass in these keyword
arguments, we will pack them into a dictionary. Just to prove it, let's print the type of
quarks. Look at that class dictionary. Within this function, you can treat quarks as if it's a
dictionary. There's a lot of built-in methods. Or we could iterate over the keys, the values, or both. to iterate
over the values. Let's say for every value in our dictionary quarks dot values
method print every value. Here's all the values for the keys. Let's change this for loop to be
for every key in quarks keys method print every key. Here are the keys for both. You
could say for every key, value in quarks do items method print every key. Actually, let me turn this into an F
string. Print every key colon
value. The items method will return key value pairs. We can pass in a varying amount of keyword
arguments. I'm going to add an apartment number. Apartment equals 100. Our keyword argument of apartment
was packed into a dictionary along with all these other keyword arguments. So that's kind of nice. We can pass in a
varying amount of keyword arguments. Let's cover an exercise. We're going to use both args and quarks together.
We will print a shipping label. Define shipping label function. The parameters will be both
args, quarks. Then just for now, I'm going to write pass just so that this program will work for now. We'll fill in
the shipping label function momentarily. When we invoke the shipping label function, we will first pass in any
positional arguments followed by keyword arguments. and it won't work the other way around. I'll prove that in a little
bit. So, let's say we have Dr. Spongebob
Squarepants the third. Then I'll add my keyword arguments. I'm going to put this on a
new line. Street equals 1 2 3 fake street. Apartment equals
100. City equals Detroit. State equals Michigan. Zip equals 543 2
1. When we invoke this function, we have a mix of arbitrary positional arguments and arbitrary keyword arguments. This
shipping label function is designed to accept both. You do need args first followed by quarks. This program will
run. But if we have it the other way around, quarks followed by args, it's not going to function
properly. You can see that we have a syntax error. With your parameters, make sure
that your keyword arguments follow your positional arguments. Let's iterate over the positional arguments first. For
every arg in args, let's print each arg. Then I will change the ending
character of my print statement to be a space. Here's the name of the user who we're shipping something to with the
shipping label function. I will print a new line. Then we will iterate over all the keyword
arguments. For every value in my dictionary quarks dot values method, I will print each
value. Then I will change the ending character of my print statement to be a space. All right, it's not looking too
bad so far. If you were to remove some keyword arguments or some positional
arguments, this should work still, which it does. I'm going to change the format of this address slightly. Let's add our
street on one line, then the city, state, and zip code on the next line. Let's get rid of this for
loop. To print the street, I'm going to print use an F string. add a placeholder
quarks.get method. I'm going to get the street key. With this get method, you'll probably need to place them within
single quotes because if you use double quotes, Python gets confused as to where this fring ends. We will use single
quotes. Let's test it. All right, we have a street. On the next line, we will print the city, state, and zip.
print ft string placeholder quarks.get within single quotes the city I'll add another
placeholder quarks.get state then
quarks.getzip. Let's see what we have. All right, not too bad. What if the user has an apartment
keyword? Apartment equals number 100. Well, we should probably add that too. Within this top print statement, I
will add another placeholder. Invoke the get method of the dictionary. The key we are looking
for is apartment Dr. Spongebob Squarepants 23 Fake Street, apartment number 100,
Detroit, Michigan 54321. What if our print statement is set up to display a street and an
apartment, but the user doesn't have an apartment? This would display none, and we don't want that. I'm thinking what
we'll do is we'll place this print statement within an if statement. What we'll check is
if apartment in quarks. If there's an apartment key in
quarks, our dictionary, then print this line. Else we will print just the
street. The person doesn't have an apartment. We won't print the apartment then. But if they do have an apartment,
apartment equals number 100, then we will 123 Fake Street, apartment number
100. Here's a challenge round. What if a user has a PO box? Let's change apartment to PO
box. The string will be PO box number 100,1. I suppose I'll add an else- if statement. else
if PO box in our dictionary quarks. Let's print the street. I'll
copy this line, paste it, followed by a second print statement.
Quarks.getp box. There we are. Dr. for Spongebob Squarepants 123 Fake Street PO Box 10001
Detroit Michigan 54321. All right, everybody. Those are arbitrary arguments. When you invoke a
function, you can pass in a varying amount of arguments. Set up your parameter to be args for a varying
amount of non-keyword arguments or quarks for a varying amount of keyword arguments. You can set up both in your
parameters, which we did for this exercise. And well everybody those are arbitrary arguments in
Python. Hey everybody. So today I got to talk about iterables in Python. An iterable it's a category. Any object or
collection that can return its elements one at a time is considered an iterable. If an object or a collection is
considered an iterable, then it can be iterated over in a loop. For example, let's create a list of numbers.
numbers equals a list. I'll add the numbers 1 through 5 to keep it simple. Lists are considered iterable. We can
use them within a for loop. In the context of a for loop, we're going to be given each element one at a
time. Each element that we're working with, we can give a temporary nickname. Let's say number. For every number in my
iterable of numbers, let's just print each number. This will give us 1 through
5. The name of the current element in our iterable should be descriptive of what we're iterating over. For example,
I don't want to rename the current number that we're working with as something like blah blah blah.
You know, this would work, but other people looking over your code might not understand what a blah blah blah is, and
I don't blame them. Each element that we're given from our iterable, the name should be descriptive of what we're
given. Or you might see item. For every item in numbers, print each item. That's also a good
choice. Now, you could even iterate backwards by enclosing our iterable within the reversed function.
So take our iterable of numbers and reverse it. Then we get the numbers 5 4 3 2 1. If you would rather not print
each element on a new line, we can replace the new line character at the end of print statements with something
else. Print is a function. We can pass in a keyword argument of end. Rather than end each line with a new line
character, let's end with a space. This will space out each of the elements. Or we could replace it with
something else. Or what about a dash? After each element, append a dash character. We could even add multiple
characters such as a space, a dash, and a space if we so choose. It's up to
you. Tpples are also iterable. Let's convert our list to a tpple by enclosing our numbers within a
set of parenthesis. And I no longer want this reversed.
For every number in my iterable of numbers, print each number. Then again, we get the numbers 1 through
5. Let's cover sets. I will create a set of fruit, which I will name
fruits. For a set, enclose any values within a set of curly braces. Let's add a string of apple, a string of orange, a
string of banana, and a string of coconut. So with our for loop, let's say
for every fruit in my iterable of fruits, I will print each fruit. That would give me apple, banana,
orange, coconut. Now sets, they're actually not reversible. I will attempt to enclose
our iterable of fruits within the reversed function. Here's what happens. We have a
type error. Set object is not reversible. Sets you can't reverse. Let's cover strings. I will
create a string of name. Type in your full name. I'll use my YouTube channel name. For every character in my iterable
of name, I would like to print each character. Maybe I would rather not have each character end with a new line. I
will set the keyword argument of end to be a space. Last, we have dictionaries, which
are the most complicated. Let's name this dictionary my dictionary. Dictionaries you enclose with a set of
curly braces, kind of like a set, but each element is a key value pair. I will add a key of A with an associated value
of 1, a key of B which has a value of two, a key of C which has a value of three. If you iterate over a dictionary,
the dictionary is going to return all the keys but not the values. We'll test that. For every key in my iterable of my
dictionary, let's print each key. This would give me the keys of A, B, and C, but none of the values 1 2 or
three. If you need the values, we're going to follow this iterable of my dictionary, use the built-in values
method. This will return all the values of your dictionary as an iterable. But let's
rename a key as value because now we're working with the values. Then we're given all the values
1 2 and three. If you need both the keys and the values, you're going to use the items
method. We'll be given both a key and a value. Make sure that the value and the key is separated with a comma.
Let's print each key followed by the value. We get the key of A with its value of 1 B 2 C 3. We can reformat the
output however we want. Let's use an F string. I will add two placeholders. Let's print each key equals then the
value A equals 1, B= 2, C= 3. Okay, everybody. So those are iterables. An object or a collection that can return
its elements one at a time is considered an iterable. Meaning that object or collection can be iterated over using a
loop. And well everybody, those are iterables in Python. Hello again. So today I got to talk
about membership operators in Python. They are the operators in and not in. They're used to test whether a value or
a variable is found within a sequence which include but are not limited to strings, lists, tpples, sets, or
dictionaries. Here's an example. I'm going to create a word, a secret word. Let's say
apple. I'm going to turn this into a game. I will have a user guess a letter. I will accept some user
input. Guess a letter in the secret
word. What I would like to do is check to see if my letter is found in my word. I can write the following statement. if
our letter in our word in is going to return a boolean value of true if that letter is found or
false if it's not. So if our letter is found I'm going to print the following statement. I'll use an f string. There
is a add a placeholder insert our letter else. Let's print. I'll use an F
string. Our letter was not found. Let's test this. Guess a letter
in the secret word. I will guess a capital A. So all these letters are uppercase. Do take note of that. Is
there an A? There is an A. Let's guess a letter that's not within this word, such as Z.
Z was not found. The in membership operator will test to see if a value or a variable is found within a sequence.
If it is, it returns true. If not, it returns false. Or for the inverse, you could say not in. If letter is not in
Word, we would have to flip these statements around. If this value or variable is not found
in this sequence, it returns true, otherwise false. So, it does the opposite of in. Guess a letter in the
secret word. Is there an E? There is an E. Is there a Q? Q was not found. Depending on the statement you're trying
to write, you can use either in or not in, whichever makes more sense in that context. Let's go over another example.
We were searching for a value or a variable found within a string. Let's try a set. List tpples and sets are
going to behave similarly. I will create a set of students. For a set, you need a set of
curly braces. Let's add a few student names such as Spongebob,
Patrick, and Sandy. I will have a user. Type in a student to search
for. We will accept some user input. Enter the name of a student. We're going to check if our student is
in our sequence of students. If in returns true, let's print the following. I'll use an f
string. Insert our student is a student. Else we will print. I'll use an
fstring. Insert that student was not
found. Enter the name of a student. Let's search for Spongebob. Spongebob is a student. Enter the name
of a student. Let's attempt Squidward. Squidward was not found. And much like the first example,
we can do the opposite. See if a value or a variable is not in a sequence. We would have to switch these statements
around. Enter the name of a student. Is Sandy a student? Sandy is a student. Enter the name of a student. Is Larry a
student? Larry was not found. Now we'll cover dictionaries. I will create a dictionary of grades.
Student grades like a grade book. Let's say that the student of Sandy, she will be a key has a value of
A. Squidward, the key of Squidward has a value of
B. Spongebob, he is also a key. Spongebob has a grade of C. Then Patrick.
Patrick has a grade of D. Here is my dictionary of grades. Then we'll search for a student.
Student equals input. Enter the name of a student. We'll check if let me close this. If our
student is found within grades, then I will print the following. We're looking for keys. Is
there a matching key? If we find that student, I'll make this an F string. Let's display the associated
value of that key. student students grade is I'll add a
placeholder. Once we find a student, we have to get that value at the given key. To do that, we'll take our
dictionary of grades at index of student. This will retrieve the value at a given
key. If we don't find a student, we'll output the following. Again, I'll use an fstring.
Student was not found. So now, if I search for a student such as Spongebob, we're given a grade.
We're given the value at that key that we're searching for. Let's test Sandy. Sy's grade is A.
Squidward. Squidward's grade is B. And Patrick. Patrick's grade is D. But Larry is not a
student. If I search for him, well, Larry was not found. Let's go over one last
example. We're going to create a variable of email. It's going to be a string. Type in whatever your email is.
Brocodegmail.com. I would like to see if this email is valid. Does it contain at and a period? I will write if our value
of at that character is in our email and a period is an email. We have two conditions. Check if
at is an email and check if a period is an email. If so, it's a valid email. Then we'll
print valid email. else we will print invalid
email is my email valid that email is valid I'll get rid of the at invalid email I'll get rid of the
period following Gmail that email is also invalid in this example we're checking
two conditions If this value is found within this sequence and this value is found
within this sequence. All right everybody. So those are membership operators in and not in. They will
return a boolean based on whether a value or a variable is found within a sequence which include but are not
limited to strings, lists, tpples, sets or dictionaries. And well everybody those are membership operators in
Python. Hey, what's going on everybody? So, in today's video, I got to explain list
comprehensions in Python. A list comprehension is a concise way to create lists in Python. They're compact and
easier to read than traditional loops. Basically, you have to follow this formula. For every value in something
that's iterable, meaning you can loop through it, check some condition, then do this expression. So, let me give you
an example with using a traditional loop. then you'll be able to see why a list comprehension is useful. We're
going to create a list and double the numbers 1 through 10. Doubles equals an empty list. Using
a traditional for loop, we will say for every value, let's say x in range 1 through 11. Remember that in the range
function, the second number is exclusive. This will give you the numbers 1 through 10. For the first
iteration, x is going to be 1, then two, 3, all the way up until 10. So, we'll iterate 10 times. During each iteration,
I'm going to take my list of doubles, use the built-in append method, we will append x. During each iteration, that's
going to be the value times two. So, if I were to print my list of doubles, here's the result.
We have the numbers 1 through 10 all doubled. 2 4 6 8 10 12 14 16 18 20. So this is a lot to write. We can use a
list comprehension to make this code more compact and easier to read. Here's how. We need a name for this list. Let's
say doubles equals an empty list. Within our list, we'll follow this formula. We have an expression for value in
iterable and optionally we can check a condition. We'll do this in exercises later on in this topic. We'll begin with
for every value let's say x in our iterable. Our iterable is going to be a range 1 through 10. Again for the first
iteration x will be 1. Then the second iteration x will be two all the way up until 10. During each iteration, what
would we like to do with x, our value? Let's take x, multiply it by two, and return
it. Then, if I was to print my list of doubles, we have the numbers 2 4 6 8 10 12 14 16 18 20. For every value in this
iterable, do this. Multiply it by two. This is a list comprehension. It's a concise way to create lists in Python.
We'll go over a few exercises. So this time we will triple each number. We'll create a list of
triples equals let's say this time for every y in range 1 through 10. So we have to write
11 take y and multiply it by three. Then we will print our list of triples 3 6 9 12 15 18 so on and so forth. Let's
square each number. We'll create a list of squares for every Z in range 1 through
10. To square a number, we take that number, multiply it by itself. So the numbers 1 through 10
squared is 1 4 9 16 15 36 49 64 81 100. So 10 * 10 is 100. Now we're going to work with
strings. We'll create a list of fruits. Equals. Let's think of some fruit. These are all going to be strings. Apple,
orange, banana, coconut. I'm going to take each string in this
list and make it uppercase. We could assign this to a new list such as uppercase
fruits or we can simply just reassign it. Just to keep it simple, I'll reassign
it. So again, we're following this formula. I like to begin with the four value in iterable portion. For every
fruit in our iterable of fruits, what do we want to do? Well, let's take each fruit. Take each
fruit. Use the built-in upper method to make it uppercase. Then I'm going to
print my list of fruits. Each string in this list is now all uppercase. You could even cut down
on one of the steps. With our iterable of fruits, I will place this list. And this does work too. Although I
do find this a little more difficult to read, but you can take either option. How about instead of making each string
uppercase, we'll take the first letter of each string, then put it within a new list. So let's take each fruit at index
of zero. That will give us the first letter. We'll place it within a new list of fruit chars, meaning
characters. Here's the result. A O B C. For every fruit in our list of fruits, return the first character of each
string. A O B C. Now we'll work with conditions. We'll create a list of numbers both negative and positive.
numbers equals let's say 1 -2 3 -4 5 -6. We'll create a list comprehension to create a new list where all of the
numbers are positive. Our new list will be positive nums equals we'll write a list
comprehension for every let's say num in numbers we'll write a condition return this number if our
num is greater than or equal to zero. We do need an expression if we're not modifying each value. we can just return
the value of num. During this exercise, we're more focused on the if condition rather than
the expression. If our value of num meets this condition, simply return it and place it within this new
list. Let's print our list of positive numbers. And we have 135. Let's do this with negative
numbers. I'll just copy what we have and change a few things around. This list will be negative numbers. Negative
nums. For every num in numbers, check this condition. Check to see if num is less than zero. If so, return that
number. Let's print our list of negative numbers. -2, -4, -6. Let's check to see if there's any
even numbers. Even nums equals for every num in numbers check to see if our num is
divisible by two. And we can do that with the modulus operator followed by two. The modulus operator will give you
the remainder of any division. If our number is even, number modulus 2 will equal zero. If it's even, this is going
to equal zero. If it's odd, it's going to be one. We're not modifying our value. We're just going to return our
number. Our list of even numbers should be -2, -4, -6. Let me add one more value. Let's add
positive 8 -24 -6 pos 8. Maybe we'll add one more.
-7. Okay, let's find any odd numbers. Let's copy this line of code. Replace even numbers with odd
numbers. If num modulus 2 is equal to 1, that means that number doesn't divide by two evenly, then we'll print our odd
numbers. 1 3 5 - 7. All these numbers are odd. Here's the last exercise. We'll create a list of grades.
We'll create a new list of any grades that are considered passing, meaning they scored 60 or above. So, let's say
one student has a grade of 85, another with a 42,
79, 90, 56,
61, let's say 30. I will create a new list of passing grades.
Equals again follow this formula for every grade in grades. Check our condition. If our
grade is greater than or equal to 60, we will return the current grade. Then let's print our list of
passing grades. That will give us 85, 79, 90, and 61. All of these grades are greater than or equal to 60. All right,
everybody. So, that is a list comprehension. It's a concise way to create lists in Python. They're compact
and easier to read than traditional loops. Remember, for every value in your iterable, optionally, you can check a
condition. You can write an expression to modify that value if you choose and return something. All right everybody.
So those are list comprehensions in Python. Hey everybody. So today I'm going to explain match case statements
in Python. If you're familiar with other programming languages, this is also known as a switch. Match case statements
are alternatives to using many else if statements. We execute some code if a value matches
a case. The benefits of using a match case statement is that they're cleaner and the syntax is more readable. In this
sample program, I have a function. There is one parameter, a day. Day will be a number, ideally a number 1 through 7.
Depending on this number, we'll return a string corresponding to the day of the week. If day equals 1, then it is
Sunday. two, it is Monday all the way up to 7 where it will be Saturday. I do have
an else clause if we pass in something that's not valid like pizza. Pizza is not a day, but it really
should be not a valid day. A cleaner and more readable alternative is to use a match case statement instead of many
else if statements. Here's how. I'm going to take my if and many else if statements and enclose them within a
match case. Match case. The case is going to be the value we're examining. The case
will be day colon. We're going to examine our value of day against matching
cases. We're going to replace if day equals with the following. just simply case. So let's do that with each of
these statements. If you have an else clause, you're instead going to have a case of
underscore. An underscore in a match case statement is a wild card. We will perform this case if there are no
matching cases. This case would function as the else statement. Here's what we're working
with. Now, if I pass in one and return the day of the week, we would get Sunday. 2 would be Monday. 3 Tuesday.
7 is Saturday. And then let's try that day of pizza. That is not a valid day. A match
case statement is an alternative to using many else if statements. I find this much easier to read than the many
else if statements. Both would technically function. Let's go over a second example. We will create a
function of is weekend. We have to pass in a day. This time our day is going to be a string
such as Monday. The value for each case instead of a number is going to be a string.
If our day matches a case of Sunday, let's return how about a boolean of true. We're checking to see if it's
the weekend. If our day is equal to a case of Monday, then we will return false. Let's do this with the other
days. I'm going to fast forward the video. We will call the function of is weekend
then 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 wild card 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 of Saturday or Sunday return
true. If the case is Monday or Tuesday, we can get rid of that.
or Wednesday or Thursday or
Friday then we will return false. We can keep our wild card case. So is
Saturday part of the weekend that is true. is Monday false
Sunday true Friday false and
pizza we have our wild card 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 benefits 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. To include a module, we would type import the name of the module, for example, 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. Pi from the math module is 3.14 and some change. Another way to import is to type import the name of the module
as. 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, another way to import is to use from the name of the
module. Import something specific. PI for instance, you would no longer need the module
name. From math import pi, pi would be included within our name space. However, I tend to not use from import as much
just because it's possible there could be name conflicts. Here's an example. Let's say from math import E. E is an
exponential constant. E is 2.71. What if I was to create a program
where we have four variables named A, B, C, D. A = 1, B = 2, C = 3, D= 4. Then I'm going to print E from the math
module to the power of A. That would give me 2.71. Then let's do this with B, C, and
D. E to the power of B, E to the power of C, E to the power of D. Here are the results. Let's say we have a different
variable E. E will be five. Then I will print E to the power of 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. math. E to the power of A to the power of B to
the power of C to the power of D. Math E to the power of our variable E. And these results are to be expected.
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. pi=
3.14159. Then a few functions. Let's create a function to square an argument that's passed in. Define square. We will
accept an argument which we will name x. Then return x to the power of two. Let's define a cube function. We will accept
one argument. Then return x to the^ of 3. Maybe a circumference function. Define
circumference. We will accept a radius. Then return 2 *<unk> * radius. Then an area function to calculate the
area of a circle. We will accept a radius as an argument. Then return pi * radius to the power of 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. 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.py. Then I will print the result which is
3.14159. Let's utilize the square function. result equals example dosquare. Let's square
three which is 9. Let's use the cube function that would be
27. Circumference that would give me 18.8. Then
area that would be 28.2. 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, function two. within function one a equals 1 then we print a
within function two b equals 2 then we print b. If I were to invoke these functions let's invoke function one then
function two. We would print 1 then two. 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 function two, if I were to print A, we would run into a name error. Name B is not defined. 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
2. Function 2 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 equals 2.
If I was to eliminate this variable declaration, we would use the enclosed version instead where x equals 1.
There's an order of operations. Use any local variables first, then enclosed variables. We're printing x within
function 2. 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 equals 3. X
is outside of any functions. When I run this program, we're printing three 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 one, 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 equals 3. Last in our order is built in.
I think what we'll do though is from math import E. E is an exponential constant. I'm going to print what E is.
E is 2.71. E is built in. I will create a function to print E. Define function
one. All I'm doing is printing E. Then we should invoke it. Invoke function one. If I was to set E to be a different
value like three, 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 leggb order, we would first look for any
local version of E, then enclosed version, then global, which we do have one of, then lastly builtin. All right,
everybody. So in conclusion, variable scope is just where a variable is both visible and accessible. Python has a
scope resolution order levb. 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. Hey everybody. So today I got to talk about this if statement. If dunder name is equal to a string of dunder
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 of if done name is equal to main. If we're not running this program
directly, don't do it. 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. file new Python file script
2. 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
2. Okay. Apply. Then okay. Using this drop-own 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? For the time
being, we'll select script one. Within script one, if I was to print, then call the dur function dur
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. Dunder name is a special type of variable. Dunder
meaning double underscore. If I was to print what's contained within dunder name, we would receive a string of
dunder main. That's why in a script you may see the statement if dunder name is equal to a string of dunder
main. If so, then you usually call a function named main to start your program. I'm going to undo that. So
let's import script two. From script two, import everything. Asterisk means
everything. Within script two, I will print dunder name. And we'll see what's within
it. Again, I'm running script one. Within script 2, dunder name is equal to a string of script 2, the name of the
Python script. However, within script one, dunder name is equal to a string of dunder main. This means I am running
script one directly. Let's delete this import. Then go to script 2. Import script one. From script one, import
asterisk meaning all. We're now going to change our run configuration from script one to script two. We are running script
two directly. Now dunder name within script one is the name of the Python script
script one. Dunder name within script 2 is now dunder
main. So by adding this if statement of dunder name is equal to dunder
main we can check to see which file is being run directly. If dunder name equals dunder main we will call a
function of main to contain the main body of our program. But we need to define this function define
main. Our main function will contain the majority of our Python code. anything that's not already within a
function. So let's print this is script one. Then we'll define another
function of favorite food. We will have one parameter of food. Let's print the following message.
I'll use an fstring. Your favorite food is add a placeholder. add our parameter of food.
Within our main function, let's call the favorite food function. Pass in your favorite food as a string. I'll type in
pizza. Then let's print the word goodbye. We're going to run script one. Run it. 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 dunder name is equal to dunder 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 this is script one. Your favorite food is pizza. 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 dunder name is equal to 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
2 now is define a function of favorite drink. There's one parameter of
drink. I will print use an fring your favorite drink is I'll add a placeholder. We'll add our parameter of
drink. Let's print the message. This is script two. We will call from script one the
favorite food function. Pass in your favorite food. This time I'll say
sushi. Let's call our favorite drink function. Favorite drink. I'll pass in coffee. Then we will print goodbye.
Okay, we are running script two. This is script two. Your favorite food is sushi. Your favorite drink is
coffee. Goodbye. We're running script 2, 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 2 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. If dunder name is equal to a string of dunder main. If we're running this program
directly, execute this code. So let's call a function of main. Define
main. Then place our main body of code within it. If I run script 2, we have the same
message. So by adding this if statement of if name is equal to 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 dunder name equals dunder main. It makes your code more modular, helps with readability, leaves no global
variables, and avoid unintended execution. And well everybody, that is the purpose of if dunder name equals
dunder 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. We'll need to make a deposit. Define
deposit. Make a withdrawal. define withdraw. 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. While is running. You can check to see if this is equal to true, but since this is a boolean, that's not
necessary. We will just say while is running. If is running becomes false, we'll exit the while loop. Within our
while loop, we'll print some sort of welcome message. Let's print
banking program. Then list some options. Let's print
one, show balance. Two,
deposit. Three will be withdraw. Four will
be exit. Afterwards, we will set a choice variable to equal some user input.
input. Enter your choice 1 through 4. We're encouraging a user to type in a number 1 through 4 to
select an option. Do they want to show their balance, make a deposit, make a withdrawal, or exit? We'll add a few if
and else if statements. Let's check to see if the user's choice is equal to one, and that is a
string of one. Our user input is a string data type unless we were to type cast it to something else. If our choice
is equal to one, we will call the function to show balance. Else if our choice is equal to
two, we will make a deposit by calling the deposit function. Else if choice is equal to
three, we will call the withdraw function. Else if choice is equal to four, that means we would like to exit.
So we need to exit this while loop. We can do that by setting our variable of is running is this program running equal
to be false to exit. If somebody types in some input that's not valid, we can handle that with an else
statement. Else, let's print that is not a valid choice. Okay, let's see what we're
working with currently to test everything. We haven't written anything within these functions yet. Show
balance, deposit, or withdraw. So, we can type one, two, three, and four to exit.
processed finished with exit code zero. So we can exit the program. We just have to select option
four. With this else statement, this will execute if we type in something besides the numbers 1 through 4 because
there's no other options left. So to test that, enter your choice 1 through 4. Uh I'm just going to type the word
poo. That is not a valid choice. So we know that the else statement is working. Once we exit the
while loop, let's print a message that says, "Thank you. Have a nice
day." If I was to type four to exit, we should exit the program. Thank you. Have a nice day. Let's make that h
capital. Now, we'll work on our functions beginning with show balance. Currently, these two variables are
global. We don't need to pass them as a parameter to these functions quite yet. We will be enclosing all of this code
within a main function. We'll handle that later, though. So, with show balance, all we're going to do is print.
I'll use an fring. Your balance is add a dollar sign or other unit of currency of your
choosing. Add a placeholder. our balance variable and let's see what we
have. I will type one to show balance. Your balance is $0. I'll display our balance with two
decimal places. After I will add a format specifier after balance colon 2f will add two decimal places. We covered
format specifiers in a previous topic. So if I were to run this again, type one, we show $0 and 0. We're displaying
two floatingoint decimal places. Now we need to make a deposit. That will be the next
function. We will define a local variable of amount equals accept some user
input. Enter an amount to be deposited. Again, when we accept user input, it's a
string. We'll type cast it to a number, a floatingoint number, because we have to include dollars and
cents. We'll add some checks, though, after accepting some user input. If our amount is greater than zero, we don't
want anybody to make a negative deposit. Let's print that's not a valid
amount. Else we are going to return our amount. So this function is going to return
something. So within our else if statement, we will take our balance plus equals the deposit we're
being returned with. This will add our deposit to our balance. balance plus equals
deposit. Let's try it. Let's show our balance. Our balance is
$0. We'll make a deposit of $100. Exactly. Again, we'll show our balance after
making the deposit. Your balance is $100. Let's attempt to deposit negative money. We'll select two to make a
deposit. We'll deposit 42069. That's not a valid amount. So, we have a problem. We have a
type error. Unsupported operand for float and non type. So within this statement, within if within our deposit
function, we're not returning anything. Let's just return zero. We have to return something. And within
this if statement, we didn't return anything previously. We'll either return zero or return a valid
amount. Let's try this again. Let's make a deposit. I will attempt to deposit 42069.
That's not a valid amount. Our program's not crashing. That's good. Now we'll attempt to make a valid deposit.
$501. Then show my balance. Your balance is $501. Okay, that is the deposit
function. We'll work on the withdraw function. Next, we will create a local variable of
amount. accept some user input. Enter amount to be
withdrawn. Our user input is going to be a string. We will type cast it to be a floatingoint
number. We need to check to see if our amount we're trying to withdraw is greater than our balance.
Users shouldn't be able to withdraw more money than what they have in their bank account. If the amount is greater than
our balance that we have, we will print insufficient
funds. Else if the amount somebody's trying to withdraw is less than zero, we will print a different message.
amount must be greater than zero else we will return our valid
amount. So with our if and else if statements we do need to return something if we take one of these
routes we will return zero. We're not making any changes within our else if statement
where we select choice three. We're going to take our balance minus equals the withdraw
amount. Let's test this banking program. Let's show our balance. Our balance is
zero. We'll make a deposit of $100. Show my balance again. Your balance is
$100. Let's press three to withdraw money. Enter amount to be withdrawn. One cajillion
dollar. Insufficient funds. Yeah, no kidding. Let's attempt to withdraw money again. We shouldn't be able to select a
negative amount. 42069. Amount must be greater than zero. Let's enter in a valid number.
This time I would like to withdraw $49.99. That has appeared to work. We'll show our balance again. Your balance is
now $501. Then we can exit by pressing four to
exit. Thank you and have a nice day. The last few changes I'm going to make is that I'm going to enclose all of
this code, our main portion of code within a main function just to encapsulate all of our variables and
help with readability. We will define a function of main. Take all of our code within the main body of
our program and place it within the function. I'm just going to select all of it and indent it. At the end of our
program, we need to call a main function to run it. If you're familiar with the statement of if dunder name is equal to
a string of dunder main that means this program can be imported or run standalone. It is good practice to
include this if statement. We discussed this in the previous video. If we're running this program directly execute
the main function. However, our variables of balance and is running they're now enclosed within this local
scope. These other functions have no idea what these variables are of balance. So we need to pass in our
balance to those functions of withdraw and show balance. When we show our balance, we
have to pass in our variable of balance. Same thing with withdraw. Then set up those
parameters. Within show balance, we will have one parameter of balance. The same thing with withdraw. The last thing I'm
going to do is add a little bit of text decoration around my program just to make it look
nice. So, I will print a bunch of asterisks. It's not necessary, but I think it'll look nice.
Let's add some text decoration before and after the title of banking program. Also before our
choice. Basically whenever we print anything we'll add some text decoration. Let's do that with show
balance our deposit and within withdraw. Okay, let's run this one last
time. banking program. Let's show our balance. Your balance is $0. We'll make
a deposit. $1001. Show our balance again. Your balance is
$1001. We will withdraw money. Enter an amount to be withdrawn. $1,000. Insufficient funds. Let's try
that again. Let's withdraw $50. Show our balance again. $501. Then press four to exit. Thank you
and have a nice day. All right, everybody. That is a simple banking program you can write using
Python. Hey everybody. In today's video, we're going to create a beginner's slot machine program using Python. This
project's meant for beginners. So, let's get started. When creating a project, I like to break up that project into
different sections, then tackle them one at a time. So, with the slot machine, what are some of the different functions
we'll need? Well, we'll need to spin a row. We'll define a function to spin row as a placeholder. I'll write pass. We'll
return to this function later. We need to display or print the row. Print row.
If somebody gets matching symbols on the slot machine, we need to give them a payout, we'll create a function to get
payout. In this function, we'll calculate what that payout is going to be, but again, we'll get to that later.
We'll write the majority of our code within a main function. At the end of this program, I
will add the if statement of if dunder name is equal to a string of dunder main. Then we will call the main
function which drives our code. This program can be imported or standalone. It is good practice to have this if
statement. A majority of the code we're going to write is going to be within our main function. So within our main
function, let's declare the variables we'll need throughout this program. We will need a starting balance which I
will just name balance. We will start with 100 as in $100. We'll need to display some sort of
welcome message. Let's print something. We will print welcome to let's name our game
Python slots. Just for some flavor, I'm going to add some text decoration. Just a
bunch of asterisks. I think it'll look cool, but you don't have
to. Let's display our symbols. We're going to use symbols. I'll add some emojis. We'll
use emojis in this program in place of images. If you're on Windows, you can hold down the window key plus semicolon.
Let's add a cherry. You typically see a lot of fruit in slot machines. A watermelon. a
lemon. There's also a lot of bells for some reason, but we'll add those. And a star. Let me just align
everything. Let's do a test run. Welcome to Python slots. Let me make one
adjustment. Okay, I'm happy with that. So, after our welcome message, we'll continue playing this game while
our balance is greater than zero. While we still have money, we can continue playing. We will print I'll use an
fstring current balance colon space. I'll add a placeholder. Pick a unit of currency.
I'll pick American dollars. Then we will display the user's balance. We will prompt the user to enter in their bet
which we will assign to a variable of bet. So input place your bet
amount. Let's do a test run. Welcome to Python slots. Current balance $100. Place your bet amount. We
won't deduce the bed amount from the balance quite yet. I just want to be sure that we can enter in something.
$1. Good. $10. $100. What if somebody types in a word like pizza? We need to prevent that
input and correct it. We'll check if take our bet. use the is digit method. Is our bet a digit? If
somebody types in a word like pizza, we need to tell them that's not valid. So, this will return true if our bet is a
digit. But we're going to use the not logical operator. If our bet is not a digit, then do this.
We will print please enter a valid number followed by the continue keyword.
The continue keyword will skip the current iteration of this loop and start from the
beginning. Let's test it. Place your bet amount. Pizza. Please enter a valid number. We
have our current balance again. Place your bet amount. I'll type in one. Okay, we did not get that message
of please enter a valid number. This bet of $1 is valid. So if our bet is a digit, we'll
convert it to be an integer using type casting because when you accept user input, it's a string. It has the string
data type. Let's reassign our bet. Type cast our bet as an integer. Then we will check to see if our bet is
greater than our balance. People can't bet money that they don't have. If the bet is greater than the
current balance, if bet is greater than balance, we will print this message instead.
Insufficient funds. Then continue. If somebody tries to bet
negative money or no money, we'll add this statement. If bet is less than or equal to
zero, we will print bet must be greater than zero and continue.
If all these checks pass, if our bet is not a digit, if our bet is greater than our balance, or if our bet is greater
than zero, we will take our original balance minus equals our bet to subtract it. Let's do a test
run. Place your bet amount. Pizza. Please enter a valid number. I will bet one cajillion dollars. Insufficient
funds. Yeah, no kidding. 0. Bet must be greater than zero. What about $1? Our bet should be subtracted
from our balance. Let's try 10. We are now down to 89. Let's bet
$90. Insufficient funds. 89. And that has appeared to work. Once we subtract our bet from our
balance, we will call the function to spin row. This function is going to return a
list which we will assign to be row. Row will be a list. Using the spin row function, we have to generate three
random symbols then return them within a list. We'll work on the spin row function
next. Within our spin row function, we will declare a list of symbols. Add your
symbols, but these need to be strings. Make sure they're all comma separated.
There we go. This is where list comprehensions can come in. If you don't know what a list comprehension is,
here's an alternative. We will declare an empty list of results. This is an empty list. We need a for loop to
generate three random symbols. We could say for
symbol in range three. This for loop will iterate three times. During each iteration, let's take our
empty list of results. Use the append method. We will append a random choice among our
symbols. So we need to import the random module. We'll do so at the top. Import random.
We're telling the random module to pick a random choice from this list of symbols. Then we will append them to our
empty list of results. After we escape the for loop, we will return our results. It's a list. Now, a much better
option is to use a list comprehension. Here's how. It's going to be a lot more concise. We will return a list. Within
the list we will write a list comprehension for every let's say symbol in range
three. There is no condition. What do we want to return during each iteration? Access the random module. Use
the choice method. Then pass in our symbols. Symbol isn't used in this
example. What you may see people do is use an underscore as a placeholder. Basically, what we're saying is for
every iteration in range three, return a random symbol. That's all we need for the spin row
function. Going back, we have our list of row. Afterwards, I am going to print it to test it. Print
row. And we should have three random symbols after making a bet. All right, it looks like it's
working. We'll make a few changes though. Instead of printing our row, I'm going to print the word
spinning, I will add a new line character just to give us some space like after this word of spinning. Then
we will call the print row function. We'll pass in one argument, our row, that's returned to us after we
spin the row. So going to our print row function, we need to set up one parameter, our row that we receive. It's
going to be a list. One easy way to print the elements of a list is that we can print pick some sort of separator
for each item in the list. For example, I'll just print a space. With strings, there are built-in methods. we will use
the join method then pass in our list or other iterable. Basically what we're saying using the join method we're going
to take our iterable in this case our list join each element by a space a space character. Here's the
result. We have three symbols. You could join them by a different character. I'll add a vertical
bar. Enter your bet amount $1. Now we have a vertical bar between each of these symbols. We could include more
than one character. I'll add a space before and after this vertical bar just to space things
out. I think that looks a lot better. And you don't have to, but I'm going to add some text decoration before and
after. I'll add a bunch of asterisks. Let's see what we're working with. Not bad.
So every time we make a bet, we get a new set of symbols. Now what if all three symbols
match? We need to calculate a payout and give it to the user cuz well they won. So after we print our row, we will
call the get payout function, but we will pass in our row. It's a list. And our bet. How
much did we bet? We will be returned with a payout which we will add to our balance. Let's go to the get payout
function. We're sending two arguments to our get payout function. A row and a bet. We have to check to see if each
element in our row is all the same. Is it all the same character? We can do that with an if statement. If our row at
index of zero, that's going to be the first symbol, is equal to row at index one, that's the second
symbol, is equal to row at the second index, and that's the third symbol. If all three symbols
match, we have to return the bet multiplied. Within our if statement, we will add another if statement. I will
check to see if our row at index zero is equal to our first symbol of cherry. Be sure to place it within
quotes because it's a string. Now, the reason I'm only checking if row at index zero is a
cherry emoji, all these symbols are going to be the same. If we're within this if statement, all of these symbols
are going to match. We only need to check one of them. It could be zero, one, or two. But I'll just add zero.
They're all going to be the same regardless. If somebody has all cherries, we will return their bet times
three or some other amount. You can make the payouts higher or lower. Else if row at index zero is
equal to a watermelon, then we will return their bet times four. So watermelons are worth
more than cherries. Else if row at index zero is equal to a
lemon, we will return their bet time 5. Else if row at index zero is equal to a
bell, let's give them time 10. Return bet* 10. else if row at index zero is equal to a
star that's worth the most. We will return their bet time 20. Make sure we're not within our if
statement anymore. If all three symbols don't match within our list, we don't want to give the user anything. They
lost that spin. We will return zero. That's all we need for the get payout function. Scrolling back down after
receiving a payout, it's returned to us from this function. We'll check to see if our payout is greater than zero. That
means they want to spin. I will print. I'll use an F string.
U1 I'll add a placeholder. Proceed this with a unit of currency. I'll use dollars. will display the
payout. Else if they did not receive a payout, that means they lost that spin. We will
print sorry you lost this round. Then take our balance. This is our original balance.
Plus equals our payout. In most cases, the payout is going to be zero. But if the user wins something, we will add
that to the balance. Okay, let's do a test run. I will bet $1. Sorry, you lost this
round. And my current balance is 99. Let's bet again. I'll just keep on doing this
until I win. We're going to lose more times than what we 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. We'll create a variable of play again. We will accept some user
input. Do you want to spin again? We'll add y for yes slashn for no. If our variable of play again does
not equal a character of capital y, then we will break to break out of this loop. Let's do a test run. Enter your bet
amount. I'll just bet a dollar. Do you want to spin again? If I type in anything besides a capital Y, we will
exit. I will type in no. Then we exit. Enter your bet amount. I'll bet a dollar. If somebody were to type in a
lowercase Y, that doesn't register. We'll make it uppercase by following our input with the upper method to make it
uppercase. Place your bet. A dollar. Hey, I won. I won $3. Do you want to play again? I'll type in a lowercase Y.
Yes, I would like to play again, but I did not hold shift in order to make this a capital Y. That will still register.
And our current balance is $12. We're ahead currently. Place your bet amount. I'll bet
$10. We lost this round. I will press N because I don't want to play again. Then we exit. So at the end of our
program, I will print I'll use an fstring game over your final balance is I'll add a placeholder. Pick a unit of
currency. I'll pick dollars. Display our balance. Then I'll just add some text decoration before and after to make it
all look nice. Okay, let's play this one last time. Enter your bet amount. I'll bet a
dollar. Sorry, you lost this round. Do you want to spin again? Yes, I do. I will bet
$5. You lost. Spin again. Yes, I will bet 10.
20 again. I'll bet 20. I keep losing. I'm running out of money, guys. Hey, I won $10, though. Do you want to spin
again? No. Game over. Your final balance is $13. That's why you shouldn't gamble. You tend to lose more money than what
you gain. All right, everybody. So, that is a slot machine program you can write using
Python. Hello everybody. Today, I'm going to show you how we can write a substitution cipher encryption program.
Basically speaking, what we're going to do is that we have a message. To hide the message, we can encrypt it by
replacing every instance of one character with another chosen at random using the same key. We can then decrypt
the message. When I was at my university, I took an intro to cyber security course. I turned this program
in as a final assignment, and I did get an A on it. I don't know, maybe it'll help you. At the very least, it's a good
exercise. All right, let's get started, everybody. We will begin by importing the random module as well as the string
module. Let's create a string of characters named chars. Whatever characters you would like to use for
your encryption program, list them here as a string. However, this can be a lot to write. I think a better solution
would be to import some constants from the string module. I'm going to include some punctuation. I will import the
punctuation constant of the string module. How the heck do you spell punctuation? Okay, that's right. Plus, I
will add some digits. String dot digits constant plus string dot asy
letters. Let's take a look at our character so far. We have one long string of
characters. What if I would like to include a space, a white space? Well, there is a constant for that, but that
includes things like carriage return. That's going to warp our results. Let me show you just for a demonstration.
String dot whitespace plus all the other stuff. We have a carriage return and some other characters. I would like to
avoid that. So in place of importing the whites space constant from the string module, I'm going to add a space
character. That's good enough. Here are all the characters I will be using this program. Feel free to
add more or less. This is all one long string. I'm going to turn the string into a list where each character is an
individual element. To do that, I'm going to take our string of chars, reassign it, then type cast my string of
characters as a list. Then let's print it again. print chars. Instead of one long string, we
have a list. A list of all the characters we'll need. I am then going to create a key, which we will shuffle
eventually. Key. Then to create a copy of a list, you can type the original list dotcopy
method. Then I will print my key. I'm going to place these lists within an F string.
chars then key. Let's see what we have. We have two identical lists. One
for the original characters and the other for the key. We're going to shuffle this
key. random.shuffle shuffle pass in our list of key. Look at that. All of the characters
are now shuffled in a random order. What we'll be doing when somebody types in some text to be encrypted, we will
replace every instance of one character within that string. Let's say an O, then replace it with another one. Every time
we run this program, this key will be reshuffled. Let's ask for some user input.
This part of our program we will do some encryption. Plain text is the original message. Plain text equals we will
accept some user input. Enter a message to
encrypt. Cipher text is the name of the encrypted message. That will be an empty
string. Okay. Let's say a user types in a message. Enter message to encrypt. I like pizza. It's a very important
message. Every instance of a character within my plain text, I will refer to the key and replace that letter with a
different one. For example, any Z's, I have two Z's in this program, will be replaced with, let's
see, capital B. Every time we run this program though, it's going to shuffle the key. So, it's not going to be
consistent. What we're going to be doing is iterating over every letter in our plain text. For every letter in plain
text, strings are iterable. Find the index of every letter from our plain text within our list of
characters. Let's assign a variable index. index equals take our list of chars, use the
index method. We are looking for that letter, whatever letter we're currently on, then return an
index, then refer to our key, get whatever letter is at that same index. So, we will append that to our cipher
text. It's currently an empty string. cyper text plus equals our key at the given
index. Our cipher text should be the encrypted message. Now let's print it out. Print I'll use an
fstring original message. Let's print our plain text. Then our encrypted
message. Print our cipher text string. Let's take a look so far. Enter a message to encrypt. I like
pizza. Then here&