Every Python journey starts with a single line of code. This chapter gets you writing, running, and understanding Python immediately.

Hello, World!

  print("Hello, World!")
  

print() sends text to the screen. Strings go inside quotes — single (') or double (") both work.

Save this as hello.py and run:

  python hello.py
  

Output:

  Hello, World!
  

The Interactive REPL

Python includes a Read-Eval-Print Loop — type code and see results instantly:

  python
  
  >>> 2 + 3
5
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!
>>> exit()
  

The >>> prompt means Python is waiting for input. Use the REPL to experiment quickly.

Running Scripts vs the REPL

REPL Script (.py file)
Instant feedback Reusable, shareable
Lost when you exit Saved to disk
Good for experiments Good for real programs

Comments

Comments explain code to humans. Python ignores them:

  # This is a single-line comment
print("Visible")  # Inline comment after code

"""
This is a multi-line string,
often used as a docstring at the top of a file or function.
"""
  

Variables and f-Strings

  language = "Python"
version = 3.12
print(f"I am learning {language} {version}")
# Output: I am learning Python 3.12
  

Variables hold values. f"..." embeds variables inside strings — the modern way to format text.

Basic Math

  print(10 + 3)    # 13  addition
print(10 - 3)    # 7   subtraction
print(10 * 3)    # 30  multiplication
print(10 / 3)    # 3.333...  division (always float)
print(10 // 3)   # 3   floor division
print(10 % 3)    # 1   remainder (modulo)
print(2 ** 10)   # 1024  exponent
  

Getting User Input

  name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hi {name}, you will be {age + 1} next year.")
  

input() always returns a string. Use int() or float() to convert when needed.

A Complete Mini Program

  """Temperature converter: Celsius to Fahrenheit."""

def celsius_to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

def main():
    c = float(input("Enter temperature in °C: "))
    f = celsius_to_fahrenheit(c)
    print(f"{c}°C = {f:.1f}°F")

if __name__ == "__main__":
    main()
  

Key ideas:

  • Functions group reusable logic (celsius_to_fahrenheit)
  • if __name__ == "__main__" runs main() only when the file is executed directly
  • :.1f formats a float to one decimal place

Common Beginner Errors

Error Cause Fix
SyntaxError Missing colon, parenthesis, or quote Check punctuation
NameError Variable used before assignment Define the variable first
IndentationError Inconsistent spaces/tabs Use 4 spaces per level
TypeError Wrong type for operation Convert types explicitly

Run your code often. Fix one error at a time. You’re now ready for Python Basics.

Running Scripts: More Options

  # Explicit interpreter
python3 hello.py

# Make executable on Unix (add shebang first)
chmod +x hello.py
./hello.py
  

Add a shebang line at the top of scripts you run directly:

  #!/usr/bin/env python3
print("Hello, World!")
  

Run a module inside a package:

  python -m pip install requests   # runs pip as a module
python -m http.server 8000       # built-in file server
  

Reading and Writing Files (Preview)

You’ll cover files in depth in File Handling. A quick taste:

  from pathlib import Path

path = Path("greeting.txt")
path.write_text("Hello from Python!\n")
print(path.read_text())
  

pathlib.Path is the modern way to work with file paths — prefer it over string concatenation.

Debugging Your First Errors

When something breaks, read the traceback from bottom to top:

  Traceback (most recent call last):
  File "hello.py", line 4, in <module>
    print(greeting)
NameError: name 'greeting' is not defined
  

Line 4 in hello.py references greeting, which was never defined. Fix that line, save, and run again.

Use print() liberally while learning — it’s the simplest debugger:

  temperature = 25
print(f"DEBUG: temperature={temperature}")