Sitemap
Yen Wang

Yen Wang

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

Python — Basic Review before diving deeper 03

Want to recall the memory of Python easily?

18 min readApr 22, 2023

--

Press enter or click to view image in full size

This is the note taken while I learned Python “again”, hope it helps you too.
There are additional links in the article for you to understand further information.

Quick tip |
Find ⚡for each topic
Find gif🤣 in the end of each topic

☘️Directory

  • Exercise 05 — Quiz Game
  • Dictionary
  • None
  • Truthy / Falsy
  • is V.S. ==
  • Random
  • Range
  • Function
  • Doc Strings
  • *args & **kwargs
  • Exercise 06 -Find the highest even number

❤️Good Resources

Bro code | Python full course

ZeroToMastery | Pyhton

⚡Quiz Game

Exercise 05

questions = (("First Question: Who was the first woman to fly solo across the Atlantic Ocean?",
"Second Question: ",
"Third Question: ",
"Fourth Question: ",
"Fifth Question: "
))

options = ( ("A. ", "B.Amelia Earhart ", "C. ", "D. "),
("A. ", "B. ", "C. ", "D. "),
("A. ", "B. ", "C. ", "D. "),
("A. ", "B. ", "C. ", "D. "),
("A. ", "B. ", "C. ", "D. "))

answers = ("B", "B","A","C","D")
guess_list = []
score = 0
question_num = 0

for question in questions:
print("----------------")
print(question)
for option in options[question_num]:
print(option)

guess = input("Enter (A, B, C, D): ").upper()
guess_list.append(guess)
if guess == answers[question_num]:
score += 1
print("COREECT!")
else:
print("INCORRECT!")
print(f"{answers[question_num]} is the correct answer.")

question_num += 1


print("----------------")
print(" RESULT ")
print("----------------")

print("Answers: ", end="")
for answer in answers:
print(answer, end=" ")
print()

print("Guesses: ", end="")
for guess in guess_list:
print(guess, end=" ")
print()

score = int(score / len(questions) * 100)
print(f"Your Score is {score}.")


Press enter or click to view image in full size
Press enter or click to view image in full size

Bro Code Version


questions = ("How many elements are in the periodic table?: ",
"Which animal lays the largest eggs?: ",
"What is the most abundant gas in Earth's atmosphere?: ",
"How many bones are in the human body?: ",
"Which planet in the solar system is the hottest?: ")

options = (("A. 116", "B. 117", "C. 118", "D. 119"),
("A. Whale", "B. Crocodile", "C. Elephant", "D. Ostrich"),
("A. Nitrogen", "B. Oxygen", "C. Carbon-Dioxide", "D. Hydrogen"),
("A. 206", "B. 207", "C. 208", "D. 209"),
("A. Mercury", "B. Venus", "C. Earth", "D. Mars"))

answers = ("C", "D", "A", "A", "B")
guesses = []
score = 0
question_num = 0

for question in questions:
print("----------------------")
print(question)
for option in options[question_num]:
print(option)

guess = input("Enter (A, B, C, D): ").upper()
guesses.append(guess)
if guess == answers[question_num]:
score += 1
print("CORRECT!")
else:
print("INCORRECT!")
print(f"{answers[question_num]} is the correct answer")
question_num += 1

print("----------------------")
print(" RESULTS ")
print("----------------------")

print("answers: ", end="")
for answer in answers:
print(answer, end=" ")
print()

print("guesses: ", end="")
for guess in guesses:
print(guess, end=" ")
print()

score = int(score / len(questions) * 100)
print(f"Your score is: {score}%")
Yes, right now!

⚡Dictionary

A collection of { key : value } pairs.
Ordered & unchangeable. No Duplicates.
— Bro Code

# Dictionary

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

print(dir(capitals)) # useful methods
print("--------------------")
print(help(capitals)) # more description
Press enter or click to view image in full size
useful methods & more description

🔸Get method

# Dictionary

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

print(capitals.get("Greece")) # Athens

How to check whether it exists or not?

# Dictionary

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

if capitals.get("Iceland"):
print("That capital exists.")
else:
print("The capital doesn't exist.")
Press enter or click to view image in full size

