Download as pdf or txt
Download as pdf or txt
You are on page 1of 129

How to change the name/ piece of information of a variable in a set of code?

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.

Check the following steps below.

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.

When running the code, it appears like this;


What Python is doing is that in the line of code, it sees the character name and wants to print
the value that was given to the character name.

Copy paste where there is the character name, which is john.

All what to do is to change the variables name.

Lets say halfway, we want to change our character’s name to Mike.


A string is basically plain text. “Tom”, “50” that iare stored. Both name, and number. For
numbers, there is no need for a for a quotation mark. A quotation mark is only used to store a
string.

Python can also store decimals.

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:

Strings are basically plain text.

In order to print a string, you need to use quotation mark.

One thing that can also be done is to create a new line inside of the string.

This will put the 2 words on 2 separate lines.


Another possibility;

This is called the escape character. It tells Python that any character that comes after it, we
want to render it literally.

This is basically to print a quotation mark.

You can also create a variable.


There is something called concatenation. It basically puts 2 strings together.

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.

The same thing for upper case,

To see now if the string is upper or lower case,


The result will be false because “Giraffe Academy” is not completely in upper case. So the
result is False ( boolean result).

We can also use functions in combination with each other.

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.

Len- the length function.

We can also get individual characters inside of a string.


In Python, when working with strings, the string index starts with 0.

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.

The result is 3 because a is at position 3.


If we put a letter that doesn’t exist, there is going to be an error.

There is also the function replace. Here, we can give 2 parameters.

The giraffe was replaced by elephant.

Working with numbers:

First, if we want to print a number, or even a decimal number, and a negative number.

Number Decimal number Negative number


You can also do basic arithmetic on Python.

Addition- “+”

Subtraction- “-”

Division- “/”

Multiplication- “*”

NOTE: do not put quotation mark.

Order of operation- you can add parenthesis.


There is also the modulus operator.

For example, print(10%3) This is actually read as 10 mode 3.

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.

We can also store these numbers inside a variable containers.


What can also be done is to convert a number into a string.

Now this has become a string.

You can even add a string.

If the number was not converted into a string, there would have been a problem.
There is also abs which is the absolute number.

The value is 5 because 5 is the absolute value of -5.

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.

The answer is 6 because 6 is the maximum number.

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.

There is another thing called importing.

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 the code.

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.

Getting input from users:

Allow a user to put information in our program.

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.

Inside the parentheses, we put a prompt.

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.

We can even add multiple pieces of information.


When running this program, it will go like this;

Building a basic calculator:

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.

Enter the user’s input inside these 2 variables.

Now, we want to print out the result.


Looking at the result, that was not the result that we were expecting to get.

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.

This error occurred because the int function was used.

This int function is looking for a whole number.

How to solve that?

The use of the function float are for decimal numbers.

Then the result will be;

With this function, you can put any kind of numbers.


Mad Libs Game:

A Mad Libs Game is a game where you can answer a bunch of random words like verbs,
nouns, names, colours.

An example of Mad Libs Game;

How to create a Mad Libs Game on python?

Lets start with these.


Lets create a Mad Libs Game from these.

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.

This is the basic structure for a Mad Lip Game.

Second, how to built these in Python?

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;

Now, lets go back to the list.


If we run these program, we get this result;

What if we want to print a specific element inside of this list.

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

If we want to look for an element in our list, we just do this;

We can also access elements from the back of the list.

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.

We can also specify a range.

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.

For example, lets say i want to modify the value Karen.

The steps are as followed.

Instead of printing Karen, it will print Mike.

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

These 2 lists are storing a bunch of different values.

If we print the friend list, the result will be;


There are other functions that could be used.

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.

The index will be 0

Or lets see if the name of Oscar is in the list.


But if we put a name that isnt in the list;

The result will be an error as Mike is not 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.

The same will apply for lucky numbers.

We can also reverse a list by using the reverse function.


The result reverse the order of the list.

Then we can create another list and make it a copy.

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.

But Tuples have a few key differences from lists.

How to create a Tuple:

One of the common examples of tuples are coordinates.

For example, coordinates = ()

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,

This is a tuple coordinates.

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.

Tuples are index starting at 0

4 is at index position 0 and 5 is at index position 1

Then, the result will be,


What would happen if we had to change 1 element;

Here, there is an error- ‘tuple’ object does not support item assignment. This is because
tuples are immutable. It cannot be changed.

We can also create a list of tuples.

Here, there is a list and in the list, there is a set of tuples. The values cannot be changed.

Functions:

A function is a collection of codes that perform a specific task.

It helps to organise the codes.

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.

The following steps are as follows;

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 do so, we have to do something called calling the function.

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?

This is basically the flow of these functions inside the program.

When we run this program, we get this result;

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;

Python actually jumps up to the first line;

And will execute all of the code inside of the function.

Once its done executing the code, it will jump back to the last line,

Its like the flow of a function.

Thats why we get the result;


We can also make these functions a bit powerful. We can give them information. They are
called parameters.

