BooleanTrue/false
Integerself explanatoryint
Stringwordsstr
Floatall numbers (including decimals)float

\b backspace

\n newline

\t horizontal tab

// quotient

% remainder or modulus

** exponention

  • / (Division): This operator performs standard division and always returns a floating-point number.
  • // (Quotient): This operator performs integer division, which returns only the whole number (the quotient) and discards any remainder
  • 3/2 yields 1.5 while 3//2 yields 1
print(f'{qty} {item} cost ${price}')

Without f-string Formatting

There are two common ways to format output without f-strings: using commas to separate items or using the concatenation operator (**+**).

  • Using Commas: This method automatically inserts a space between the items.
    • Example: print("The area is", area, "square units")
    • Example: print("Your name is", name)
  • Using Concatenation (**+**): This method joins strings together. However, you must manually convert non-string data types (like integers or floats) into strings using the **str()** function, or Python will raise a **TypeError**.
    • Example: print('$' + str(profit))

With f-string Formatting

F-strings allow you to embed variables directly into a string by placing an **f** before the opening quotation mark and enclosing variables in **curly braces ****{}**.

  • Basic Variable Embedding:
    • Example: print(f'Hi, {name}.')
    • Example: print(f'{qty} {item} cost ${price}')
  • Advanced Formatting (Precision and Alignment): F-strings also allow you to format the data, such as rounding decimals or aligning text, by adding a colon (:) inside the braces.
    • Example (Rounding to 2 decimal places): print(f"Wage of employee {employee_id} is ${wage:.2f}")
    • Example (Right-aligning in a width of 8): print(f"{i:>8}")
    • output will look like (8 spacing then i)

Comparison Table

FeatureWithout f-string (Concatenation)With f-string
Syntaxprint("Value: " + str(val))print(f"Value: {val}")
Type ConversionManual (must use str())Automatic
ReadabilityCan be “messy” with many itemsCleaner and easier to read
FormattingDifficult to align or roundEasy via format specifications

Formatting

  • If the variable **i** is the number **123**, the command **f"{i:>8}"** will reserve 8 spaces and place “123” at the very end, like this: ** 123** (with 5 leading spaces).
  • You can control decimal places by using a dot followed by the number of places and the letter **f** (e.g., **:.2f** for two decimal places)