Python — Basic Review before diving deeper 02
Want to recall the memory of Python easily?
This is the note taken while I was learning Python “again”, hope it helps you too.
There are additional links in the article for you to understand further information.
Directory
- Indexing
- Format specifiers
- Exercise 01 — countdown timer
- Exercise 02 — credit card
- Collection — List, Set, Tuple
- Exercise 03 — shopping cart
- 2D-List
- Exercise 04 — Numpad
- Conclusion of 2D-Collection
❤️Good Resources
Reminder
Indentation is important in python, be aware it.
more info can be seen | here
Indexing⚡
Can be used in string, list, etc.
- more info | String
- more info | List
indexing =
accessing elements of a sequence using [ ] (indexing operator)
[start : end : step]
— Bro Code
credit_number = "1234-5678-9ABC-DEFG"
print(credit_number[0])
print(credit_number[:3])
print(credit_number[6:9])
print("*************")
print(credit_number[6:])
print(credit_number[-1])
print(credit_number[::2])You can try reversal in this way.
credit_number = "1234-5678-9ABC-DEFG"
print(credit_number[-4:]) #DEFGFormat Specifiers⚡
format decimal precision
a = 3.14159
b = -987.654
c = 543.687
print(f"a is {a:.3f}")
print(f"b is {b:.2f}")
print(f"c is {a:.1f}")format space
a = 3.14159
b = -987.654
c = 543.687
print(f"a is ${a:10f}")
print(f"b is ${b:10f}")
print(f"c is ${a:10f}")Clean Space
& addtional zero in the frontal spaces
a = 3.14159
b = -987.654
c = 543.687
print(f"a is ${a:10}")
print(f"b is ${b:10}")
print(f"c is ${a:10}")
print("***********")
print(f"a is ${a:010}")
print(f"b is ${b:010}")
print(f"c is ${a:010}")Alignment
- to the centre
- to the left
- to the right
a = 3.14159
b = -987.654
c = 543.687
# center
print(f"a is ${a:^10}")
print(f"b is ${b:^10}")
print(f"c is ${a:^10}")
print("***********")
# to the left
print(f"a is ${a:<10}")
print(f"b is ${b:<10}")
print(f"c is ${a:<10}")
print("***********")
# to the right
print(f"a is ${a:>10}")
print(f"b is ${b:>10}")
print(f"c is ${a:>10}")Positive or Negative
a = 3.14159
b = -987.654
c = 543.687
# positive
print(f"a is ${a:+}")
print(f"b is ${b:+}")
print(f"c is ${c:+}")
print("***********")
# negative
print(f"a is ${a:-}")
print(f"b is ${b:-}")
print(f"c is ${c:-}")Comma
a = 3000.14159
b = -9870000.654
c = 543000000.687
print(f"a is ${a:,}")
print(f"b is ${b:,}")
print(f"c is ${a:,}")Mix
positive & comma & two as decimal precision
a = 346544.14159
b = -9465687.654
c = 547893.687
print(f"a is ${a:+,.2f}")
print(f"b is ${b:+,.2f}")
print(f"c is ${a:+,.2f}")
Countdown Timer⚡
Exercise 01
import time
the_time = int(input("Enter the time in seconds: "))
for i in range(the_time, 0, -1):
print(i)
time.sleep(1)
print("TIME'S UP!")How about longer time?
import time
the_time = int(input("Enter the time in seconds: "))
for i in range(the_time, 0, -1):
seconds = i % 60
minutes = int(i / 60) % 60
hours = int(i / 3600)
print(f"{hours:02}:{minutes:02}:{seconds:02}")
time.sleep(1)
print("TIME'S UP!")Easy Credit Card Validator
exercise 02
Rules
- It must contain exactly 16 digits.
- It should only contain 0–9 digits.
- It must start with either 9 or 7 or 3.
- It may have digits in a group of 4 with a separator (-).
- It must not contain any other symbols such as _ or space(‘ ‘).
Steps
- Remove ‘-’ or ‘ ‘(blank space)
- from right to left, add every odd digits
- from right to left, double every even digits (add the two-digit number together to get the single number)
- sum step 2 & step 3
- If the sum can be devided by 10, the credit card number is valid.
Test credit card numbers
Test Credit Card Account Numbers
American Express 378282246310005
American Express 371449635398431
American Express Corporate 378734493671000
Australian Bankcard 5610591081018250
Diners Club 30569309025904
Diners Club 38520000023237
Discover 6011111111111117
Discover 6011000990139424
JCB 3530111333300000
JCB 3566002020360505
MasterCard 5555555555554444
MasterCard 5105105105105100
Visa 4111111111111111
Visa 4012888888881881Step 1
sum_odd = 0
sum_even = 0
total = 0
# step 1
card_num = input("Enter a credit card number: ")
card_num = card_num.replace("-", "")
card_num = card_num.replace(" ", "")
print(card_num)Step 2
Let’s test the for loop.
for i in card_num[::1]:
print(i)Remember to convert the credit card numbers from string input to integer value.
# step 2
for i in card_num[::2]:
sum_odd += int(i)Step 3
# step 3
for i in card_num[1::2]:
i = int(i) * 2
if i >= 10:
sum_even += (1 + (i % 10))
else:
sum_even += iStep 4
# step 4
total = sum_odd + sum_evenStep 5
# step 5
if total % 10 == 0:
print("The credit card number is valid.")
else:
print("The credit card number is invalid.")Whole codes
sum_odd = 0
sum_even = 0
total = 0
# step 1
card_num = input("Enter a credit card number: ")
card_num = card_num.replace("-", "")
card_num = card_num.replace(" ", "")
# step 2
for i in card_num[::2]:
sum_odd += int(i)
# step 3
for i in card_num[1::2]:
i = int(i) * 2
if i >= 10:
sum_even += (1 + (i % 10))
else:
sum_even += i
# step 4
total = sum_odd + sum_even
# step 5
if total % 10 == 0:
print("The credit card number is valid.")
else:
print("The credit card number is invalid.")Collection
- Single “variable” used to store multiple values. — Bro Code
- Python’s
collectionsmodule provides a rich set of specialized container data types — realPython - They are called as Data Sturcture as well. 🔥🔥🔥
List⚡
- List = [ ] ordered and changeable. Duplicates OK. — Bro Code
- Actually it’s the term “array” in other languages — ZeroToMastery
So, how to use index and print multiple values out?
# List
fruits = ["apple", "banana", "lemon", "peach"]
print(fruits[0])
for i in fruits:
print(i)dir
Some attibutes and methods we will discuss in the future
# List
fruits = ["apple", "banana", "lemon", "peach"]
print(dir(fruits))Commonly used methods
- append
- clear
- copy
- count
- extend
- index
- insert
- pop
- remove
- reverse
- sort
If you want to see more description of each method, you can try “help”
help
# List
fruits = ["apple", "banana", "lemon", "peach"]
print(help(fruits))Length & Boolean
# List
fruits = ["apple", "banana", "lemon", "peach"]
print(len(fruits))
print("banana" in fruits)
print("coconut" in fruits)Let’s use methods!
Methods
# List
fruits = ["apple", "banana", "lemon", "peach"]
print(fruits.index("banana"))
fruits.append("coconut")
print(f"append - {fruits}")
fruits.remove("banana")
print(f"remove - {fruits}")
fruits.insert(0, "banana")
print(f"insert - {fruits}")
fruits.sort()
print(f"sort - {fruits}")
fruits.clear()
print(f"clear - {fruits}")What’s the difference between append and extend?
More info can be seen here | StackOverflow
List Extend Method | GeeksforGeeks
# extend
l = [1, 2, 3]
l.extend([4, 5, 6])
print(l)# append
l = [1, 2, 3]
l.append([4, 5, 6])
print(l)Basically, extend method merge the lists, but append method just add another list to the end of the original list.
pop
You can store the popped value.
# pop
l = [1, 2, 3]
l.extend([4, 5, 6])
l.pop()
print(l)
print("--------------")
l.pop(0)
print(l)l = [1, 2, 3]
l.extend([4, 5, 6])
popped = l.pop()
print(popped) # 6clear
You can store the cleared value too.
l = [1, 2, 3]
l.extend([4, 5, 6])
new_list = l.clear()
print(new_list)
print(l)Index
= Where is the thing?
More about index | GeeksforGeeks
How to find the index | freeCodeCamp
l = [1, 2, 3, 4, 5, 6]
print(l.index(4)) # 3l = ['A', 'B', 'C', 'D', 'E']
print(l.index('D')) # 3We can set the index for searching the element .
l = ['A', 'B', 'C', 'D', 'E']
print(l.index('D', 2, 4)) # 3l = ['A', 'B', 'C', 'D', 'E']
print(l.index('B', 2, 4)) # ErrorCount
l = ['A', 'B', 'C', 'D', 'E', 'D']
print(l.count('D')) # 2Sort
l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']
print(l.sort())
print(l)sorted
l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']
print(sorted(l))sort & sorted ?
The main difference between
sort()andsorted()is that thesorted()function takes a list and returns a new sorted copy of it.— freeCodeCamp
copy
Two ways to copy the list
l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']
c = l[:]
c2 = l.copy()
print(c)
print(c2)
# original list remains the same
print(l)
print(sorted(l))reverse
Notice that reverse just flips the list from left to right.
It’s not like sort method. You might encounter similar questions from the interviewers.
l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']
l.reverse()
print(l)
# clearer version
l2 = ['a', 'b', 'c', 'd', 'e']
l2.reverse()
print(l2)This works too.
l = ['a', 'b', 'c', 'd', 'e']
print(l[::-1])List range
print(list(range(1,100)))Join
Common pattern is like this
✅✅✅
s = ''.join(['Heyyyyy ', 'How ', 'Are ', 'UUUUUUUUU ','?????'])
print(s)And THIS is not gonna show you anything.
❌❌❌❌❌
s = ''
''.join(['Heyyyyy', 'How', 'Are', 'UUUUUUUUU','?????'])
print(s)List unpacking
a,b,c = [1,2,3]
print(a) # 1
print(b) # 2
print(c) # 3
And this is like magic.
a,b,c, *other, d = [1,2,3,4,5,6,7,8,9]
print(a)
print(b)
print(c)
print(other)
print(d)Set⚡
Set = { } unordered and immutable, but Add/Remove OK. NO Duplicated.
— Bro Code
# Set
fruits = {"apple", "banana", "lemon", "peach"}
print(dir(fruits))
print("****************")
print(help(fruits))Length & Boolean
# Set
fruits = {"apple", "banana", "lemon", "peach"}
print(len(fruits)) # 4
print("coconut" in fruits) # FalseNotice that there is no each usage in set.
Get Yen Wang’s stories in your inbox
Join Medium for free to get updates from this writer.
Because set is unordered, so there is no index as well.
# Set
fruits = {"apple", "banana", "lemon", "peach"}
print(fruits[0])# Set
fruits = {"apple", "banana", "lemon", "peach"}
print(fruits.index("banana"))Methods
Commonly used methods for beginners.
# Set
fruits = {"apple", "banana", "lemon", "peach"}
fruits.add("coconut")
print(f"add - {fruits}")
fruits.remove("banana")
print(f"remove - {fruits}")
fruits.pop()
print(f"pop - {fruits}")
fruits.clear()
print(f"clear - {fruits}")Let’s dive deeper now.
There is a list containing duplicates, and you want to make it a collection only containing unique elements.
Convert it to a set 🔥
a_list = [1,2,3,4,5,6,6,6,6]
print(set(a_list))Covert it to list??
a = {1,2,3,4,5,6}
print(list(a))in
Use it to return a boolean value.
a = {1,2,3,4,5,6}
print(3 in a) # Truecopy & clear
a = {1,2,3,4,5,6}
b = a.copy()
a.clear()
print(a)
print(b)There are more methods, but the rest is quite similar with the ones above.
Difference & Discard & Difference_update
Basically they show the results with comparing the difference.
Below, I collect the explanations for each method from W3School.
🔸Difference —Use the method to show the difference of a from b
🔸Discard — Remove the element
🔸Difference_update — The method is None, but the original set has changed only remain the different elements.
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9,10}
print(a.difference(b))
print(a)
print("------------------")
print(a.discard(5))
print(a)
print("------------------")
print(a.difference_update(b))
print(a)
print("------------------")🔸intersection — Return a set that contains the items that exist in both set a, and set b
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9,10}
print(a.intersection(b))
print(a)
print("------------------")🔸isdisjoint — Return True if no items in set a is present in set b
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9,10}
print(a.isdisjoint(b))
print(a)
print("------------------")🔸issubset — Returns whether another set b contains this set a or not
🔸issuperset — Returns whether this set a contains another set b or not
a = {4,5,6}
b = {4,5,6,7,8,9,10}
print(a.issubset(b))
x = a.issubset(b)
print(x)
print("------------------")
print(b.issuperset(a))
y = b.issuperset(a)
print(y)
print("------------------")🔸union — Return a set containing the union of sets
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9,10}
x = a.union(b)
print(x)Some useful shortcut…
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9,10}
# union
print(a | b)
# intersection
print(a & b)Tuple⚡
Tuple = ( ) ordered & unchangeable. Duplicates OK.
FASTER than List.
— Bro Code
🔸Dir
# Tuple
fruits = ("apple", "banana", "lemon", "peach")
print(dir(fruits))🔸Help
# Tuple
fruits = ("apple", "banana", "lemon", "peach")
print(help(fruits))🔸Length & Boolean
# Tuple
fruits = ("apple", "banana", "lemon", "peach")
print(f"Length is {len(fruits)}")
print("coconut" in fruits)
print("apple" in fruits)Useful method
🔸index
# Tuple
fruits = ("apple", "banana", "lemon", "peach")
print(fruits.index("banana")) # 1🔸Count
Interesting method
# Tuple
fruits = ("apple","coconut", "banana", "lemon", "peach", "coconut","coconut")
print(fruits.count("coconut"))🔸For loop
🔹iterable — list, dictionary, tuple, set, string
🔹iterate(an action) — one by one check each item in the collection
More info about nouns of iteration, iterable & iterator. — StackOverflow
# Tuple
fruits = ("apple","coconut", "banana", "lemon", "peach", "coconut","coconut")
for i in fruits:
print(i)We haven’t told about dictionary which will be discussed in Python — before diving deeper 03. But you can bear in mind with that tuple can be applied in dictionary.
user = {
(4,5): [1,2,3],
'greet': 'heyyy',
'age': 18
}
print(user[(4,5)])Integer is not iterable.
for i in 50:
print(i)But you can do this instead.
for i in range(50):
print(i, end=" ")Underscore
in for loop
# Ignore a value of specific location/index
for _ in range(10):
print ("Test")Indexing
user = (1,2,3,4,5,6)
x = user[2]
print(x) # 3You can assign the range as well.
user = (1,2,3,4,5,6)
x = user[1:4]
print(x)Unpacking in tuples!?
a,b,c, *sth = (1,2,3,4,5,6)
print(a)
print(b)
print(c)
print(sth)Shopping Cart⚡
Exercise 03
Rules
- User types food name each time
- Users types the price of the food each time
- User types q to quit
- After quitting, show the list of user’s purchase(name + price)
Steps
- Keep asking questions until users type q to quit
- Ask user about food names & prices
- Show list & total
Tips
- Use List to store variables
- For loop to calculate total
- while loop for continually asking questions
food_list = []
prices = []
total = 0
while True:
food = input("Enter a food name(q to quit): ")
if(food.lower() == "q"):
break
else:
price = float(input(f"Enter the price of {food}: $"))
food_list.append(food)
prices.append(price)
print("---- Your Cart ----")
for i in food_list:
print(i, end=" ")
for i in prices:
total += i
print()
print(f"Total is {total:.2f}")2D-List⚡
first = ["a", "b", "c"]
second = ["d", "e", "f"]
third = ["g", "h", "i"]
sum = [first, second, third]
print(sum)Index
first = ["a", "b", "c"]
second = ["d", "e", "f"]
third = ["g", "h", "i"]
sum = [first, second, third]
print(sum[2])What about sum[1][2]?
first = ["a", "b", "c"]
second = ["d", "e", "f"]
third = ["g", "h", "i"]
sum = [first, second, third]
print(sum[1][2])Mostly used way
sum = [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]]
print(sum[1][2])Print the 2D-List
sum = [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]]
for i in sum:
print(i)Tuple in List?
sum = [("a", "b", "c"),
("d", "e", "f"),
("g", "h", "i")]
print(sum[1][2])2D-tuple?
sum = (("a", "b", "c"),
("d", "e", "f"),
("g", "h", "i"))
print(sum[1][2])for loop
sum = (("a", "b", "c"),
("d", "e", "f"),
("g", "h", "i"))
for row in sum:
for j in row:
print(j, end=" ")
print()Set in Tuple?
sum = ({"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"})
for row in sum:
for j in row:
print(j, end=" ")
print()Set in List?
sum = [{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"}]
for row in sum:
for j in row:
print(j, end=" ")
print()NumPad⚡
Exercise 04
Be Aware of the for loop, it’s quite different from normal for loops in other languages. I’d been confused at the first time I saw it. 😂
Correct Way 👌
✅✅✅
num_pad = ( (1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#"))
for row in num_pad:
for j in row:
print(j, end=" ")
print()❌❌❌❌❌❌❌❌
num_pad = ( (1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#"))
for i in num_pad:
for j in row:
print(j, end=" ")
print()Let’s sum up 2D-Collections⚡
I’m a bit dizzy now, are you too?
2D list of lists
num_pad = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
["*", 0, "#"]]2D list of tuples
num_pad = [ (1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#")]2D list of sets
num_pad = [ {1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{"*", 0, "#"}]2D tuple of tuples
num_pad = ( (1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#"))2D tuple of lists
num_pad = ( [1, 2, 3],
[4, 5, 6],
[7, 8, 9],
["*", 0, "#"])2D tuple of sets
num_pad = ( {1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{"*", 0, "#"} )2D set of lists (NOT VALID) ❌
num_pad = { [1, 2, 3],
[4, 5, 6],
[7, 8, 9],
["*", 0, "#"]}2D set of tuples
num_pad = { (1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#") }2D sets of sets (NOT VALID) ❌
num_pad = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{"*", 0, "#"} }








