Sitemap
FAUN.dev() 🐾

We help developers learn and grow by keeping them up with what matters. 👉 www.faun.dev

Python — Basic Review before diving deeper 02

Want to recall the memory of Python easily?

16 min readApr 19, 2023

--

Press enter or click to view image in full size

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

Bro code | Python full course

ZeroToMastery | Pyhton

Reminder

Indentation is important in python, be aware it.
more info can be seen | here

Indexing⚡

Can be used in string, list, etc.

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])
Press enter or click to view image in full size

You can try reversal in this way.

credit_number = "1234-5678-9ABC-DEFG"

print(credit_number[-4:]) #DEFG

Format 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}")
Press enter or click to view image in full size

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}")
Press enter or click to view image in full size
10 spaces & additional 0 behind the number

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}")
Press enter or click to view image in full size

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}")
Press enter or click to view image in full size

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:,}")
Press enter or click to view image in full size

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}")

Press enter or click to view image in full size

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!")
Press enter or click to view image in full size

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!")
Press enter or click to view image in full size

Easy Credit Card Validator

exercise 02

Rules

  1. It must contain exactly 16 digits.
  2. It should only contain 0–9 digits.
  3. It must start with either 9 or 7 or 3.
  4. It may have digits in a group of 4 with a separator (-).
  5. It must not contain any other symbols such as _ or space(‘ ‘).

References | Codespeedy

Steps

  1. Remove ‘-’ or ‘ ‘(blank space)
  2. from right to left, add every odd digits
  3. from right to left, double every even digits (add the two-digit number together to get the single number)
  4. sum step 2 & step 3
  5. If the sum can be devided by 10, the credit card number is valid.

Test credit card numbers

More can be seen Here | wtools.io

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 4012888888881881

Step 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)
Press enter or click to view image in full size

Step 2

Let’s test the for loop.

for i in card_num[::1]:
print(i)
Press enter or click to view image in full size

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

Press enter or click to view image in full size
# 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

# step 4
total = sum_odd + sum_even

Step 5

# step 5
if total % 10 == 0:
print("The credit card number is valid.")
else:
print("The credit card number is invalid.")
Press enter or click to view image in full size
Press enter or click to view image in full size

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 collections module provides a rich set of specialized container data types — realPython
  • They are called as Data Sturcture as well. 🔥🔥🔥

More about built-in functions | Python Doc

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)
Press enter or click to view image in full size

dir

Some attibutes and methods we will discuss in the future

# List

fruits = ["apple", "banana", "lemon", "peach"]
print(dir(fruits))
Press enter or click to view image in full size

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))
Press enter or click to view image in full size
Type Enter to see More

Length & Boolean

# List

fruits = ["apple", "banana", "lemon", "peach"]

print(len(fruits))
print("banana" in fruits)
print("coconut" in fruits)
Press enter or click to view image in full size

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}")
Press enter or click to view image in full size

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)
Press enter or click to view image in full size

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)
Press enter or click to view image in full size
l = [1, 2, 3]
l.extend([4, 5, 6])

popped = l.pop()
print(popped) # 6

clear

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)
Press enter or click to view image in full size

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)) # 3
l = ['A', 'B', 'C', 'D', 'E']

print(l.index('D')) # 3

We can set the index for searching the element .

l = ['A', 'B', 'C', 'D', 'E']

print(l.index('D', 2, 4)) # 3
l = ['A', 'B', 'C', 'D', 'E']

print(l.index('B', 2, 4)) # Error

Count

l = ['A', 'B', 'C', 'D', 'E', 'D']

print(l.count('D')) # 2

Sort

l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']

print(l.sort())
print(l)
Press enter or click to view image in full size

sorted

l = ['X', 'B', 'C', 'G', 'E', 'D', 'A', 'D']

print(sorted(l))
Press enter or click to view image in full size

sort & sorted ?

Check out here | freeCodeCamp

The main difference between sort() and sorted() is that the sorted() 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))
Press enter or click to view image in full size

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)
Press enter or click to view image in full size

This works too.

l = ['a', 'b', 'c', 'd', 'e']

print(l[::-1])
Press enter or click to view image in full size

List range

print(list(range(1,100)))
Press enter or click to view image in full size

Join

Common pattern is like this

✅✅✅
s = ''.join(['Heyyyyy ', 'How ', 'Are ', 'UUUUUUUUU ','?????'])
print(s)
Press enter or click to view image in full size

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)
I just can’t help.

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))
Press enter or click to view image in full size

Length & Boolean