More Methods

# Dictionary = { key : value }

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

capitals.update({"Germany": "Berlin"})
print(f"update - {capitals}")
print()

capitals.pop("Denmark")
print(f"pop - {capitals}")
print()

capitals.popitem()
print(f"popitem - {capitals}")
print()

capitals.clear()
print(f"clear - {capitals}")
print()
Press enter or click to view image in full size

Let’s dive deeper.

dic_a = {
'a': [1,2,3],
'b': 'heyyyyy',
'x': True
}

print(a_list['a'][1]) # 2

What about a list?

a_list = [
{
'a': [1,2,3],
'b': 'heyyyyy',
'x': True
},
{
'a': [4,5,6],
'b': 'heyaaa',
'x': True
},
{
'a': [7,8,9],
'b': 'helllllllllllo',
'x': False
},
]

print(a_list[0]['a'][2]) # 3

🔸Key

❗key should be unique

❌❌❌❌❌
a_list = [
{
'a': [1,2,3],
'a': 'heyyyyy',
'x': True
}
]

print(a_list['a'][1])
NOOOOOOOOOOOOOOOOOO!!!!

🔸Keys

This is the built-in method, don’t be confused with key in dictionary.

# Dictionary

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

keys = capitals.keys()
print(keys)

print("-----------------")

for key in capitals.keys():
print(key)
Press enter or click to view image in full size

Let’s see more dictionay methods.

You can find more here | W3Schools

🔸Get

a_list = {
'a': [1,2,3],
'b': 'heyyyyy',
'x': True
}

print(a_list.get('b')) # heyyyyy

What if the key doesn’t exist yet?

a_list = {
'a': [1,2,3],
'b': 'heyyyyy',
'x': True
}

print(a_list.get('c'))
print(a_list.get('c', 5678))
print(a_list)
Press enter or click to view image in full size
print(a_list.get('c', 5678))

This means, if key c doesn’t exist, create 5678 as a value for it.

So Great!!

Another way to create a new dictionary.

b_list = dict(name = 'Apple')
print(b_list)
Press enter or click to view image in full size

As you may notice, the key is announced directly without single quote.

❌❌❌❌❌
b_list = dict('name' = 'Apple')
print(b_list)
Press enter or click to view image in full size

🔸in

use it like a boolean

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print('heyyy' in user.keys()) # False
user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print('heyyy' in user.values()) # True

🔸Values

# Dictionary

capitals = {"Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi",}

v = capitals.values()
print(v)

print("-----------------")

for v in capitals.values():
print(v)
Press enter or click to view image in full size

🔸items

Simple example,

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print(user.items())
Press enter or click to view image in full size

More complex one,

# Dictionary

capitals = { "Costa Rica": "San Jose",
"Greece": "Athens",
"Iceland": "Reykjavik",
"Denmark": "Copenhagen",
"Vietnam": "Hanoi" }

c = capitals.items()
print(c)

print("-----------------")

for k, v in capitals.items():
print(f"{k} : {v}")
Press enter or click to view image in full size

🔸Clear

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print(user.clear())
print(user)
Press enter or click to view image in full size

You can see which to use depending on what you need from the returned value.

🔸pop()

To use this method, you need give it a parameter(key).

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print(user.pop('age'))
print(user)
Press enter or click to view image in full size

🔸popitem()

  • This method is not random anymore after Python 3.7, it will remove the last key: value pair in the dictionary.
  • It doesn’t need a parameter.

More info can be found here | W3Schools
More comparisons between pop, popitem, clear, del | note.nkmk ⭐⭐⭐

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

print(user.popitem())
print(user)
Press enter or click to view image in full size

🔸Del

Delete certain pair by the parameter given.

user = {
'cart': [1,2,3],
'greet': 'heyyy',
'age': 18
}

del user['age']
print(user)
Press enter or click to view image in full size

⚡None

This article represents good explanation comparing None with Null.

None in Python | realPython
Clear examples help you understand | GeeksforGeeks ⭐⭐⭐

  • None is an object, and a first-class citizen in Python
  • None isn’t equal to zero, none is none.
  • So you can print it.
  • None is returned when the function, object is null, or empty state. (I know it’s a bit confusing…)
