0% found this document useful (0 votes)
5 views

Python Lesson Part 2, 20 Out of 100

Uploaded by

filbert24si
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Lesson Part 2, 20 Out of 100

Uploaded by

filbert24si
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 28

part 2 11-20

1/8/2024

-----------------------------------------------------------------------------------
---------------

11th lesson. While loop

while look is a statement that will execute it's block of code as long it's
condition remain true

For this example where we create a program where we will prompt a user to enter
their name

if they attempt to skip that prompt then we will continually ask the user enter
their name and they
can't continue on with the rest of the program until they do so

something to keep in mind about while loop is that you want some way to eventually
escape the while loop
if don't have any way to escape the while loop then it's referred to as an
infinity loop.

let's create an example of infinity loop because it's fun

we type while and make the condition 1 equal to 1

like this

while 1==1
print ("Help! I'm stuck in a loop!") ( this is indented)

the result would be


------------------------------------------------------
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
Help! I'm stuck in a loop
-------------------------------------------------------
until infinity / keep on going

Because we have no way to escape this while loop

Now let's use this comcept and write a program where we prompt user to type in
their name

if they don't type anything then we will continue to prompt them to type in at
least something
let's create a user input asking for name

name= input("What is your name?:)

then create the while loop, while also checking our user input str lenght
if it's 0 / any number we put it will repeat the prompt

like this
-----------
while len(name) ==0
-----------

then indented to it we write


print(" Please enter your name: ")

then let's create a prompt that say hello after entering it

under while loop code type

print("Hello "+name)

Now let's run the code while not typing any value / str and just entering it

--------------------------------
What is your name? :
Please enter your name :
Please enter your name :
Please enter your name :
Please enter your name :
Please enter your name : Filbert

Hello Filbert
--------------------------------

the loop ended until I enter a string

You can write this type code in another way like leave the variable blank

examp : name = "" or name=none

but it will only print this message


-------------------------------------
Please enter your name :
Please enter your name :
Please enter your name :
Please enter your name :
Please enter your name : Filbert
-------------------------------------

12th lesson. For loop

For loop = a statment that wil execute it's block of code a limited amount of times

it's similar but different because

while loop = unlimited


for loop = limited
On this example let's create a for loop that will simply count it to 10 and then
we'll create a few
more sophiscated example

so let's create a for loop up to 10

this is what we'll type

---------------------
for i in range(10):
---------------------
let me explain

-----------------------------------------------------------------------------------
------
i = Index. This gonna act like a counter/ counting

( What letter example : A,B,C,D,E,F it will still work.. we just need a letter as
an index
to make loops (idk the in depth explanation)

in = of course inside of 10 because we wanna repeat this 10 times not outside of 10


range = until when you wanna loop it
-----------------------------------------------------------------------------------
------
The next lines of code will be indented, as it will be the block of code that are
gonna be
repeated 10 times

let's just print what | i| ( index ) is

the result would be

-----------------------------------------
0
1
2
3
4
5
6
7
8
9

as computer always start from 0


------------------------------------------

We can modify it a bit like

for i in range(10+1):

OR

print(i+1)

The result would be


------------------------------------
0
1
2
3
4
5
6
7
8
9
10
------------------------------------

This time let's count the range between two numbers

make it like this

for i in range(50,100):
print(i)

the first number is starting point and it's inclusive

the 2nd number is the ending point and it's exclusive

note incase i forgot

inclusive = include the number you type

exclusive = does not include the number you type basically just -1

now let's try to run it

----------------------------------------
50
51
52
53
...
... ( I don't wanna make this long you know )
...
95
96
97
98
99
-----------------------------------------

we can make this too 100 by doing some modification like

while i range(50,100+1)

then it will count from 50 to 100 not 99 this time

but if you add another coma and input any number


while i range(50,100+1,2)

it will count every 2 words

let's try
----------------------------------

50
52
54
56
...
...
...
96
98
100
-------------------------------------------
Work exactly like string slicing

the benefit of for loop is we can iterate anything that is considered iterable this
could include
a letter in the string or any sort of collection

so now let's create a for loop will iterate once through each letter maybe a
name...

so let's code it

for i in "Filbert Ang"


print(i)

now the result would be


---------------------------------
F
i
l
b
e
r
t

A
n
g
-------------------------------

now we're going to create a program where wegoing to simulate a countdown starting
at 10 counting down to 0

to create this we need import so at the top of all line of code type

import time

because we be waiting 1 second after each iteration of this for loop


for seconds ( this is not needed. as you can type anything here... you can type it
as "I" it doesn't matter )
after |for| then write | in range| after it

like this

for seconds in range(10,0,-1):


print(seconds)
time.sleep(1)

print("happy new year")

here's the line of code and result


-----------------------------------------------------------------------------
import time

for seconds in range(10,0,-1):


print(seconds) ( I delete the other line program)
time.sleep(1) ( to not get it confusing )

print("happy new year!")

the result
10
9
8
7
6
5
4
3
2
1
happy new year!

---------------------------------------------------------------------

13th lesson. Nested loop

Nested loop in general conceptis having a one loop inside of another loop it
doesn't matter if it's for loop and while loop

nested loop = the" inner loop" will finish all of it's iteration before finishing
one iteration of the "outer loop"

to best demonstrate this we're going to create a program where we will draw a
rectangle made out of a certain symbol that
we choose

We need to set a witdh ( lebar/ column(kolom)) and a height ( panjang / tinggi /


row(baris))

so to best do that we need to use nested loop

let's create a few prompth one for column, row and a symbol that we gonna use to
make rectangle with.
let's begin with row

Look's like we're making it where user can make a rectangle with code we have

rows = int(input("how many rows?: ")) ( cause we need to ask number)


column = int(input("how many column?: "))
symbol = input(" enter a symbol to use: ")

let's create the for loop

for i in range(rows):
for J in range (columns): ( this is indented to the row for loop)
print(symbol, end="")

-------------------------------------
explanation we create a loop based on the answer from user input

reminder that after for | index| it doesn't matter what letter i put for example

for B in range(rows):
for F in range (columns):
print(symbol, end="")

it would still work

and our inner for loop ( columns) will iterate as many times as we have rows

now the explanation for the print

it's indented under for j in range (columns):

for J in range (columns):


print(symbol, end="")

and now for the explanation for the print symbol

after using the print prompt we will enter a new line of code when we run it... so
to prevent that

we use print(symbol, end="")

this will prevent our cursor from moving down to the next line

---------------------------------------------

after that we create a new line of code not indented or inside the nested loop

print()

so it will create a new line

the result would be

33333333333333333333

I don't know why it didn't work....

but somehow bro code make it work... maybe it's in my pycharm settings that made me
fail ? not too sure

-----------------------------------------------------------------------------------
--------

14th. lesson. Loop control statement

loop control statement = change a loop execution from it's normal sequence

There are three we going to discuss..

1st. Break
2nd. Continue
3rd. Pass
-------------------

@ 1st break
> used to terminate the loop entirely

for this example

let's create a line of code similar to the 11th lesson where we ask the user to
input their name..
if they don't type anything then the while loop will loop over and over again

We cannot use this 11th lesson variant


--------------------------------
name= input("What is your name?:)

while len(name) ==0


print("please enter your name: " )
--------------------------------

because if we use break under print then the loop will just be over after it print
the message.. because
of how nested loop work so we need to change this a bit

like this
--------------------------------------------
While True:
name =input(" please enter your name: ")
if name!="":
break
--------------------------------------------

Basically what this code mean is that it will repeat the same message " please
enter your name:" if the user
didn't put anything in there hence why we only write the if statement like this
"" cause it empty / the
user not inputing anything

Then there will a new line of code indented to if statement we gonna make break
prompt on that one after the
user enter something

so the result would be

---------------------------------
please enter your name:
please enter your name:
please enter your name:
please enter your name:
please enter your name:
please enter your name: fil
---------------------------------

then it stop after we enter something

----------------
@ 2nd continue
> skip to the next iteration of the loop

Let's say we have a phone number

we enter a random one

phone_number ="123-456-7890" ( str since we not gonna use this for math)

now let's create for loop

for i in phone_number:
if i =="-"

if statement here we use to check if there's a dash in our number then add

continue

let's print the number

print (i)

if we do it like that once we run the code the result would be:
----
1
2
3
4
5
6
7
8
9
----

so to prevent that we add | end=| like the previous lesson

print (i, end="")

here's the end result of the line of code


------------------------------
for i in phone_number:
if i =="-":
continue
print(i,end="")
------------------------------

quick explanation i think.. with that if statement we check if there's dash (-) if
there's -
then we skip it...

so the end result


---------------------------------
12344567890
---------------------------------

@ 3rd. pass
> Does nothing, acts just like a placeholder

let's say we wanna print a number from 1 to 20 using for loop

for i in range(1,21):
if i==13:
pass
else:
print(i)

we skip the number 13 because of else...

Pass literally does nothing if you don't wanna use break / continue

let's change this a bit to be much clearer...

--------------
for i in range(1,21):
if i==13:
pass
print(i)

the result 1-20 ( including 13)

-----------

if we were to use break

-------------
for i in range(1,21):
if i==13:
break
print(i)

the result 1-12


-------------

if we use continue
-------------
for i in range(1,21):
if i==13:
continue
print(i)

the result 1-20 ( without including 13 )


-------------

-----------------------------------------------------------------------------------
---
15th lesson. List

List = used to store multiple items in a signle variable

for example let's say we have a variable called food..

we can make this variable to hold several value.

so first we're going to surround all of the values we would like to add to our with
a set of square bracket []

now let's try to enter multiple string value into that variable

-----
food = ["pizza", 'hamburger', "donut", "indomie"]

now what happen if we try to print that variable

the result
--------------------------------------------------------
['pizza', 'hamburger', 'donut', 'indomie']
--------------------------------------------------------

Each item in a list is called element


-----------------------------------------

If we want to access certain element inside the list, we have to list the index

So next to our list let's add a set of square bracket

like this

-------------------
print(food[])
-------------------
because computer always start with 0.

the element number 0 would be pizza

the element number 1 would be hamburger

the element number 2 would be donut

the element number 3 would be indomie

So if we want to access a certain element, put the element number inside the square
bracket

like for example we wanna access element 0

then
-------------
print(food[0])

once we run it the result would be

Pizza
---------------------

let's try the other


---------------------
print(food[1])

once we run it the result would be

hamburger
---------------------
print(food[2])

once we run it the result would be

donut
---------------------
print(food[3])

once we run it the result would be

indomie
---------------------

what if we try to access index 4 that doesn't exist ?

the result would be like this


-------------------------------------
print(food[4])

once we run it the result would be

IndexError: list index out of range


-------------------------------------

then if we try to add another element


-------------------------------------
['pizza', 'hamburger', 'donut', 'indomie', ' sushi']

print(food[4])

result would be

sushi
-------------------------------------

One important concept with list is that you can always update and change the
element within the list

later on in the program after you declare one

let's say we wanna immediately change one of these element

we write it like this

food[0] = " ramen"

now let's try to print this element

-----------------
print(food[0])

the result would be

Ramen
-----------------

This would be no longer pizza because we update the element 0 to be ramen

If you wanna display all of the element found within a list. you can easily do so
with a standard for loop

we write it like this

f x in food:
print(x)

the result would be


----------------------------
ramen
hamburger
donut idk why we don't just print it to display it all not using for
loop...
indomie
sushi
-----------------------------

------------------------------------------
A few function of list

to acess this, just like string function just add |.| after your list

like this

food.

then there's a bunch to choose from we gonna introduce a few


---------------
1st append

adding value to your list

for example
-----------------------------------------
food.append("nasi goreng")

f x in food:
print(x)

the result
ramen
hamburger
donut
indomie
sushi
Nasi goreng
------------------------------------------
2nd. remove
> remove value... no need other explanation ;/

food.remove("donut")

the result
------------------------------------------
ramen
hamburger
indomie
sushi

I turn off the oter line of code with # so it doesn't interfere and explanation is
much simpler

-------------------------------------------------------

3rd. pop
> remove the last element. |Just for refrences - ramen |
| - hamburger |
| - donut |
| - indomie |
| - sushi |

food.pop()

the result :
--------------------------
ramen
hamburger
donut
indomie
------------------------------

4th. Insert
> adding new element into element number you want to

For example

food.insert(0,"cake")
------------------------
the result would be
- ramen
- hamburger
- donut
- indomie
- sushi
------------------------

5th. sort
> Sort the list alphabetically

food.sort()

the result
-------------------------------------------------------
['donut', 'hamburger', 'indomie', 'pizza', 'sushi']
-------------------------------------------------------

6th clear
> will clear all the element on the list

food.clear

the result
--------------------

--------------------

nothing..

anyway that's it

-----------------------------------------------------------------------------------
-------

16th lesson. 2d list / multi dimensional list

2d list = list of a list

let's create seperate list

drink = ["juice","soda","coffee"]
dinner =["pizza","hamburger", "sushi"]
desert = ["cake", "donut"]

It doesn't need to have the same value / element

now let's create another list but this time the value would be other list

food = [drink,food,dessert]

ok now what happen if we print this

print(food)

the result
-----------------------------------------------------------------------------------
-----------
[['juice', 'soda', 'coffee'], ['pizza', 'hamburger', 'sushi'], ['cake', 'donut']]

this is drink this is dinner this is dinner


-----------------------------------------------------------------------------------
-----------

So what if we want to access one of these list only

Then we do this

print(food[0])

this will access

the first list that is drink

the result
--------------------------------------
["juice","soda","coffee"]
--------------------------------------

Let's try the other one

print(food[1])

the result
--------------------------------------
['pizza', 'hamburger', 'sushi']
--------------------------------------

print (food[2])

the result

----------------------------------
['cake', 'donut']
----------------------------------

What if we want to access one of these element inside of the list

we just add another square bracket then enter the number of our element

for example

print(food[1][0])

the result

----------------
Juice
----------------

print (food[0][1])
----------------
Soda
----------------
print (food[0][2])

-----------------
coffee
-----------------

17th lesson. Tuple

tuple = collection which is ordered and unchangeable, they're very similar to list
but they're ordered and unchangeable

they are useful for grouping together related data

let's say we like to create some sort of student record so we can create a table
for us

let's called a tuple called student

process of creating tuple is similar to list but this time we're going to surround
our value with paranthesses | () |
inside of that we can put a bunch of value related to student information

we're going to put name, age and gender inside of that

like this

student= ("filbert","17", "male")

--------

Now we gonna learn a few function related to tuples by typing

student.

it's not as many as list

---
1st. Count
> Count how many times a value appear

let's count how many times the value of male appear

so we type it like this

print( student,count("male"))

the result would be


-------------------------
1
-------------------------

2nd function Index


> Finding the index of value

for example

print( student,index("male"))

the result would be


-----------------
1
2
-----------------

We can display all the content of tupple with for loop

we type it

type x in student
print(x)

the result would be


-----------
Filbert
17
male
-----------
we can also check if a certain value exist within our tuple using | if| statement

we write

if "filbert" in student:
print( "filbert is here")

the result
-------------------
Filbert is here
-------------------

-----------------------------------------------------------------------------------
-------------------------
18th lesson. Set

set = a collection which is unordered, unindexed and no duplicate value

let's create a set

same like list and tuple but this time we surround our value with curly braces -->
{}

like this

utensils ={"fork","spoon","knife"}

Now let's display all our value

for x in utensils
print(x)

let's try to run it


-------------------------

fork
knife
spoon

if i try to run it again

knife
fork
spoon

-------------------------

As you can see it's different from list and tuples as it's unordered

A set actually run faster than a list if you just want to check something within a
set compared to a list
and they do not allow any duplicate value

for example let's add another value called knife. The exact same valae
utensils ={"fork","spoon","knife","knife"}

And let's try to run it

----------------------
fork
knife
spoon
----------------------

cause it not allowed duplicate

---------

Now we gonna learn a few function in a set

1st add
> adding a value into our set

we write it like this

utensils.add("napkins")

run it

-----------------
spoon
fork
knife
napkins
-----------------

2nd. remove
> remove a value

utensil.remove("knife")

run it
----------------
fork
spoon
----------------

3rd. clear
> clear all value

utensils.clear()

run it
---------------

---------------

as it clear all value

For this example we have to make another set


dishes ={"plate","bowl","cup"}

and now

--------

4th. update
> where we add a set into a set

in this case we gonna add dishes into our utensils

we type it

utensils.update(dishes)

if we try to run it

the result
-----------------------------------------------
fork
knife
spoon
cup
plate
napkins
bowl
-----------------------------------------------

what if switch it arround

dishes.update(utensils)

for a in dishes:
print(a)

the result
-----------------------------------------------
fork
cup
plate
knife
spoon
bowl
-----------------------------------------------

well it wouldn't be that much different since it's unordered

We can join two set together and create a new set entirely

dinner_table = utensil.union(dishes)

change the print

for a in dinner_table:
print(a)

result
------------------------------------------------
bowl
cup
fork
spoon
plate
knife
------------------------------------------------
5th and 6th

There are also a method where we can compare a similarities as well as the
differences between the element found within 2 sets

let's see what utensil has and dishes doesn't

let's add another element on dishes that are the same with utensil so they have 1
in common let's add knife

dishes ={"plate","bowl","cup","knife"}

5th difference

print(utensils.difference(dishes))

this line of code is telling what utensil have that dishes don't

let's try to run it


-------------------------
{'spoon', 'fork'}
-------------------------

we can reverse the role also

print(dishes.difference(utensils)) (what dishes have that utensils don't have )


remember we add knife element into our dishes set
--------------------------
{'cup', 'bowl', 'plate'}
--------------------------

6th intersection
> checking the element set have in common

we type it like this

print(utensils.intersection(dishes))

the result
--------------------
{'knife'}
-----------------------------------------------------------------------------------
---------------

19th lesson..Dictionaries

Dictionaries = A changeable, unordered collection, that allow you to store key-


value pairs.
fast because they use hashing, allow us to access value quickly
creating a dictionaries is very similar to creating a set except we're going to
store unique key: value pairs

let's create a dictionaries of countries and their capital, we gonna store those as
key: value pairs

Let's call the dictionaries capital

capitals = {}

We need a key and a value

let's make USA the key and the capital of the USA would the value.

In order to asociate it we need to follow the key with a colon like this
-------------

capitals = {"USA":"Washington DC"}

-------------

data type here doesn't matter but for this example we gonna use string

Let's add another capital, to seperate another key value pair just use a coma..

it gonna like this


-----------------------------------------------------------------------------------
--------------------------
capital = {"USA":"Washington DC", "India":"New Delhi", "China":"Beijing",
"Russia":"Moscow"}

But we can seperate each key value pairs by pressing enter ( not shift enter) after
the coma so it goes down
so it's much more organized

like this

capital = {"USA":"Washington DC",


"India":"New Delhi",
"China":"Beijing",
"Russia":"Moscow"}

-----------------------------------------------------------------------------------
--------------------------

Now we have dictionaries called capital with it's unique key value pairs

In order to access one of these value using numbered index, we're going to use to
associated key
with that value

example

we want to try to print the capital of russia

let's type in print


print(capital[])

inside that square bracket we gonna type the key. in this case it will be russia

print(capital["Russia"])

let's try to run it

the result

------------------

Moscow
------------------

this method isn't always safe.. let's say we try to use a key that doesn't exist
like for example

Germany

print(capital["Germany"])

If we try to run this, the result would be error and this will interupt the flow of
the program

A much safer way to access a key to see if it's there or not , is to use get
method

so let's turn this line into a comment

-----------------------------------------------------------------------------------
-

comment = turning the line of code off by using # at the start


-----------------------------------------------------------------------------------
-

The on a new line of code let's try to use get method

like this

print(capital.get["germany")

the result
-------------------------

None

-------------------------

2nd method. keys

If you wanna show only all of your key then you use the keys method

Like this

print(capital.keys())

the result
---------------------------------------------------------------------------
(['USA', 'India', 'China', 'Russia'])
---------------------------------------------------------------------------

3rd method. values

If you only wanna show all your value

print(capital.values())

the result
---------------------------------------------------------------------------
(['Washington DC', 'New Delhi', 'Beijing', 'Moscow'])
---------------------------------------------------------------------------

4th method. Items

If you wanna show all your keys and value

print(capital.items())

the result
-----------------------------------------------------------------------------------
-------------
([('USA', 'Washington DC'), ('India', 'New Delhi'), ('China', 'Beijing'),
('Russia', 'Moscow')])
-----------------------------------------------------------------------------------
-------------

Another way we can display all of the key value pairs in dictionary is using for
loop

let's make it

for key, value in capital.item():


print(key,value)

the result
-----------------------------------------------------------------------------------
-------------
USA Washington DC
India New Delhi
China Beijing
Russia Moscow
-----------------------------------------------------------------------------------
-------------

Another featurew of dictionaries is that they are mutable/ changeable or alter them
after the program is already
running

One way to do that is to use the update method

Let's add Germany as a key and berlin as the value

let's write that

capital.update({"Germany":"Berlin"})
now let's try to print our dictionaries again

the result
----------------------------------------------------
USA Washington DC
India New Delhi
China Beijing
Russia Moscow
Germany Berlin
----------------------------------------------------

with this method you also can update an existing key value pairs

for example we gonna change the capital of the USA

just do it like this


---
capital.update({"USA":"Filbert"})
---

now once we run the code and print it again

the result would be


-------------------------------------------------
USA Filbert
India New Delhi
China Beijing
Russia Moscow
-------------------------------------------------

2nd method to modify the dictionaries pop


> remove key value pairs from the dictionaries

capital.pop(china)

the result
-----------------------

Error..

Why ???

Because i write it wrong.. my china C is capital while i not type it like that

that's why the code is wrong

Let's try again

-------------------------------

USA Washington DC
India New Delhi
Russia Moscow
-------------------------------

the result

3rd method. clear


a method that will clear all your dictionaries

this need to explanation or example.. as there are already a bunch of it...

-----------------------------------------------------------------------------------
-----------------

20th. Index Operator that is represented by a set of square bracket []

> Give access to a sequence's element.. they include but not limited to (str,list
and tuples)
( that mean we prolly can use intreger, Float, etc ( not sure though))

For this example we're going to use string because string are easy to work with

let's create a variable using our name

name = " filbert ang"

now we gonna use the if statment to see if our name is lower bracket or not
-------------------------------------------------------------------------------

NOTE

lower bracket = a letter that is not capital


Higher bracket = a capital letter

-------------------------------------------------------------------------------

let's write the if statement


----------------------
if(name[0])
----------------------
we add square bracket after name then type in the number of the word of your
choosing in the example
i gonna check word 0

then add a | islower| method to check if it's lower bracket

-----------
if (name[0]).islower())
-----------

now we gonna make the first letter of our name that is lower bracket into high
bracket by doing this
---------------------------
if (name[0]).islower())
name = name.capitalize[])
---------------------------

let's print and run it

the result would be


-----------------------------------
Filbert ang

compared to the original : filbert ang


-----------------------------------
So if you need to access a element within a sequence, a string or a list

you would a set of square bracket [] afterward then list the intreger of the
element / word that your trying to access

Let's create another example...

Let's say we would like to create some substring and we can do so by using our
index operator.

so i wwould like to create a sub string with the first part of our name

so what we do is create a new variable

first_name = name[0:7].upper()

we gonna add upper for more extra example..

now let's try to print it

------------
print(first_name)

the result

FILBERT
------------

Remember the shortcut where we don't enter anything on start / end part

like
----------------------------
first_name= name[ :7].upper()
----------------------------

if we do it like that we gonna start from 0

and let's try to create a new variable using shortcut

and make a quick change so that the first letter of our name have capital letter
on it

So that this code / example will work

name= "filbert Ang"

last_name = name[8:].lower()

print(last_name)

the result would be

-------------
filbert ang
-------------

We can also access the last character of our element / word using negative indexing
( just like in the first part)

we create a ne wvariale

last_character = name[-1]

print last_character

the result
-----------
g
---------

change it a bit

last_character = name [-3]

the result
---------------
aw
---------------

You might also like