Python Lesson Part 2, 20 Out of 100
Python Lesson Part 2, 20 Out of 100
1/8/2024
-----------------------------------------------------------------------------------
---------------
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.
like this
while 1==1
print ("Help! I'm stuck in a loop!") ( this is indented)
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
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
-----------
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
--------------------------------
You can write this type code in another way like leave the variable blank
For loop = a statment that wil execute it's block of code a limited amount of times
---------------------
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)
-----------------------------------------
0
1
2
3
4
5
6
7
8
9
for i in range(10+1):
OR
print(i+1)
for i in range(50,100):
print(i)
exclusive = does not include the number you type basically just -1
----------------------------------------
50
51
52
53
...
... ( I don't wanna make this long you know )
...
95
96
97
98
99
-----------------------------------------
while i range(50,100+1)
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
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
like this
the result
10
9
8
7
6
5
4
3
2
1
happy new year!
---------------------------------------------------------------------
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
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
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="")
and our inner for loop ( columns) will iterate as many times as we have rows
after using the print prompt we will enter a new line of code when we run it... so
to prevent that
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()
33333333333333333333
but somehow bro code make it work... maybe it's in my pycharm settings that made me
fail ? not too sure
-----------------------------------------------------------------------------------
--------
loop control statement = change a loop execution from it's normal sequence
1st. Break
2nd. Continue
3rd. Pass
-------------------
@ 1st break
> used to terminate the loop entirely
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
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
---------------------------------
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
---------------------------------
----------------
@ 2nd continue
> skip to the next iteration of the loop
phone_number ="123-456-7890" ( str since we not gonna use this for math)
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
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
----
quick explanation i think.. with that if statement we check if there's dash (-) if
there's -
then we skip it...
@ 3rd. pass
> Does nothing, acts just like a placeholder
for i in range(1,21):
if i==13:
pass
else:
print(i)
Pass literally does nothing if you don't wanna use break / continue
--------------
for i in range(1,21):
if i==13:
pass
print(i)
-----------
-------------
for i in range(1,21):
if i==13:
break
print(i)
if we use continue
-------------
for i in range(1,21):
if i==13:
continue
print(i)
-----------------------------------------------------------------------------------
---
15th lesson. List
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"]
the result
--------------------------------------------------------
['pizza', 'hamburger', 'donut', 'indomie']
--------------------------------------------------------
If we want to access certain element inside the list, we have to list the index
like this
-------------------
print(food[])
-------------------
because computer always start with 0.
So if we want to access a certain element, put the element number inside the square
bracket
then
-------------
print(food[0])
Pizza
---------------------
hamburger
---------------------
print(food[2])
donut
---------------------
print(food[3])
indomie
---------------------
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
-----------------
print(food[0])
Ramen
-----------------
If you wanna display all of the element found within a list. you can easily do so
with a standard for loop
f x in food:
print(x)
------------------------------------------
A few function of list
to acess this, just like string function just add |.| after your list
like this
food.
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
-----------------------------------------------------------------------------------
-------
drink = ["juice","soda","coffee"]
dinner =["pizza","hamburger", "sushi"]
desert = ["cake", "donut"]
now let's create another list but this time the value would be other list
food = [drink,food,dessert]
print(food)
the result
-----------------------------------------------------------------------------------
-----------
[['juice', 'soda', 'coffee'], ['pizza', 'hamburger', 'sushi'], ['cake', 'donut']]
Then we do this
print(food[0])
the result
--------------------------------------
["juice","soda","coffee"]
--------------------------------------
print(food[1])
the result
--------------------------------------
['pizza', 'hamburger', 'sushi']
--------------------------------------
print (food[2])
the result
----------------------------------
['cake', 'donut']
----------------------------------
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
-----------------
tuple = collection which is ordered and unchangeable, they're very similar to list
but they're ordered and unchangeable
let's say we like to create some sort of student record so we can create a table
for us
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
like this
--------
student.
---
1st. Count
> Count how many times a value appear
print( student,count("male"))
for example
print( student,index("male"))
we type it
type x in student
print(x)
we write
if "filbert" in student:
print( "filbert is here")
the result
-------------------
Filbert is here
-------------------
-----------------------------------------------------------------------------------
-------------------------
18th lesson. Set
same like list and tuple but this time we surround our value with curly braces -->
{}
like this
utensils ={"fork","spoon","knife"}
for x in utensils
print(x)
fork
knife
spoon
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"}
----------------------
fork
knife
spoon
----------------------
---------
1st add
> adding a value into our set
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
---------------
---------------
and now
--------
4th. update
> where we add a set into a set
we type it
utensils.update(dishes)
if we try to run it
the result
-----------------------------------------------
fork
knife
spoon
cup
plate
napkins
bowl
-----------------------------------------------
dishes.update(utensils)
for a in dishes:
print(a)
the result
-----------------------------------------------
fork
cup
plate
knife
spoon
bowl
-----------------------------------------------
We can join two set together and create a new set entirely
dinner_table = utensil.union(dishes)
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 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
6th intersection
> checking the element set have in common
print(utensils.intersection(dishes))
the result
--------------------
{'knife'}
-----------------------------------------------------------------------------------
---------------
19th lesson..Dictionaries
let's create a dictionaries of countries and their capital, we gonna store those as
key: value pairs
capitals = {}
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
-------------
-------------
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..
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
-----------------------------------------------------------------------------------
--------------------------
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
inside that square bracket we gonna type the key. in this case it will be russia
print(capital["Russia"])
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
-----------------------------------------------------------------------------------
-
like this
print(capital.get["germany")
the result
-------------------------
None
-------------------------
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'])
---------------------------------------------------------------------------
print(capital.values())
the result
---------------------------------------------------------------------------
(['Washington DC', 'New Delhi', 'Beijing', 'Moscow'])
---------------------------------------------------------------------------
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
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
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
capital.pop(china)
the result
-----------------------
Error..
Why ???
Because i write it wrong.. my china C is capital while i not type it like that
-------------------------------
USA Washington DC
India New Delhi
Russia Moscow
-------------------------------
the result
-----------------------------------------------------------------------------------
-----------------
> 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
now we gonna use the if statment to see if our name is lower bracket or not
-------------------------------------------------------------------------------
NOTE
-------------------------------------------------------------------------------
-----------
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[])
---------------------------
you would a set of square bracket [] afterward then list the intreger of the
element / word that your trying to access
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
first_name = name[0:7].upper()
------------
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()
----------------------------
and make a quick change so that the first letter of our name have capital letter
on it
last_name = name[8:].lower()
print(last_name)
-------------
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
the result
---------------
aw
---------------