print(type(None))
Press enter or click to view image in full size

This is None,

def check_return():
pass
print(check_return()) # None

And this is None too…


# declaring a variable as None
var = None

# checking it's value
if var is None:
print("var has a value of None")
else:
print("var has a value")
Press enter or click to view image in full size

Examples are from GeeksforGeeks, check out for more.

⚡Truthy or Falsy?

StackOverflow | What is Truthy and Falsy? How is it different from True and False?

FreeCodeCamp | Truthy and Falsy Values in Python: A Detailed Introduction⭐⭐⭐⭐⭐

The basic rules are:

  • Values that evaluate to False are considered Falsy.
  • Values that evaluate to True are considered Truthy. — freeCodeCamp
is_gris_greeting = bool('heyyy')
isNum = bool(7)

print(is_greeting) # True
print(isNum) # True

🔸 Truthy Values

According to the Python Documentation:

By default, an object is considered true. — freeCodeCamp

is_greeting = bool('heyyy')
isNum = bool(7)

if is_greeting and isNum:
print("Turthyyyyyy condition")
else:
print("Falsyyyyy")
Press enter or click to view image in full size

But if the variable is equal to zero…

is_greeting = bool('heyyy')
isNum = bool(0)

if is_greeting and isNum:
print("Turthyyyyyy condition")
else:
print("Falsyyyyy")
Press enter or click to view image in full size

There is an advanced way by using built-in function __bool__, we will discuss this in the future.

To make it easy, if the variable is zero or empty(for collections), they are falsy, otherwise, they are truthy.

⚡Ternary Operator

More about it in Python | GeeksforGeeks

Easiest way to understand the concept…

isAllowed = False

yes = "Yeeeeesssss" if isAllowed else "NOOOOOOOOOOOOOOOO"

print(yes)
isAllowed = True

yes = "Yeeeeesssss" if isAllowed else "NOOOOOOOOOOOOOOOO"

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

A super neat sentence while coding.

If you ever had experience with javascript, it looks like this in JS.
More about JS-ternary operator | MDN

/* Javascript */
function getFee(isMember) {
return (isMember ? '$2.00' : '$10.00');
}

It’s such fun to recognize similarities or differences within different languages.

⚡Short Circuit

More in Python Doc
Good examples in | GeeksforGeeks

To shorten the description, When the Python interpreter scans or expression, the first statement will be checked to see if it’s true, but the second one might be ignored depending on the situation.

However, in and expression, both statements will be checked.

An expression containing and or stops execution when the truth value of expression has been achieved. Evaluation takes place from left to right. — GeeksfroGeeks

isAllowed = False
isUser = False

if isAllowed and isUser:
print('Yeeeeeeeeeaaaaaa!')
else:
print('Nooooooooooooooo!!!')
Press enter or click to view image in full size
isAllowed = True
isUser = False

if isAllowed or isUser:
print('Yeeeeeeeeeaaaaaa!')
else:
print('Nooooooooooooooo!!!')
Press enter or click to view image in full size
isAllowed = True
isUser = False

if isAllowed and isUser:
print('Yeeeeeeeeeaaaaaa!')
else:
print('Nooooooooooooooo!!!')
Press enter or click to view image in full size
isAllowed = False
isUser = True

if isAllowed and isUser:
print('Yeeeeeeeeeaaaaaa!')
else:
print('Nooooooooooooooo!!!')
Press enter or click to view image in full size
My brain has a short circuit.

⚡Logical Operator

  • <
  • >
  • ==
  • ≥
  • ≤
  • !=
  • and
  • or
  • not
print(4 == 5) # False
print(1 < 2 > 3 > 4) # False
print(1 >= 0) # True
print(0 != 0) # False
print(0 != 1) # True
# Both are allowed
print(not True) # False
print(not(True)) # False

A Tricky Quesiton

print('a' > 'A') # True

Answer in StackOverflow

The char will be converted into an integer according to ASCII table.

So print('a' > 'A') is true because print(97 > 65).

⚡is V.S. ==