A parameter is a piece of information that we give to a function.

At this stage, we can specify that this function needs to receive some parameters.

In order to do that, we just name the parameter we want to receive.

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

For example, like this;


What we can do now, we can actually access this parameter or variable inside of our
function.

Then,

It will just say hello to whatever name is shown in the highlighted part.

We can add also one more name.


When we run this program, the result is;

From the result, it actually print whatever name was pasted and not Hello User.

We can add also more parameters. As many as you wish

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.

For example, if we cube a number. First, we want to make a function.


This function will basically cube this number.

When we run the program, we see that nothing happened.

When we called this cube function cube(3) it didnt really do anything.

What if we print this out;


The result is none.

Actually, this function;

was
supposed to be cubing the number (the highlighted part).

This is where we use the return statement in Python.

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.

If Statements are statements that human beings deals everyday.

Here are a bunch of If Statements.

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;

The highlighted part is the condition.

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.

How If Statement works?

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.

Start with if and a condition that will be true or false.

For example,

What if we change is_male= False

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.

If we change the is_male= True

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.

We can use the or keyword.


This is basically see if the person is either male or tall, then we want to do something. This is
going to be true if only 1 or both of these values is true.

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;

If we set both variables to false;


There is another operator we can use called and. It means that both condition has to be true.
If the person is male and also tall, then we are going to execute .

This is because the 2 variables are set false.

If we make both variable true;


What if we make one of the variable False;

It is going to execute what is in the else.

What if we check more conditions- like what if they are male and not tall.

There is a keyword in python called else if (elif);

We want to check if they are male and not tall

This ‘not’ function will negate whatever is in the highlighted part.

We can also put another condition if they are not male and tall, we can use elif function;

If we set both variables to True;


If we set is_male=False

If we set is_male=True and is_tall=False

If we set both variables to false;


If Statements & Comparisons:

Using Comparisons in If Statements.

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.

What we are doing here is that we are comparing different numbers.

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.

It is the same for num1 >= num3

The highlighted part is a comparison operator.


If the highlighted part- this whole condition is true, then num1 is the biggest. Then, we can
just return num1.

We can also check some other condition by using elif function.

Then we can return num2

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.

If we change the number;

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.

Other comparison signs

== Check to see if the 2 values are equal.

!= Not equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Building a better calculator:

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.

Then, we will want to do for the operator.

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 can use If Statement to figure this out.

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;

the program will convert the full month name.

The first thing is to create a name.

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.

All the keys has to be unique. No key has to be repeated


Now we have created all the 12 months- a bunch of keys and each of those keys is
associated with a different value.

Now we can access to a key inside this dictionary.

To access a specific key or value, we have to refer to the dictionary by name.

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.

Another would be using this;

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.

Inside of this .get function;


The key doesnt have to be a string. It can also be a number, as long as they are unique.

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.

Here, we are using this i


value and additing it to 1.

Another possible way is;

It will automatically add 1 to i

We are going to keep looping in the code as long as this condition (the highlighted part) is
true.
The result is;

What python will see if if 1 is less tan and equal to 10.

It will go through this loop until this condition is done.

Building a Guessing Game:

First we need to create a variable to store our secret word.

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 then, what is going to happen is that we come back up here;

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;

Now, lets see when we run the game;


So we can type whatever we want. As long as we dont type the secret word, it will keep on
continuing.

But if we enter the secret word, this happens;

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;

Then, we add a out of guess variable and set to to a boolean value.


This out_of_guesses variable will be a boolean and will tell us whether or not the user is out
of guesses.

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.

Now to make these variables functional;

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.

Now, lets run it;

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.

Now, what if we win the game,

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.

The result will be;

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.

We can also pass in a number.

For example;

We can see that it is going the range from one to 10 excluding 10. Starting to 0 up to 9.

We can also specify between a range of 3 and 10;

It will print the numbers from 3-10 not including 10


Now, inside of this range, we can pass in the length of the array. If i want to get the length of
this array (the highlighted part);

Like, if we want to figure out how many elements were inside of it, we can just use the len
function;

The result will be 3 because there are 3 elements here.

What we can do if in the range function, we can type;

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;

What if we print a range up to 5?

What if we make this a special loop by using an If Statement;


Exponent Function:

An exponent function is going to allow us to take a certain number and raise it to a specific
power.

For example,

This is basically, 2^3 (2 power 3)

We will create an exponent function that will do this and we will use For Loops to do it.

Now, lets create a function.

Inside of this function, we need to start writing some code.

For example, if we knew we were just trying to square or cube this number, we could just
return the base num * base num;

But we don't know what the pow value will be.

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.

I can make this a range of pow num.

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.

And everytime through the loop we will multiply base_nu by itself.

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.

Then we return the result;


Then, we print the raise_to_power;

Another example;
2D Lists & Nested Loops:

2D Lists:

This is a basic list.

Normally, if we are creating a list, we could just put in a bunch of attributes and a bunch of
elements.

All these elements are inside these number grid list.

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.

