Python - Prep Work
Python - Prep Work
First you need to give a name to the container that will store the information.
You need to type the name of the variable you want to create.
There are 2 variables here- one representing the character’s name and one representing the
character’s age.
After that, if you want to put a variable inside the print statement, you have to end the
sentence “There once was a man named ”, and add “” at the end.
Instead of using the name John, you do + then character_name with another + and then the
last text.
Python can also store boolean values. It is just True or False value. True or False must be T
and F capitals.
Working with strings in Python:
One thing that can also be done is to create a new line inside of the string.
This is called the escape character. It tells Python that any character that comes after it, we
want to render it literally.
Functions. There is a block of codes that we can run to perform specific operations. We can
use functions to modify our strings and also to get information about our strings.
In order to access to these functions, you just need to add dot to see all the functions.
For example, using a function to convert characters in lower case.
For example,
What python did is that it run the first upper function phrase.upper() , then it is gonna run is
supper ().
That's why the value is True, since it converted all the text in capital letters.
We can also figure out the number of characters inside of the string.
Another function is the index function. The index function will tell us where a specific
character or text is located inside of our string.
phrase.index() Between the parenthesis, we can could this a value. This is called a passing a
parameter. Giving the value of a function a parameter.
For example,
The result is 0 because G is at position zero.
First, if we want to print a number, or even a decimal number, and a negative number.
Addition- “+”
Subtraction- “-”
Division- “/”
Multiplication- “*”
Python is going to take the first number divided by the second number and spit out the
remainder.
So python is going to do 10/3 which will be 3.1 The result will be the remained 1.
If the number was not converted into a string, there would have been a problem.
There is also abs which is the absolute number.
There is also pow. We can give 2 pieces of information. First it will be the number and then
the power that i want take that number to.
For example, print(pow(3, 2)) This basically means 2 to the power of 2 (3^2)
There is also the max function. It will return the larger number that we passed into it.
There is also the min function. It will return the smaller number that we passed into it.
There is also the round function. This will allow us to round a number.
In Python, we can actually import external code into our file. To access these specific maths
functions, you have to import something called Python Maths.
This is going to grab a bunch of different maths functions that could be used.
Once add this code, you can access to more maths functions.
One is floor function. This will grab the lowest the number.
The number is 3 because it has just chop off the decimal.
The is another function called ceil. This will rounder up the number no matter what.
There is another function called square root, sqrt. This will return the square root of a
number.
NOTE: If you want more maths functions, just look up on google.
You just type input() This will tell python that we want to input from a user and python will
allow the user to type on some information.
This is like creating a python app, allowing the user to enter the name and store the name
inside a variable and will basically say hi to the user.
What i want to do is store whatever the user stored into the program inside of a variable.
The variable is name, which will equal to input. We are taking the value the user inputs and
im storing it into this variable container called name. I have access to whatever they will put.
Then we can write after is;
We are getting a name from the user, storing inside the name variable and im printing it out
onto the screen.
We enter a value and Python will store that value in the variable and then will print it.
So, in this part, we would get 2 number from the user, and add those numbers together an
print the answer on the screen.
The aim is to create 2 variables and inside those variables, you want to store the 2 numbers
the user wants to store together.
What happened?
When we get input from a user by default, Python will convert it into a string. In order to make
this num1 and num2 variables numbers, we have to convert the string that we got from the
users into numbers.
In order to do that, we need to use 2 special Python functions. The first one is called int.
The int function will convert whatever is inside these open and close parenthesis which is
num1 and num2 into an integer number.
An integer number is a whole number. Like 1,2,3,4,5. (It cannot have decimal number).
Now, it will convert both of these numbers into integers, that is into whole numbers.
But what will happen if the number is a decimal, there will be an error in the result.
A Mad Libs Game is a game where you can answer a bunch of random words like verbs,
nouns, names, colours.
First, if we remove red and make the user answer their own color.
Instead of having violets, why not let the user answer in a plural now.
And of saying I love you, why not let the user answer by choosing a celebrity.
First we need to get the user answer these by creating 3 variables called color, plural noun,
and celebrity and store the users input inside of those variables
After that, we just need to replace, in print, the names of these variables.
The result;
Lists:
The first thing when making a list is to give a name and make a list.
When we create a list, we use [ ] open close square brackets. Whenever using these square
brackets, Python knows that we want to store a bunch of values inside of these list.
Here, there are 3 values inside the friend list. When creating a normal variable in python, we
generally give 1 value, a string, a number or a boolean.
But in a list we can store multiple values inside of the same object. Then we can access
these individual items inside of my programs. Inside of these friends list, we can store
different values.
What can we put inside of a list? We can put any kinds of information- strings, boolean,
numbers. For example;
We can refer each element by their index. Each element in the list has an index starting with
0.
Index of kevin is 0
Index of Karen is 1
Index of Jim is 2
For example;
When using negatives, it starts at the back of the list.
Lets say if we want to access the last 2 elements of the list, we can add the index number
followed by a : colum, and this will grab the element at index position 1 and what is followed
after.
Here the result is only Karen and Jim and not Oscar because the range between 1 and 3, it
will grab only 1 and 2.
We can also modify the list.
List Funtions:
In python, a List is one of the most important structures to store information. A list allows a
bunch of different values to organise them, and store them inside of their own little list
structure
One function called the extend function, will allow you to take a list and add another list to the
end of it.
We can also add individual elements onto the list, by using the append function
We can also add elements in the middle of the list by using the insert function. In this
function, there will be 2 parameters.
We can also remove elements by using the function remove function.
We can also remove all the elements from the list by using the clear function.
There is also another function called pop. It will pop an item out of this list.
In this result, we got rid of the last element of the list. Thats what pop does. It removes the
last element from this list.
What if we want to figure out if a certain value is in the list. For example, lets see if the name
Kevin is in the list.
We can also count similar elements in the list, by using the count function.
We can also sort this list by using the sort function and it will sort the list in ascending order.
The result is in alphabetical order.
Friends2 is going to have the same attributes as friends. It is basically copying what is in the
list of friends.
Tuples:
A tuple is a type of data struction. It is a container where we can store different values. It is
similar to a list, where we can store multiple information.
Whenever we want to create a tuple inside of python, we are going to use these open and
close parenthesis ()
Inside of these parenthesis, we are going to put the value we want to store.
For example,
One feature of a tuple that makes them unique is that tuples are immutable. This means that
the tuple cannot be changed or modified or add or erase elements inside the tuple.
Here, there is an error- ‘tuple’ object does not support item assignment. This is because
tuples are immutable. It cannot be changed.
Here, there is a list and in the list, there is a set of tuples. The values cannot be changed.
Functions:
Let's say we want to create a function that says ‘hi’ to the users.
The first thing to use is a key word called def. When Python will see this keyword def, it will
say that this person wants to use a function.
After typing def, we need to give this function a name, just like giving name for a variable.
So, to create a function that says hi, you just need to type it;
There can be underscore or there can also be no underscore.
This is basically saying to Python that all the codes coming after the whole line is gonna be
inside of the function.
In order to write code that is going to end up side a function, you have to indempt it.
The highlighted part is what is called indemnation. Basically, the space after pressing ‘enter’
after the column.
Then,
If we run the program at this stage, nothing will happen, as shown from the picture below.
Now, all we have to do is call the function. To execute the code inside of this function, we
have to specify when we want to execute it.
In order to call the function, you just type out the function’s name and the open and close
parenthesis.
When we run this program, we see that it prints out Hello User.
How do these functions actually work?
What is happening is that when Python goes through and executes this program, it goes to
the first line;
Then goes to the second line where we want to execute this;
Once its done executing the code, it will jump back to the last line,
At this stage, we can specify that this function needs to receive some parameters.
This function mean that whenever i call this say_hi function, we have to give it a name. So
whenever i call this, we have to give it a name
Then,
It will just say hello to whatever name is shown in the highlighted part.
From the result, it actually print whatever name was pasted and not Hello User.
We can also pass in an integer for the age. But we will have to convert the integer into a
string.
The result is the same. Just a different way.
You also can pass strings, numbers, booleans, arrays, any type of data into a function.
Return Statement:
Python function is a collection of python code that performs a specific task in our python
program and to perform these task, we call a python function.
In a lot of times when calling a python function, we just call it and does its thing and we move
on with the program.
But sometimes, when we call a function, we actually want to get information back from that
function.
The return keyword basically allow python to return information from a function.
was
supposed to be cubing the number (the highlighted part).
And now, Python is going to return whatever value we put to the right (num*num*num)
The same if we put 4;
let's go a bit further. Lets create a variable called result = cube(4)
This variable result is going to store the value to gets return from the cube function.
If Statements:
If Statements are special structures in python where we can help our programs to make
decisions.
By using an If Statement, we can execute certain code when certain condition are true, or
execute other code when other condition are ture.
If Statement allow our program to respond to the input we are giving. Depending on the data
we are using in the program, our program will be able to respond with certain data or certain
values and also other data and other values.
The highlighted part is a condition. This is going to be true or false. If its true, we go ahead
and eat breakfast. If its false, we are going to skip whatever was after ‘I eat Breakfast’ and
move on.
Another example;
If that condition is true, we will bring the umbrella. If the condition is false, we bring the
sunglasses, as it will skip the ‘ I bring an umbrella’ and move on to the next line which is ‘ I
bring sunglasses’
Another example;
If this condition is true, then i order a streak. If the condition is false, it goes on the next
condition, if i want pasta, I order spaghetti and meatballs. If this condition is true, i get the
spaghetti if it is false, i order a salad.
First, we need to create a boolean variable that will store whether the user if a male or not.
This is a boolean variable set to true.
We can use an If Statement to check what the value of the variable is and if its true, i can do
something.
For example,
There will be nothing in the result because that condition is not true.
We can also use another keyword in Python which is else. Else is like otherwise.
We can also make this more complex by adding another boolean attribute.
Now, we want to check both variables, if they are male and they are tall or if they are male
and not tall or if they are not male and so on.
Thats because if we execute this code inside of this else, that means that both of these guys
are false.
If we set is_male=False and is_tall= True;
What if we check more conditions- like what if they are male and not tall.
We can also put another condition if they are not male and tall, we can use elif function;
We will create a python function and this function will give us the maximum number that we
pass into it. This function will take 3 parameters and input and will print out the biggest
number we give it.
We are passing 3 numbers and this function will return the largest of the 3.
In order to figure out which number is the largest, we will have to use an If Statement.
If the first number is greater or equal to ( > =) the second number or its not and the
highlighted part is a comparison. It is actually a boolean value- it is True or False.
Then, we can add else function. If num1 isnt the biggest and num2 isnt the biggest, then we
can assume num3 is the biggest.
The result was 5 because 5 is the biggest.
Another possibility;
No matter which number- num1, num2, num3, it ends up telling us the biggest without any
problem.
We compared numbers but we can also compare strings, booleans.
!= Not equal
We need to get the input form the user. We are going to create 3 variables, one for the 1st
number, one for the 2nd number and one for the operator
Whatever the users enter, we will want to convert it in a number. From string to number.
How to do that?
This will automatically convert whatever the user inputs into a float.
Operator will be +, -, /, *
Then, the last piece piece of input from the user.
Now we need to figure out what is inside of that op (operator), what operator the user wants
to do.
We have to check condition to see if this operator is equal to a what operator’s sign.
I also want to be an else statement to determine that the user has entered an operator that is
not among the 4 other operators.
If we run this program;
1st example;
2nd example;
3rd example;
Dictionaries:
A dictionary is a special structure in python which allows us to store information called key
value pairs.
We can create these key value pairs and access to specific information inside of the
dictionary by referring by its key.
The word will be the key and the value will be the definition.
We will create a program that will allow us to create a 3-digit month name into the full month
name.
For example;
Whenever we create dictionaries in python, we use these open and close curly brackets {}
Inside the dictionary, now we can insert what is called the Key Value Pairs. We define a key
and we give it a value.
We type this with an open and close square bracket [] one of the keys and it should get back
to the value.
The same will be applied to other keys.
If we try to find a key that is not found in the dictionary, the result is like this;
Sometimes, we will want to create a default value. Like if we get a key that is not inside the
dictionary, we can pass a default value.
While Loops:
A while loop is a structure in Python which allows us to loop through and execute a block of
code multiple times.
When creating a while loop, the first thing is to create an integer, a variable that is a number.
This is what you call a loop condition or a loop guard. So, we are going to keep looping
through the code inside of the while loop as long as this condition is True.
So, everything that is below this while loop declaration, is considered as code inside the
while loop.
We are going to keep looping in the code as long as this condition (the highlighted part) is
true.
The result is;
Then, we want to create a variable to store the users’ response, a variable that all the
guesses the user will make.
Now we need to prompt the user to enter the secret word. The catch is that we want the user
to enter the secret word and if they dont guess it correctly, we want to prompt them to enter
another guess. We cant just use a single input statement. We have to use a while loop to
continually guess the word until they guess it.
This basically mean that we want to keep looping as long as the user’s guess is not equal to
the secret word. As long as they havent guess the secret word, it will keep on looping until
the user gets the correct secret word.
Then;
Here we are basically telling the user to enter their guess, and storing whatever they enter
inside of this guess variable, as highlighted in blue
and check if the guess is equal to the secret word. If the guess isnt equal to the secret word,
then the user would do it again but if the guess is correct, then we will just break out of the
loop, and print out a success message because they win as seen below;
The program will terminate since the secret word was guessed.
What if we make the guessing game a bit complex by limiting the number of guess the user
would enter.
Lets say the user has 3 tries / guesses and if they cannot guess the word after 3 tries, they
are going to lose the game.
How to set the limit on the number of huesses the user will have?
In order to do this, we will need to create a couple more of variables at the start of our coding
line.
Then add a guess limit;
If out of guesses is true, this means that they have no more guesses and lost the game.
If out of guesses is false, this means that they still have some guesses left.
The first thing to do is when i go through this loop, i want to check if the users have more
guesses. In other words before i let the user enter a guess, i want to see if they have already
used up their guesses.
If guess_count is less than guess_limit, that means that they havent used up all their amount
of guesses. They have some guesses left.
If this isnt true, in other wrds, they have reached their guess limit, then i want to set
out_of_guesses= True. They have no more guesses.
Now, if the users have reach their number of guess limit, we dont want them to guess
anymore and break out of this loop.
So if we add;
As long as they havent guessed the word and they still have some guesses left, we are going
to keep looping.
But breaking out of the loop, there will be 2 possible scenarios, either the user guessed the
secret word correctly, or the user ran out of guesses.
What will happen if we enter more guess than we have and lose the game;
So, we were not able to guess it in 3 guesses.
For Loop:
A For Loop is a special type of loop in Python, that allows us to loop over different collections
of items.
We sure For Loops in Python to loop through different arrays, or we can loop over like the
letters inside of a string, or we could just look through a series of numbers.
In a way to create a For Loop is to write ‘for’ and specify a variable. This variable is going to
essentially represent a different value every time we go through this For Loop.
We can notice the use of iteration for For Loops. It will change on each iteration of the loop.
If we create an array;
With the For Loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
For example;
We can see that it is going the range from one to 10 excluding 10. Starting to 0 up to 9.
Like, if we want to figure out how many elements were inside of it, we can just use the len
function;
What this is going to do is that its going to give me the range between 0 and the number of
friends inside this list just like below;
And the result will be;
An exponent function is going to allow us to take a certain number and raise it to a specific
power.
For example,
We will create an exponent function that will do this and we will use For Loops to do it.
For example, if we knew we were just trying to square or cube this number, we could just
return the base num * base num;
In order to write this function, we will use a For Loop. First we need to create a variable
called result.
Now, i want to create a For Loop, and specify an index and and then a range
Range will basically range us through a collection of numbers.
If i want to multiply the base num by itself as many times as the power num specifies.
We will loop throught this For Loop as many times as pow num. So, if pow_num is 2, we will
loop through it twice. If pow_num is 4, we will loop through it four times.
So, inside of this For Loop, we can say result = result *base_num
This should take this number to this specific power. So, the actual result is going to get stored
inside of this result variable.
The first time through the loop, we are just multiplying base_num by one. The result will be 1.
The second time through the loop, we would square the number.
The third time through the loop, we would cupe the number.
Another example;
2D Lists & Nested Loops:
2D Lists:
Normally, if we are creating a list, we could just put in a bunch of attributes and a bunch of
elements.
We can also put inside of this number_grid list. So the first item in the number grid list is
going to be a first list. The second item in the number grid list is going to be a list and so on.
To do so we write;
The first square bracket will be row and the second one will be column.
The result will be one because from the list, 0,0 is
one.
Another example;
Nested Loops:
A Nested for loops is a situation where we have a for loop inside of a for loop.
What if we want to get individual numbers inside of each arrays. We have to create another
for loop.
Build a translator:
We can take in a string in like a phrase of a word to be able to translate it into a different
language.
So we are calling it the giraffe language. In the Giraffe Language, all vowels become G. So, if
we were to translate an english word into a draft word, for example the word dog, we would
look through the words dog and any instances where there is a vowel, like in the example its
o and a, it will convert into a g.
Now we need to figure our how to translate English into our draft language.
Now, we want to loop through every letter inside this phrase. If there is a vowel, we want to
change it to G and if it is not a vowel, we will leave it alone.
When i loop through letters, (the highlighted part) I can have access to each individual letters
inside of the phrase that they passed in.
I want to check to see if the letter is a vowel or not. If it is a vowel, we can add a G onto
translation. It it is not a vowel, we can just add on whatever letter it was onto translation.
We use the If Statement. In Python, we can check if something is in something. So, we can
say if letter in “AEIOUaeiou”.
We see if this letter is inside of this string (the highlighted part) and if the letter is among this
string then we know its a vowel.
Then;
This is because if this letter is a vowel, we just want to convert it into a ‘g’.
Otherwise;
So in the case where we have a vowel, we add a ‘g’ onto translation. If it is it not a vowel, we
just add the letter that was onto translation.
Finally, down below this For Loop, we just want to return the translation.
Lets print this out and call this function translate and inside the parentheses, we are just
going to pass whatever the user inputs. Inside the parenthesis we enter a prompt (phrase).
So, we are going to print out the translation of what phrase is going to be put in.
Now, lets run the program;
Another example;
Another method regarding this line;
There is also one more thing about this program. The letter ‘g’ used inside is small letter.
What if we get a capital vowel ‘G’
For example;
We get a lower case g and not an upper case. Its not keeping an upper case syntax.
The result;
Comments:
A comment is basically a line inside our Python file that will not get rendered by python.
Try Except:
Here, we are prompting te user to enter in a number using this input command. Then, we are
converting whatever they enter into an integer.
So, as long as they enter in a valid interger, we can store this whole number in the ‘number’
variable and execute it.
Here it says;
This means that the user did not answer an integer as said in the command ‘Enter a number’
In order to control all those error, we have something called a try except block.
A try except block will allow your program to try out a pice of code, and if everyone goes well,
it is good.
If they entered a text instead of a number, we can tell the that they entered the wrong thing.
How:
Use the try function and then indemne what’s below it.
Now since we put this code (highlighted part) inside of this try block,, if the user enters in
something wrong, its going to be able to catch what the user did wrong and print out invalid
output onto the screen.
For example;
If we create a variable called value and set it to 10/0 (it is not possible to divide a number by
0)
The program is not going to be able to handle this and will throw an error.
If we put the variable value inside of this try block, it is going to get caught by the exception.
Lets see the result;
It says invalid input. But the thing is that we didn’t input something that was invalid. We just
divided by 0.
For example, we have a division with 0 error and an input error. We can create 2 different
except blocks to catch 2 different kind of errors.
With the space, we can specify the type of error that we want to catch.
If we end up dividing by 0
Reading Files:
Sometimes we would like to read files that are outside your python file. So, you might want to
read information from like a text file, or CSV file or like an HTML file.
And you can actually use something called Python Read Command. It will allow you to read
a file that is stored outside of your Python file.
So, we can use these files to get information that is stored outside your python file.
Here we have the file called employees.txt and list out information.
The first thing to do is open that file inside of python by using the open function
This is going to be either a relative path to the file or an absolute path to the file or just the
files name if both files are in the same directory.
We can also put one more thing inside of the brackets and it will be the mode in which i want
to open the file with.
The first mode is called read. We just need to put an ‘r’ since it will stand for read.
This means we only want to read the information inside the file. We dont want to modify,
change it. We just want to see whats in the file and do some stuffs with that information.
Another mode is called write. We just need to put a ‘w’ since it will stand for write.
Write mode means that you can change the file- write new information, change existing
information.
Another one is the r+ which means read and write. This will give you the power of reading
and writing.
https://www.youtube.com/watch?v=rfscVS0vtbw
The readline mode will read the first line of the file.
Since there are 2 lines in this file, it is going to print the first 2 line of the text and will keep
doing so as we copy paste the same line in the code.
Another method;
https://www.youtube.com/watch?v=rfscVS0vtbw
We append to the file- add some text at the end of the file
Nothing happens.
If we put Toby one more time, and when we check the employees list;
This new additional Toby didnt go on to the next line. Mistakes can occur and need to be
careful when appending a file.
Another thing we can do is what if we want to add another employee, and theres no line, we
want to add a new line;
Here, we only have one line, that is because we are using ‘w’ and it overrides everything that
is in that existing file.
Modules:
https://www.youtube.com/watch?v=rfscVS0vtbw
Check the video.
Pip:
https://www.w3schools.com/python/python_pip.asp
Classes and objects can help to make programs more organized and more powerful.
Not all information, or data or things can be represented using strings, numbers, or Booleans
like a computer or phone and so on.
With classes and objects, we can create our own data type for anything in Python. For
example creating a phone data type to represent a phone and would store any form of
information about the phone. That's where we create a class for it.
Lets say we are writing a program and we want to represent a student inside of this program.
Like writing a program for a college or university.
We cannot store student in a single string or number and there is no student data type.
Then, we type class and the name of the class we want to create.
Inside of the student class, we can define a bunch of attributes about a student. And we can
use strings, numbers and booleans what what a student should or should not have.
In order to use that student class and create a student object, we need to import that.
This means that from the student file (the highlighted part is the student file), we want to
import the student class.
Inside of the parenthesis, we want to give the student a name, a major, a gpa and where he
is on probation value.
How it appear;
Then;
Or,
First, how to represent the question and what could be the answer in the test?
To do that, we need to create a question class to store the question and the answer.
Then, we have to write a function that will run the test and ask the user the question.
And we also wan to keep track of the users score and we create a variable called score and
we set it to 0;
So, every time the user scores the right answer, we will increment the result.
This means that for each question object inside of this questions array, i want to do
something.
The first is to ask the user a question and to store the answer in a variable;
Then we need to see if the user will get the question right and for that, we will use If
Statement;
This mean it will add the score by one if the answer is correct.
Then, we print the score of the user- you got 1/3 question or 0/3 question or 3/3 question
Then;
Now, lets run the program;
Object Functions:
We define a function inside the student class and then all the student objects can access it.
So, lets say we want to create a function that told us whether or not this particular student
has honors.
We could define a function that will tell us if that particular student is on honor rolls;
Inheritance:
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
If we create a file calls Chief and in this chef class, the chef can do 3 things;
Now, let’s say we want to create another class to model another type of chef.
For example, lets say we want to create a class that modeled a Chinese Chef.
Now, lets say te Chinese Chef can do everything that our generic chef can do. So the
Chinese Chef is like a special chef - a specific type of chef.
So, like the Chinese Chef can ‘make chicken’, can ‘make salad’ and can ‘make special dish’
If we want to give the Chinese Chef all that functionality, we could just copy paste from the
normal chef to the chinese chef.
Lets say that the Chinese Chef can make additional things
When we go back to the app.py file, we want to create a Chinese Chef object.
So, remember, the ChineseChef can do everything the normal Chef can do.
But the problem here is that when we go to the ChineseChef.py, we want to use all the
functionality that was inside this chief class
We had to copy and physically paste from the Chef.py file to the ChineseChef.py file.
There is a function called inheritance. So instead of copy paste all of the functions in a fule,
we could just inherit these functions from that chef class.
To do that;
This means that inside of the ChineseChef, we want to be able to use all the functions that
are contained inside the Chef class.
By using inheritance, we are still able to run the program in the app.py file.
The issue is for special dish. The ChineseChef was supposed to make orange chicken but
when we run the program;
How to solve?
What we can do if to go on the ChineseChef file and override that ‘make special dish’.
When we go back to our app.py file and try to run the program;
Python Interpreter:
https://www.youtube.com/watch?v=rfscVS0vtbw