print(True == 1)
print('1'== 1)
print('' == 1)
print([] == 1)
print(10 == 10.0)
print([] == [])
Press enter or click to view image in full size
print(bool(1)) # Trues 

is

Doc in W3Sc

The is keyword is used to test if two variables refer to the same object.
— W3Schools

print(True is 1)
print('1' is 1)
print('' is 1)
print([] is 1)
print(10 is 10.0)
print([] is [])
Press enter or click to view image in full size
print(True is True) # True
print('1' is '1')# True
print('' is '')# True
print([] is []) # False ❌
print(10 is 10)# True
print([1, 2, 3] is [1, 2, 3]) # False ❌

Same object or not?

x = ['H', 'E', 'Y']
y = x

print(x is y) # True
x = ['H', 'E', 'Y']
y = ['H', 'E', 'Y']

print(x is y) # False

⚡Random

What do you get this time?

import random

print(random.randint(5, 20))

🔸Useful Methods

More methods in W3Schools

🔹randint() — Return a number between x and y

Get Yen Wang’s stories in your inbox

🔹random() — Return random number between 0.0 and 1.0

🔹choice() — Return a random element from a list:

🔹shuffle()

You can ask help too.

import random

print(help(random))

randint()

import random

print(random.randint(5, 20)) # e.g. 16

random()

import random

print(random.random()) # 0.31545485554509703

Choice

import random

mylist = ["A", "B", "C", "D", "X", "E"]

print(random.choice(mylist)) # random one

Shuffle()

import random

mylist = ["A", "B", "C", "D", "X", "E"]

random.shuffle(mylist)

print(mylist)
Press enter or click to view image in full size
What do you get this time?

⚡Range

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. — W3Schools

🔸Syntax — range(start, stop, step)

x = range(3, 6)
for n in x:
print(n)

Increment 3 each time, from 5 to 20.

x = range(5, 20, 3)
for n in x:
print(n)
Tell me everything from start to the end 😼

Enumerate

The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object.

The enumerate() function adds a counter as the key of the enumerate object. — W3Schools

🔸Syntax — enumerate(iterable, start=0)


a = ["A", "B", "C"]

for i in enumerate(a):
print (i)

print("--------------")

for k, v in enumerate(a, 100):
print (k, v)

print("--------------")

for k, v in enumerate(a):
print(k, v)

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

It works in a string as well.

for i, char in enumerate('Heyyyyyyyyyyyyaaa!!'):
print(i, char)
Press enter or click to view image in full size

Range in list

for i, char in enumerate(list(range(30))):
if char == 15:
print(f"index of {char} is: {i}")

If you want to see all.

for i, char in enumerate(list(range(30))):
print(i, char)
if char == 15:
print(f"index of {char} is: {i}")
Where is the start of the line?

⚡While Loop

With the while loop we can execute a set of statements as long as a condition is true. — W3Schools

🔹Use break statement when you decide to stop the iteration

🔹Use continue to stop the current iteration and move forward to next one

🔹Use pass to do nothing 😂essentially it passes to the next line like a placeholder

while True:
a = input("Say somehting(q to quit): ")
if a == 'q':
break

🔸While loop or for loop?

🔹While loop

  • More flexible.
  • Use it when you are not sure how many iterations it may take

🔹For loop

  • Simpler to use
a = [1, 2, 3, 4, 5]

for i in a:
print(i)

c = 0
while c < len(a):
print(a[c])
c += 1

break

a = [1, 2, 3, 4, 5]

for i in a:
print(i)
break

c = 0
while c < len(a):
print(a[c])
c += 1
break

continue

a = [1, 2, 3]

for i in a:
print(i)
continue

c = 0
while c < len(a):
print(a[c])
c += 1
continue

To make it clearer, continue will go back to the new iteration.

a = [1, 2, 3]
b = [4, 5, 6]

for i in a:
continue
print(i)

c = 0
while c < len(b):
print(b[c])
c += 1
continue
Press enter or click to view image in full size

Let’s look it clearer.

a = [1, 2, 3]
b = [4, 5, 6]

for i in a:
continue
print(i)

