Skip to main content

python basics: effective python ref

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

for i, (item, count) in enumerate(pantry):
print('#%d: %-10s = %.2f' % (i, item, count))

What It Prints (Correctly)

#0: avocados = 1.25
#1: bananas = 2.50
#2: cherries = 15.00

#%d → prints the index number (0, 1, 2).
%-10s → left-aligns the string (item name) in a field 10 characters wide.
Example: "bananas " (adds spaces to align neatly).

%.2f → prints the number with 2 decimal places.

So the = sign belongs in the format string itself:

'%-10s = %.2f'


✅ If you run the exact code above, you will not see separate lines with just the numbers.
Instead, you’ll see neatly aligned item + count pairs.

👉 Do you want me to also show you the f-string version (more modern & cleaner than % formatting)?

yes



Perfect 👍 f-strings make this much cleaner and easier to read.

Here’s your same example rewritten with f-strings:

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

for i, (item, count) in enumerate(pantry):
print(f"#{i}: {item:<10} = {count:.2f}")

Output

#0: avocados = 1.25
#1: bananas = 2.50
#2: cherries = 15.00

Explanation

{item:<10} → left-aligns the string in a field 10 characters wide.

{count:.2f} → formats the number with 2 decimal places.

f"..." → directly embeds variables into the string (no % or .format() needed).



>>> pantry = [
... ('avocados', 1.25),
... ('bananas', 2.5),
... ('cherries', 15),
... ]
...
... for i, (item, count) in enumerate(pantry):
... print(f"{i} {item} = {count}")
...
0 avocados = 1.25
1 bananas = 2.5
2 cherries = 15



Great! Let’s align the numbers in a column so that the decimal points line up neatly.

We can give the number a fixed width in addition to 2 decimal places.
Example

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

for i, (item, count) in enumerate(pantry):
print(f"#{i}: {item:<10} = {count:6.2f}")

Output

#0: avocados = 1.25
#1: bananas = 2.50
#2: cherries = 15.00

Explanation

{count:6.2f}

6 → total width (including digits, decimal point, and spaces).

.2f → 2 decimal places.

So shorter numbers get padded with spaces on the left, making the column line up.


👉 If you want even bigger alignment (for larger prices like 1234.56), you can increase the width, e.g. {count:8.2f}.

Would you like me to also show how to make this into a pretty table style (like a shopping list)?

yes


Perfect 👍 Let’s make your pantry print like a neat shopping list table.

We’ll use f-strings with alignment for each column.
Example: Pretty Table

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

# Print header
print(f"{'Index':<5} {'Item':<12} {'Price':>8}")
print("-" * 30)

# Print rows
for i, (item, count) in enumerate(pantry):
print(f"{i:<5} {item:<12} {count:>8.2f}")

Output

Index Item Price
------------------------------
0 avocados 1.25
1 bananas 2.50
2 cherries 15.00

Explanation

{'Index':<5} → left-align “Index” in 5 spaces.

{'Item':<12} → left-align item names in 12 spaces.

{'Price':>8} → right-align prices in 8 spaces (so decimals line up).

"—" * 30 → prints a line separator.


👉 Would you like me to also show you how to do this using the tabulate library (gives a professional table format

yes


Awesome 🚀 The tabulate library makes this super easy and looks very professional.

First, you’ll need to install it (only once):

pip install tabulate

Example with tabulate

from tabulate import tabulate

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

# Prepare table data with headers
table = [(i, item, count) for i, (item, count) in enumerate(pantry)]

print(tabulate(table, headers=["Index", "Item", "Price"], floatfmt=".2f"))

Output (default style)

Index Item Price
------- ---------- ------
0 avocados 1.25
1 bananas 2.50
2 cherries 15.00

You can also change table styles:

print(tabulate(table, headers=["Index", "Item", "Price"], tablefmt="grid", floatfmt=".2f"))

Output:

+---------+-----------+--------+
| Index | Item | Price |
+---------+-----------+--------+
| 0 | avocados | 1.25 |
| 1 | bananas | 2.50 |
| 2 | cherries | 15.00 |
+---------+-----------+--------+

Other table options: "plain", "fancy_grid", "github", "pipe", "html", etc.

👉 Do you want me to show you how to export this table directly to Excel/CSV/Markdown after formatting?

yes


Perfect ✅ Let’s extend this so you can export your pantry table into common formats like Excel, CSV, or Markdown.
1. Export to CSV

import csv

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

with open("pantry.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Index", "Item", "Price"])
for i, (item, count) in enumerate(pantry):
writer.writerow([i, item, f"{count:.2f}"])

👉 Creates a pantry.csv file that opens in Excel or any text editor.
2. Export to Excel (.xlsx)

from openpyxl import Workbook

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

