Skip to content

Comments, Input & Type Conversion

Comments

Comments are notes for humans — Python ignores them when running.

# This is a single-line comment

print("hello")  # comment at the end of a line

# Use multiple # lines
# for a comment block

"""
This is technically a string, but if you don't
assign it to anything, it works as a multi-line
comment / docstring.
"""

print("done")

When to use comments: - Explain why (the what should be obvious from the code). - Mark TODOs: # TODO: handle the edge case. - Warn about non-obvious behavior.

When NOT to comment: - Restating what the code obviously does. - Outdated explanations that disagree with the current code (worse than no comment).

Taking input from the user

input() reads a line of text from the user. It always returns a string — even if the user types a number.

name = input("What's your name? ")
print("Hello,", name)

Note: In Pyodide (the browser Python), input() pops up a small prompt. In a regular terminal it reads from stdin.

Type conversion

Since input() returns a string, you'll often need to convert it to a number.

# input() returns a string
age_str = "25"
print(type(age_str))    # <class 'str'>

# Convert to int
age = int(age_str)
print(type(age))        # <class 'int'>
print(age + 5)          # now math works

Common conversion functions:

Function Converts to Example
int(x) integer int("42")42
float(x) decimal float("3.14")3.14
str(x) string str(42)"42"
bool(x) True/False bool(0)False, bool(1)True
list(x) list list("abc")['a','b','c']

Run this:

# A string of digits → int
n = int("100")
print(n + 1)                # 101

# An int → str (useful for printing)
age = 25
msg = "I am " + str(age) + " years old"
print(msg)

# Float to int — drops the decimal (no rounding)
print(int(3.99))            # 3
print(int(-3.99))           # -3

# Round properly
print(round(3.99))          # 4
print(round(3.14159, 2))    # 3.14

Putting it together — a mini calculator

# Two hard-coded inputs (instead of input() so it runs cleanly)
a_str = "12"
b_str = "8"

# Convert to numbers
a = int(a_str)
b = int(b_str)

# Compute
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")

f-strings — the modern way to format output

f"..." lets you embed values directly inside a string with {...}:

name = "Alice"
age = 25
balance = 1234.5678

print(f"{name} is {age} years old.")
print(f"Balance: ${balance:.2f}")          # 2 decimal places
print(f"Hex of 255: {255:#x}")              # 0xff
print(f"Padded:    {age:>5}")               # right-aligned in 5 chars

f-strings are faster and more readable than older % or .format() styles. Use them by default.

Practice

What does this print?

Expected: Price: $9.50

price = 9.4999
print(f"Price: ${price:.2f}")

Add the age to the year correctly

Expected: 30

age_str = "25"
bonus = 5
print(age_str + bonus)   # bug: can't add str + int — convert first

Quiz — Quick check

What you remember

Q1. input() always returns a value of type…

  • int
  • depends on what the user typed
  • str
  • bytes

Why: Every keystroke is read as text. If you need a number, convert it with int(...) or float(...).

Q2. What does int(3.99) return?

  • 3
  • 4
  • 3.99
  • IndexError

Why: int() truncates toward zero — it drops the decimal part without rounding. Use round(3.99) to get 4.

Q3. Which is the most modern, recommended way to format Alice is 25?

  • "%s is %d" % ("Alice", 25)
  • "{} is {}".format("Alice", 25)
  • f"{name} is {age}"
  • "Alice" + " is " + str(25)

Why: f-strings (Python 3.6+) are faster, more readable, and the recommended default. The other forms still work — you'll see them in older code.

Common doubts

What's the difference between # comment and \"\"\"docstring\"\"\"?

# is a true comment — ignored at parse time. A triple-quoted string isn't ignored: it's a string object. If it's not assigned, Python just discards it. The convention is: - Use # for explanatory notes. - Use """...""" as the first statement inside a function or class to document it — that's a "docstring", and tools like help() pick it up.

Why is \"5\" + 3 an error but \"5\" * 3 works?

+ between strings does concatenation; between a string and an int it has no sensible meaning, so Python raises TypeError. * between a string and an int is defined to repeat the string: "5" * 3"555".

Should I use single or double quotes for strings?

Either works. Pick one and be consistent. Most style guides (and black, the popular formatter) prefer double quotes. Use the other kind when your string contains the first kind — e.g. "don't" avoids escaping.

What's next

Operators