c = 0
while c < len(b):
c += 1
continue
print(b[c])

Nothing is gonna happen.

The 6th & 12th line will never be executed cause continue statements keep going back the loops themselves.

Press enter or click to view image in full size

pass

a = [1, 2, 3]
b = [4, 5, 6]

for i in a:
print(i)
pass

c = 0
while c < len(b):
print(b[c])
c += 1
pass

It just skips to the next line 😂

Pass statement

is rare to be seen in production, but it’s used as placeholder.

E.g. when you still can’t figure out the content for loops or functions, put pass statement there because it’s not allowed to be null in loops or functions in Python.

❌❌❌❌❌
This is not gonna work.

a = [1, 2, 3]
b = [4, 5, 6]

for i in a:
# nothing here ❌

c = 0
while c < len(b):
print(b[c])
c += 1
pass
Press enter or click to view image in full size

This works!

a = [1, 2, 3]
b = [4, 5, 6]

for i in a:
pass

c = 0
while c < len(b):
print(b[c])
c += 1
pass
Hooray!

⚡Find the Duplicates

Exercise 07

a = [1, 2, 3, 3, 8, 9, 9, 6, 7, 5, 11, 12, 18, 55]

duplicates = []
for i in a:
if a.count(i) > 1:
if i not in duplicates:
duplicates.append(i)

print(duplicates)

⚡Function

Think about D.R.Y = Don’t Repeat Yourself Rule.

Function can reduce the lines for you from repeating the same codes.

More examples in | freeCodeCamp

def show_me():
print("Heyyyyyyyyyyyyyyea")


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

🔸Parameters & Arguments

🔹parameter is used to define a function

🔹argument is used to call/invoke a function

def show_me(name, place):
print(f"Heyyea {name}! Are you from from {place}?")


show_me('A', 'B')
show_me('C','D')
show_me('E','F')
Press enter or click to view image in full size
Press enter or click to view image in full size

🔸Invoke / Call

We “invoke” or “call” a function.

🔸 Keyword Arguments

V.S. positional arguments.

Keyword Arguments is a bad way to use because it makes the codes more complicated.🤨

def show_me(name, emoji):
print(f"Hello {name}! How are you {emoji}?")

# positional arguments
show_me('Alice', '😁')
show_me('Cindy', '😎')
show_me('Elle', '😮')

# keyword arguments
show_me(name='Bob', emoji='😅')
Press enter or click to view image in full size

Let’s see another example.

def hello(greeting, title, first, last):
print(f"{greeting} {title} {first} {last}")

hello("HEY", "Miss.", "Apple", "Juice")

The power of keyword argument is, even I shuffle the arguments while invoking the function, if the keyword is correct, the result returns right one.

def hello(greeting, title, first, last):
print(f"{greeting} {title} {first} {last}")

hello(title="Miss.", greeting="HEY", last="Juice", first="Apple")

🔸Default Parameters

Set the default parameter for the function.

# Default Parameters
def show_me(name='ZeroMan', emoji='🥰'):
print(f"Hello {name}! How are you {emoji}?")

# positional arguments
show_me('Alice', '😁')
show_me('Cindy', '😎')
show_me('Elle', '😮')
# keyword arguments
show_me('Molly')
show_me()
Press enter or click to view image in full size

🔸Return

If you didn’t add return, the function will return None.

def sum(a, b):
a + b


print(sum(2, 3))
😮
def sum(a, b):
return a + b


print(sum(2, 3))
🤗

Let’s have some fun!

def sum(a, b):
return a + b


total = sum(4, 5)
print(sum(total, sum(2, 3))) # 14

🔸Nested Function

def sum(a, b):
def ano_sum(a, b):
return a, b


total = sum(4, 5)
print(total)
😮

Most of time, we need to return something.

def sum(a, b):

def ano_sum(a1, b1):
return a1 + b1

return ano_sum(a, b)


total = sum(4, 5)
print(total) # 9

Notice that, each function had better use different parameters or they may cause confusion.

How fun!

Doc strings

It helps other developer understand your codes.

def test(a):
'''
Info : This is a test function and printing param a.
'''
print(a)