First we make an open and close square brackets.


There are 4 elements in this grid list which are lists as well.

How to access individual elements inside this list structure.

Lets say we want to print out the 1.

To do so we write;

So in the open close quare brackets, we just put the row.

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.

And the result will be;


We are basically printing out one all the way
to zero. We are printing out all the elements inside of the arrays in the number_grid.

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, how to build a draft translator?

The first thing to do is to fine a translate function.


Inside of the paracentesis (), we want to take one piece of information, which is going to be a
phrase that we want to translate.

Now we need to figure our how to translate English into our draft language.

Then, we create a variable that will be the translation.

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.

Now, why dont we allow the user to put some information.

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;

And the result will be;

We can run the program as many time as we want.

Another example;
Another method regarding this line;

What we can do is;

The result will be the same.

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.

How to solve this problem?

We can use another If Statement;

Now, we can control both upper and lower case G / g


The whole code;

The result;

Now its keeping the capital letter.

Comments:

We have this program and when we run it;


There is also a special line of code that we can write and its called a comment.

A comment is basically a line inside our Python file that will not get rendered by python.

Comments starts with a #, and Python will ignore them:

The result will still be Hello, World!

Try Except:

In this part, we are going to see how to catch errors in Python.

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.

This will work.

What if we ignore the command and put some random text;

The program will throw an error.

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.

Lets see the result;


They were able to handle the error. This is to protect the program.

’except’ will catch any error


under the sun.

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.

We can actually catch and accept specific types of errors.

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.

When dividing by zero, we have the;

We can also make another except;


If we divided by zero, then the result will be;

But if we enter a wrong number, the result will be;


We can also store this error as a variable.

If we end up dividing by 0

It printed out the error.

Reading Files:

Here, we will learn about reading from external files in Python.

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.

Now how to use python to read employees inside of that file.

The first thing to do is open that file inside of python by using the open function

Between parenthesis we type the name of the file


we want to open.

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.

In this case, app.python and employees.txt are in the same directory;


Since they are in the same directory, we can just type the name of the file.

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.

We can open files in a couple of different modes.

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.

There is another one called ‘a’ which stands for append.


This mode means that you can append information onto the end of the file. You cannot
modify, change but you can only add new 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

Start watching the video.

When we open a file, we close the file as well.

How to get information form the file?

Before, how to check the file is readable?


The result is true, so it shows that the program is readable.

The result is false because we can only read the file.


The read mode will spit out whatever information was in that file.

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;

The result will be set in an array.

If we want to refer to a specific line, we just refer to its index.


We can also create a For loop;

Writing and Appending to files:

https://www.youtube.com/watch?v=rfscVS0vtbw

We can write new files and append new existing files.


What if we want to add a new person to the list.

We append to the file- add some text at the end of the file

If we print the result;

Nothing happens.

But if we go on the employees.txt;


The list is updated.

There could be some mistakes as well;

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;

This will create a new line

Now, it is on a new line.

Now, how to write a file?


Because there is a ‘w’, it is going to override the entire file.

When we run this;

Here, we only have one line, that is because we are using ‘w’ and it overrides everything that
is in that existing file.

We can also create a new file.

This will create another file when running this.

A new file has been added.


If we open this file, there is the same information as what is in employee.txt

If we want to create a webpage, we can write;

And when we run this;

Modules and Pip:

Modules:

https://www.youtube.com/watch?v=rfscVS0vtbw
Check the video.

Pip:

https://www.w3schools.com/python/python_pip.asp

Classes and objects:

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.

We can create a student class.

First, we create a new file.

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.

First, we create an initialise function by just typing def

We map out what attributes a student should have.

This is a student data type.

Then, we assign some values.

Then, we use that data type in the app.py file;


We can actually create an actual student and give it some information. That is called an
Object.

The student class is defining what a student is.

An object is an actual student with a name, module, gpa.

In order to use that student class and create a student object, we need to import that.

What we have to do is:

This means that from the student file (the highlighted part is the student file), we want to
import the student class.

After this, we can create a student.

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,

If we had another student;


Building a Multiple Choice Quiz:

How to build a multiples choice test?

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.

We need to create a file;

In the app.py file and we are going to create an array of questions.

We have 3 prompts. And we create questions objects;


We are creating 3 questions, and each one is getting a different prompt and a different
answer.

Then, we have to write a function that will run the test and ask the user the question.

Now, all i want to do is loop through all the questions.

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.

Then, we will create a For Loop;

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;

If this is true, we will increment the score;

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:

This is a student file where we created a student data type;

In the app.py file, we created 2 students;


What we can do is to use functions inside of these class files.

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;

Then, we apply a condition;

Now, if we run the program;


The result is false because student 1 has only a GPA of 3.1

If we did the same thing on student 2;

The result is true because it is bigger than 3.5

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;

When we go on the app.py file;


Now if we type myChef.make_chicken()

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.

First we need to create a ChineseChef file.

Then, we create a class;

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

Watch- it is more about the Terminal and the command.

You might also like