| Boolean | True/false | |
|---|---|---|
| Integer | self explanatory | int |
| String | words | str |
| Float | all 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)
- Example:
- 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))
- Example:
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}')
- Example:
- 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)
- Example (Rounding to 2 decimal places):
Comparison Table
| Feature | Without f-string (Concatenation) | With f-string |
|---|---|---|
| Syntax | print("Value: " + str(val)) | print(f"Value: {val}") |
| Type Conversion | Manual (must use str()) | Automatic |
| Readability | Can be “messy” with many items | Cleaner and easier to read |
| Formatting | Difficult to align or round | Easy 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)