test('Yea')
Press enter or click to view image in full size

You can print out the doc strings directly too.

def test(a):
'''
Info : This is a test function and printing param a.
'''
print(a)


print(test.__doc__)
Press enter or click to view image in full size
Press enter or click to view image in full size
Yea…. Doc… Cool.

⚡args & kwargs

More in GeeksforGeeks | *args and **kwargs in Python

These are two special symbols.

🔹args — non keyword arguments

🔹kwargs — keyword arguments

🔹* — unpacking operator

🔸*args


def myFun(*argv):
for arg in argv:
print(arg)


myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Press enter or click to view image in full size
Example from GeeksfroGeeks

It only receives 1, but I give it 5.

def myFun(args):
print(args)


myFun(1, 2, 3, 4, 5)
Press enter or click to view image in full size
😮

How about print out *args?

def myFun(*args):
print(*args)


myFun(1, 2, 3, 4, 5)
We have all the arguments/parameters printed.

How about print out args without * ?

def myFun(*args):
print(args)


myFun(1, 2, 3, 4, 5)
Press enter or click to view image in full size
Then we have a tuple.

If we sum them, we have the correct answer wanted.

BTW. I use built-in function sum here. — W3Schools

def myFun(*args):
print(args)
return sum(args)


print(myFun(1, 2, 3, 4, 5))
Press enter or click to view image in full size

🔸**kwargs

def myFun(*args, **kwargs):
print(kwargs)
total = 0
for i in kwargs.values():
total += i
return sum(args) + total


print(myFun(1, 2, 3, 4, 5, num1=5, num2=10))
Press enter or click to view image in full size

How to pass parameters legally?

🔹Rule:

params, *args, default, parameters, **kwargs

def myFun(name, *args, a='hi', **kwargs):
print(kwargs)
total = 0
for i in kwargs.values():
total += i
return sum(args) + total


print(myFun('Alice', 1, 2, 3, 4, 5, num1=5, num2=10))
Press enter or click to view image in full size
🤯

🔹Change the name of parameters

args -> arv

kwargs -> kwv

def myFun(name, *arv, a='hi', **kwv):
print(kwv)
total = 0
for i in kwv.values():
total += i
return sum(arv) + total


print(myFun('Alice', 1, 2, 3, 4, 5, num1=5, num2=10))

It works!

Press enter or click to view image in full size
A milestone! Guys!!

⚡Find the Highest Even Number

Exercise 06

I use built-in function — max here.

def highest_even(n):
evens = []
for i in a:
if i % 2 == 0:
evens.append(i)
return max(evens)


a = [12, 15, 9, 8, 5, 3, 2, 21, 6]
print(highest_even(a)) # 12

If you would like to, Do share your solution 😊

Now we finish another exercise!

⚡Walrus Operator :=

🔹One of the latest features in Python 3.8 is the Walrus Operator.

🔹 another name for assignment expressions.

— GeeksforGeeks

🔹assign values to variables as part of a larger expression

— from Python Doc

Normal Code

a = 'Heyyyyyyyyyyyyyyyyyyyyyyyea'

if (len(a) > 10):
print(f"Too long! {len(a)} elements.")

It breaks D.R.Y.

a = 'Heyyyyyyyyyyyyyyyyyyyyyyyea'

if (n := len(a) > 10):
print(f"Too long! {n} elements.")

And the returned value is Boolean — True. 🤯

Press enter or click to view image in full size

Another example.

a = 'Heyyyyyyyyyyyyyyyyyyyyyyyea'

if (n := len(a) > 10):
print(f"Too long! {n} elements.")

while ((n := len(a)) > 1):
print(n)
a = a[:-1]
Press enter or click to view image in full size

❗Be aware

If you didn’t put parentheses correctly, it will give you…

Press enter or click to view image in full size
a = 'Heyyyyyyyyyyyyyyyyyyyyyyyea'

if (n := len(a) > 10):
print(f"Too long! {n} elements.")

while (n := len(a) > 1):
print(n)
a = a[:-1]

Infinite True 🤣

--

--

Yen Wang
Yen Wang

Written by Yen Wang

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