wb = Workbook()
ws = wb.active
ws.append(["Index", "Item", "Price"])

for i, (item, count) in enumerate(pantry):
ws.append([i, item, round(count, 2)])

wb.save("pantry.xlsx")

👉 Creates a nice Excel sheet with rows and columns.
3. Export to Markdown Table

from tabulate import tabulate

pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

table = [(i, item, count) for i, (item, count) in enumerate(pantry)]

markdown = tabulate(table, headers=["Index", "Item", "Price"], tablefmt="github", floatfmt=".2f")

with open("pantry.md", "w") as f:
f.write(markdown)

print(markdown)

Output inside pantry.md:

| Index | Item | Price |
|---------|-----------|---------|
| 0 | avocados | 1.25 |
| 1 | bananas | 2.50 |
| 2 | cherries | 15.00 |

✨ Now you can choose:

CSV → easy for data exchange.

Excel → best for office use.

Markdown → perfect for docs or GitHub.

👉 how to export as a nicely formatted PDF report (with table borders)?
Install once

pip install reportlab



program


from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib import colors

# Pantry data
pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]

# Create PDF
pdf_file = "pantry.pdf"
doc = SimpleDocTemplate(pdf_file, pagesize=letter)

# Prepare table data (with header row)
data = [["Index", "Item", "Price"]]
for i, (item, count) in enumerate(pantry):
data.append([i, item, f"{count:.2f}"])

# Create table
table = Table(data)

# Style the table
style = TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.lightblue), # header background
("TEXTCOLOR", (0, 0), (-1, 0), colors.white), # header text color
("ALIGN", (0, 0), (-1, -1), "CENTER"), # center text
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), # bold header
("BOTTOMPADDING", (0, 0), (-1, 0), 10),
("BACKGROUND", (0, 1), (-1, -1), colors.whitesmoke),# rows background
("GRID", (0, 0), (-1, -1), 1, colors.black), # border grid
])

table.setStyle(style)

# Build PDF
doc.build([table])

print(f"✅ PDF saved as {pdf_file}")


✅ PDF saved as pantry.pdf
>>>
bala@BALAs-MacBook-Pro ~ % open pantry.pdf
bala@BALAs-MacBook-Pro ~ %


menu = {
'soup': 'lentil',
'oyster': 'kumamoto',
'special': 'schnitzel',
}
template = ('Today\'s soup is %(soup)s, '
'buy one get two %(oyster)s oysters, '
'and our special entrée is %(special)s.') formatted = template % menu
print(formatted)

We ’re using the old-style dictionary string formatting in Python.

Your code just needs a tiny correction (you’re missing a newline / semicolon between the template and formatted).
Corrected Code

menu = {
'soup': 'lentil',
'oyster': 'kumamoto',
'special': 'schnitzel',
}

template = ("Today's soup is %(soup)s, "
"buy one get two %(oyster)s oysters, "
"and our special entrée is %(special)s.")

formatted = template % menu
print(formatted)

Output

Today's soup is lentil, buy one get two kumamoto oysters, and our special entrée is schnitzel.

How it works

%(soup)s → replaced with menu['soup']

%(oyster)s → replaced with menu['oyster']

%(special)s → replaced with menu['special']

% menu → tells Python to substitute using the dictionary

The modern f-string version:

f-strings make this much cleaner than the old % formatting.


menu = {
'soup': 'lentil',
'oyster': 'kumamoto',
'special': 'schnitzel',
}

formatted = (
f"Today's soup is {menu['soup']}, "
f"buy one get two {menu['oyster']} oysters, "
f"and our special entrée is {menu['special']}."
)

print(formatted)

Output
Today's soup is lentil, buy one get two kumamoto oysters, and our special entrée is schnitzel.
✅ Advantages of f-strings:

Variables are inserted directly in {} → no need for % or .format().

Easier to read and maintain.

Supports formatting numbers, alignment, etc. (e.g., {price:.2f}).









Comments

Popular posts from this blog

python operator

  Python provides an if statement with the same semantics as languages like C++ and Java, although with its own sparse syntax: if expression1: suite1 elif expression2: suite2 else: suite3 The first thing that stands out to programmers used to C++ or Java is that there are no parentheses and no braces. The other thing to notice is the colon: This is part of the syntax and is easy to forget when starting out. Colons are used with else, elif, and in many other places to indicate that a block of code (a suite in Python-speak) is to follow. As we would expect, there can be any number. Group Operators Description Comparison <, <=, ==, !=, >=, > The <> operator is also permitted as a synonym for != but is deprecated Identity is, is not These are used to determine if two object references refer to the same underlying object Membership in, not in These are used on lists, dictionaries, and strings Logical not, and,or Both and and or short-circuit; the bit-wise equivalents a...