Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Introductory

if Statement

age = int(input("Please enter you age: "))
# `if ... elif ... elif ... else` sequence:
if age < 0:
    age = 0
    print("Entered age is negative! You cannot be aged negatively, we changed it to zero")
elif age == 0:
    print("Entered age is zero! Are you sure?")
elif age > 0 and age < 30:
    print("You have not entered your middle age era.")
else:
    print("Get ready, you're now 30 or over 30.")

[!TIP]

Truth Table:

  • T stands for “true”.
  • F stands for “false”.
  • && equivalent in Python is and.
  • || equivalent in Python is or.

Truth table

Literals VS Singletons

is None VS == None

p = [1]
q = [1]
print(p is q)  # False because they are not the same actual object
print(p == q)  # True because they are equivalent

Learn more.

Dictionary in Python

for Statement

[!NOTE]

These user.copy().../scores.items() are the built-in libraries and modules that we mentioned here.

range Function

Infographic of range function

[!NOTE]

  • It doesn’t really make the list, thus saving space (print(range(10))).
  • Its return type is an iterable object.

    • Some functions/constructs expect something, from which they can obtain successive items until the supply is exhausted.
    • E.g. for statement, or sum function

      Iterables

break & continue Statements

ads = [
  { 'title': "CodeRabbit", 'category': 'ai' },
  { 'title': 'Netflix', 'category': 'entertainment' },
  { 'title': 'Audible', 'category': 'audio-book' },
]
for ad in ads:
    if ad['category'] == 'entertainment':
        continue
    print("Personalized ad: ", ad['title'])
for week in range(52):
    print('Week #' + str(week + 1))
    for work_day in range(7):
        if work_day > 4:
            print("Hooray, its weekend!")
            break
        print('Day #' + str(work_day + 1))

[!TIP]

When to use break/continue: Stackoverflow Q&A.

else Clause in a for/while Loop

For else statement to find prime numbers

pass Statement

class Polygon:
    pass # A polygon class with xyz helper func
def initlog(*args):
    pass # Remember to implement this!

Tuple

single_tuple = ('Google',) # Note that the trailing comma is necessary
coordinates = (34.66688492670634, 133.9371036903121)
print('Latitude: ', coordinates[0])
print('Longitude: ', coordinates[1])

[!TIP]

We can pack and unpack lists and tuples in Python:

Packing & unpacking tuples

match Statement

# LLM stands for Large Language Model
llm = input("Please enter your LLM: ")
match llm:
    case "claude":
        print("Claude is a family of large language models developed by Anthropic.")
    case "gpt4":
        print("Generative Pre-trained Transformer 4 is a multimodal large language model created by OpenAI")
    case "gp3":
        print("Generative Pre-trained Transformer 3 is a large language model released by OpenAI in 2020.")
    case "gemini":
        print("Gemini, formerly known as Bard, is a generative artificial intelligence chatbot developed by Google.")

Or it can be a bit more sophisticated:

A helper function to translate http error codes

We can use tuples in a match statement too, here you can see how we:

point = (1, 3)
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y): # Similar to unpacking assignment: (x, y) = point
        print(f"X={x}, Y={y}")
    case _:
        raise ValueError("Not a point")

Or you can opt for matching against lists:

https://github.com/kasir-barati/python/blob/80b305428801a3517eec3e038987e1ed065cd742/02-getting-started/assets/match-a-list-of-points.py#L1-L27

[!TIP]

# Unpacking a dict/list/tuple:

  • Unpacking a list in a match statement.

    • We use the same syntax to unpack tuples that we use to unpack a list.
    value = [1, 2, 4]
    match value:
        # Matches a list with at least 2 elements
        case [a, b, *rest]:
            print(f"First two: {a}, {b}, rest: {rest}")
    
  • Unpacking a dictionary in a match statement:

    user = {
      "name": "Mohammad Jawad san",
      "age": "30",
      "hobby": "Programming",
      "job": "Solving tough problems through computer science"
    }
    match user:
        case {"job": job, "age": age, **rest}:
            print(job, age)
            print(rest)
    

Guard in match Statement

event = input("Is today a holiday or a workday? ")
is_seek = True
match event:
    case "holiday" if is_seek == True:
        print("You've got the entire holiday to rest. Get well soon :)")
    case "holiday":
        print("Let's go out and have fun :)")
    case "workday":
        print("let's go to work :)")
    case _:
        print('It is neither "holiday" nor "workday"')

Access Unpacked Subsequence

coordinates = [
    [53.0793, 8.8017],
    [35.6762, 139.6503]
]
match coordinates:
    # No difference with:
    #   case [bremen, tokyo]:
    #   case [(_, _) as bremen, (_, _) as tokyo]:
    #   case [[x1, y1] as bremen, [x2, y2] as tokyo]:
    case [(_, _), (x2, y2) as tokyo]:
        print(f"Tokyo's latitude and longitude are {tokyo} respectively")

[!TIP]

To learn more read PEP 636 which is interestingly written in tutorial format.

Extra Resources

YouTube/Aparat

Ref