# Set

fruits = {"apple", "banana", "lemon", "peach"}

print(len(fruits)) # 4
print("coconut" in fruits) # False

Notice that there is no each usage in set.

Because set is unordered, so there is no index as well.

# Set 

fruits = {"apple", "banana", "lemon", "peach"}
print(fruits[0])
Press enter or click to view image in full size
# Set

fruits = {"apple", "banana", "lemon", "peach"}

print(fruits.index("banana"))
Press enter or click to view image in full size

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}")
Press enter or click to view image in full size

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))
Press enter or click to view image in full size

Covert it to list??

a = {1,2,3,4,5,6}

print(list(a))
Press enter or click to view image in full size

in

Use it to return a boolean value.

a = {1,2,3,4,5,6}

print(3 in a) # True

copy & clear

a = {1,2,3,4,5,6}

b = a.copy()
a.clear()

print(a)
print(b)
Press enter or click to view image in full size
We are almost there!

There are more methods, but the rest is quite similar with the ones above.

See more in | W3Schools

Press enter or click to view image in full size
Don’t memorize, try it instead.

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("------------------")
Press enter or click to view image in full size

🔸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("------------------")
Press enter or click to view image in full size

🔸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("------------------")
Press enter or click to view image in full size

🔸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("------------------")
Press enter or click to view image in full size

🔸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)
Press enter or click to view image in full size

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)
Press enter or click to view image in full size

Tuple⚡

Tuple = ( ) ordered & unchangeable. Duplicates OK.

FASTER than List.

— Bro Code

🔸Dir

# Tuple

fruits = ("apple", "banana", "lemon", "peach")

print(dir(fruits))
Press enter or click to view image in full size

🔸Help

# Tuple

fruits = ("apple", "banana", "lemon", "peach")

print(help(fruits))
Press enter or click to view image in full size

🔸Length & Boolean

# Tuple

fruits = ("apple", "banana", "lemon", "peach")

print(f"Length is {len(fruits)}")
print("coconut" in fruits)
print("apple" in fruits)
Press enter or click to view image in full size

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"))
Press enter or click to view image in full size

🔸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)
Press enter or click to view image in full size

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)])
Press enter or click to view image in full size

Integer is not iterable.

for i in 50:
print(i)

But you can do this instead.

for i in range(50):
print(i, end=" ")
Press enter or click to view image in full size

Underscore

in for loop

More in GeeksforGeeks | Underscore (_) in Python

# Ignore a value of specific location/index
for _ in range(10):
print ("Test")
Example from GeeksforGeeks

Indexing

user = (1,2,3,4,5,6)

x = user[2]
print(x) # 3

You can assign the range as well.

user = (1,2,3,4,5,6)
x = user[1:4]
print(x)
Press enter or click to view image in full size

Unpacking in tuples!?

a,b,c, *sth = (1,2,3,4,5,6)
print(a)
print(b)
print(c)
print(sth)
Press enter or click to view image in full size

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}")
Press enter or click to view image in full size
Yes, Yes, YAAAAAAAAAAAAAAAS!

2D-List⚡

first =  ["a", "b", "c"]
second = ["d", "e", "f"]
third = ["g", "h", "i"]

sum = [first, second, third]

print(sum)
Press enter or click to view image in full size

Index

first =  ["a", "b", "c"]
second = ["d", "e", "f"]
third = ["g", "h", "i"]

sum = [first, second, third]

print(sum[2])
Press enter or click to view image in full size

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])
Press enter or click to view image in full size

Mostly used way

sum = [["a", "b", "c"], 
["d", "e", "f"],
["g", "h", "i"]]

print(sum[1][2])
Press enter or click to view image in full size

Print the 2D-List

sum = [["a", "b", "c"], 
["d", "e", "f"],
["g", "h", "i"]]

for i in sum:
print(i)
Press enter or click to view image in full size

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()
Press enter or click to view image in full size

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()
Press enter or click to view image in full size
❌❌❌❌❌❌❌❌
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()
Press enter or click to view image in full size
Of course 🤣

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, "#"} }

👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇

🚀Join FAUN Developer Community & Get Similar Stories in your Inbox Each Week

--

--

Yen Wang
Yen Wang

Written by Yen Wang

Curious mind. Interested in both creative and exploitative sides. More about me | https://www.yenwang.dev/

FAUN.dev() 🐾
FAUN.dev() 🐾

Published in FAUN.dev() 🐾

We help developers learn and grow by keeping them up with what matters. 👉 www.faun.dev