Skip to main content
Python for Beginners
CHAPTER 03 Beginner

Python Syntax and First Program

Updated: May 17, 2026
20 min read

# Python Syntax and First Program

Welcome to Chapter 3! Now that Python is installed on your machine, let's learn the rules of writing Python code. Every language has grammar rules — Python's "grammar" is its syntax. The great news? Python's syntax is one of the simplest and cleanest in the programming world.

---

1. Introduction

Syntax refers to the set of rules that define how a Python program is written. Just like English has grammar rules (capitalize the first letter, end with a period), Python has its own rules that must be followed for code to run correctly.

The beauty of Python is that its syntax was deliberately designed to be readable and intuitive. Guido van Rossum wanted Python code to look almost like English pseudocode.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Understand Python's syntax structure.
  • Use indentation correctly.
  • Write single-line and multi-line comments.
  • Use the print() function with various options.
  • Write and run complete Python programs.
  • Build a simple calculator as a mini project.

---

3. Python Syntax Basics

3.1 Statements

A statement is a single instruction that Python can execute:

```python id="py3_ex1" # Each line is a statement name = "Alice" age = 25 print(name)

123
### 3.2 Case Sensitivity
Python is **case-sensitive**. `Name`, `name`, and `NAME` are three different variables:

python id="py3_ex2" name = "Alice" Name = "Bob" NAME = "Charlie"

print(name) # Alice print(Name) # Bob print(NAME) # Charlie

123
### 3.3 Line Continuation
For long statements, use a backslash `\` to continue on the next line:

python id="py3_ex3" total = 10 + 20 + 30 + \ 40 + 50 + 60

print(f"Total: {total}") # Total: 210

12
Or use parentheses (preferred):

python id="py3_ex4" total = (10 + 20 + 30 + 40 + 50 + 60)

print(f"Total: {total}") # Total: 210

123
### 3.4 Multiple Statements on One Line
Use a semicolon `;` (but this is **not recommended** — it reduces readability):

python id="py3_ex5" a = 10; b = 20; print(a + b) # Works but avoid this style

123456
---

## 4. Indentation — Python's Signature Feature

Unlike Java, C++, or JavaScript which use `{}` curly braces to define code blocks, Python uses **indentation** (whitespace at the beginning of a line).

Code Block Comparison: ┌─────────────────┐ ┌─────────────────┐ │ Java/C++/JS: │ │ Python: │ │ │ │ │ │ if (x > 5) { │ │ if x > 5: │ │ print(x); │ │ print(x) │ │ print("Hi");│ │ print("Hi")│ │ } │ │ │ └─────────────────┘ └─────────────────┘ Uses { } Uses indentation

12345
### Rules for Indentation:
1. Use **4 spaces** per indentation level (PEP 8 standard).
2. Be **consistent** — don't mix tabs and spaces.
3. All code within the same block must have the same indentation.

python id="py3_ex6" # Correct indentation score = 85

if score >= 90: print("Grade: A") print("Excellent!") elif score >= 80: print("Grade: B") print("Good job!") else: print("Keep trying!")

12
### Indentation Error Example:

python id="py3_ex7" # ❌ WRONG — inconsistent indentation if True: print("Hello") print("World") # IndentationError!

1
**Error:**

IndentationError: unexpected indent

123456789
---

## 5. Comments in Python

Comments are notes for **humans** — Python ignores them completely. They explain what your code does and why.

### 5.1 Single-Line Comments
Use the `#` symbol:

python id="py3_ex8" # This is a single-line comment name = "Alice" # This is an inline comment

# Calculate the area of a rectangle length = 10 width = 5 area = length * width # length × width print(f"Area: {area}")

123
### 5.2 Multi-Line Comments
Python doesn't have a built-in multi-line comment syntax, but you can use triple quotes:

python id="py3_ex9" """ This is a multi-line comment. It spans multiple lines. Python treats this as a string literal that is not assigned to any variable, so it's effectively a comment. """

''' You can also use single triple quotes. Both work the same way. '''

print("Comments don't affect output!")

123
### 5.3 Docstrings
Triple-quoted strings placed as the first statement in a function or class are called **docstrings** (documentation strings):

python id="py3ex10" def calculatearea(length, width): """ Calculate the area of a rectangle. Parameters: length (float): The length of the rectangle. width (float): The width of the rectangle. Returns: float: The calculated area. """ return length * width

# Access the docstring print(calculatearea.doc_)

12345678
---

## 6. The print() Function — Deep Dive

The `print()` function is the most fundamental Python function. Let's master it.

### 6.1 Basic Usage

python id="py3_ex11" print("Hello, World!") print(42) print(3.14) print(True)

1
**Output:**

Hello, World! 42 3.14 True

12
### 6.2 Printing Multiple Values

python id="py3_ex12" # Separate values with commas print("Name:", "Alice", "Age:", 25)

1
**Output:**

Name: Alice Age: 25

123
### 6.3 The `sep` Parameter
Control what separates multiple values:

python id="py3_ex13" print("Apple", "Banana", "Cherry", sep=", ") print("2025", "01", "15", sep="-") print("Python", "is", "awesome", sep=" ❤️ ")

1
**Output:**

Apple, Banana, Cherry 2025-01-15 Python ❤️ is ❤️ awesome

123
### 6.4 The `end` Parameter
Control what appears at the end of print (default is `\n` — new line):

python id="py3_ex14" print("Loading", end="") print(".", end="") print(".", end="") print(".", end="") print(" Done!")

1
**Output:**

Loading.... Done!

12345678910
### 6.5 Escape Characters

| Escape | Meaning |
|--------|---------|
| `\n` | New line |
| `\t` | Tab |
| `\\` | Backslash |
| `\"` | Double quote |
| `\'` | Single quote |

python id="py3_ex15" print("Line 1\nLine 2\nLine 3") print("Name\tAge\tCity") print("Alice\t25\tNew York") print("He said \"Hello!\"") print('It\'s Python!')

1
**Output:**

Line 1 Line 2 Line 3 Name Age City Alice 25 New York He said "Hello!" It's Python!

1234
---

## 7. Writing Your First Complete Program

python id="py3ex16" # myfirst_program.py # A simple program that introduces you!

# Program header print("=" * 40) print(" MY FIRST PYTHON PROGRAM") print("=" * 40)

# Personal information name = "Student" language = "Python" year = 2025

# Display information print(f"\nHello! My name is {name}.") print(f"I am learning {language} in {year}.") print(f"This is my very first program!") print(f"\n{'=' * 40}") print(f" Thank you for running this program!") print(f"{'=' * 40}")

1
**Output:**

======================================== MY FIRST PYTHON PROGRAM ========================================

Hello! My name is Student. I am learning Python in 2025. This is my very first program!

======================================== Thank you for running this program! ========================================

123456
---

## 8. The Zen of Python

Type `import this` in your Python shell to see Python's philosophy:

python id="py3_ex17" import this

1
**Key principles:**

Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Readability counts. There should be one-- and preferably only one --obvious way to do it.

1234
---

## 9. Mini Project: Simple Calculator

python id="py3project" # simplecalculator.py # A basic calculator that performs arithmetic operations

print("=" * 40) print(" 🧮 SIMPLE PYTHON CALCULATOR") print("=" * 40)

# Define two numbers num1 = 15 num2 = 4

# Perform operations addition = num1 + num2 subtraction = num1 - num2 multiplication = num1 * num2 division = num1 / num2 floordivision = num1 // num2 modulus = num1 % num2 power = num1 ** num2

# Display results print(f"\n Numbers: {num1} and {num2}") print(f" {'-' * 30}") print(f" Addition : {num1} + {num2} = {addition}") print(f" Subtraction : {num1} - {num2} = {subtraction}") print(f" Multiplication : {num1} × {num2} = {multiplication}") print(f" Division : {num1} ÷ {num2} = {division:.2f}") print(f" Floor Division : {num1} // {num2} = {floordivision}") print(f" Modulus : {num1} % {num2} = {modulus}") print(f" Power : {num1} ^ {num2} = {power}") print(f"\n{'=' * 40}")

1
**Output:**

======================================== 🧮 SIMPLE PYTHON CALCULATOR ========================================

Numbers: 15 and 4 ------------------------------ Addition : 15 + 4 = 19 Subtraction : 15 - 4 = 11 Multiplication : 15 × 4 = 60 Division : 15 ÷ 4 = 3.75 Floor Division : 15 // 4 = 3 Modulus : 15 % 4 = 3 Power : 15 ^ 4 = 50625

======================================== ``

---

10. Common Mistakes

  1. 1. IndentationError: Mixing tabs and spaces. Configure your editor to use 4 spaces.
  1. 2. Forgetting the colon: if, for, while, def, and class statements must end with :.
  1. 3. Mismatched quotes: Starting with " and ending with ' causes a SyntaxError.
  1. 4. Forgetting parentheses in print(): In Python 3, print is a function: print("Hello"), not print "Hello".
  1. 5. Using reserved words as variable names: Words like print, if, for, class cannot be used as variable names.

---

11. Best Practices

  • Use 4 spaces for indentation — This is the PEP 8 standard.
  • Write meaningful comments — Explain *why*, not *what*.
  • Keep lines under 79 characters — Improves readability.
  • Use blank lines to separate logical sections of code.
  • Follow PEP 8 — Python's official style guide.

---

12. Exercises

  1. 1. Write a program that prints your name, city, and favorite food on separate lines.
  1. 2. Use sep and end parameters to print a custom formatted date.
  1. 3. Write a program with at least 5 comments explaining each step.
  1. 4. Create a multi-line string that displays a poem or quote.
  1. 5. Modify the calculator project to include two more numbers and compute the average.

---

13. MCQs with Answers

Q1: How many spaces should each indentation level use according to PEP 8? A) 2 B) 3 C) 4 D) 8 Answer: C — PEP 8 recommends 4 spaces per indentation level.

Q2: Which character starts a single-line comment in Python? A) // B) # C) -- D) /* Answer: B — The # symbol is used for single-line comments.

Q3: What does print("A", "B", sep="-") output? A) A B B) A-B C) AB D) A, B Answer: B — The sep parameter changes the separator to "-".

Q4: What happens if you mix tabs and spaces? A) Nothing, Python handles it B) IndentationError C) SyntaxError D) Warning only Answer: B — Mixing tabs and spaces causes an IndentationError.

Q5: Which of these is a valid multi-line comment in Python? A) /* comment */ B) <!-- comment --> C) ''' comment ''' D) // comment Answer: C — Triple quotes ''' or """ are used for multi-line comments.

Q6: What is the output of print("Hello", end="!")? A) Hello B) Hello! C) Hello ! D) !Hello Answer: B — The end parameter replaces the default newline with "!".

Q7: Python is: A) Case-insensitive B) Case-sensitive C) Both D) Neither Answer: B — Python is case-sensitive; Name and name are different.

Q8: What does \t represent in a string? A) New line B) Tab space C) Backslash D) Double quote Answer: B — \t represents a horizontal tab.

Q9: How do you continue a long statement to the next line? A) Using & B) Using \ C) Using | D) Using >> Answer: B — Use a backslash \ for line continuation.

Q10: What is the purpose of a docstring? A) To define variables B) To document functions and classes C) To import modules D) To handle errors Answer: B — Docstrings provide documentation for functions, classes, and modules.

---

14. Interview Questions

  1. 1. What is indentation in Python and why is it important?
*Answer:* Indentation is the whitespace at the beginning of a line that defines code blocks. Unlike other languages that use curly braces, Python uses indentation as a core part of its syntax. Incorrect indentation causes IndentationError.
  1. 2. What is the difference between comments and docstrings?
*Answer:* Comments (#) are ignored by Python and are for developer notes. Docstrings (triple-quoted strings) are stored as the
_doc_ attribute of functions/classes and can be accessed programmatically.
  1. 3. What is PEP 8?
*Answer:* PEP 8 is Python Enhancement Proposal #8, the official style guide for Python code. It covers naming conventions, indentation, line length, imports, and other formatting standards.
  1. 4. Can you write multiple statements on one line in Python?
*Answer:* Yes, using semicolons (
;), but it's discouraged as it reduces readability.
  1. 5. What are escape characters in Python?
*Answer:* Escape characters are special sequences starting with
\ that represent characters that are hard to type directly, like \n (newline), \t (tab), \\ (backslash), and \" (double quote).

---

15. FAQs

Q: Can I use tabs instead of spaces? A: While tabs work, PEP 8 strongly recommends using 4 spaces. Most modern editors can convert tabs to spaces automatically.

Q: Is there a semicolon at the end of Python statements? A: No. Python statements end with a newline, not a semicolon. Semicolons are optional and only used to put multiple statements on one line (which is discouraged).

Q: What happens if I forget the colon after if? A: You'll get a SyntaxError: expected ':' error. The colon is mandatory after if, elif, else, for, while, def, and class.

---

16. Summary

  • Python syntax is designed to be clean and readable.
  • Indentation (4 spaces) is used to define code blocks — it's not optional.
  • Comments use # for single-line and """ for multi-line.
  • The print() function supports sep, end`, and escape characters for flexible output.
  • Python is case-sensitive and statements end with newlines, not semicolons.
  • Following PEP 8 makes your code professional and maintainable.

---

17. Next Chapter Recommendation

You've mastered Python's syntax! In Chapter 4: Variables and Data Types, we'll explore how Python stores data — from integers and floats to strings and booleans. You'll learn about dynamic typing, type conversion, and memory management. Let's dive deeper! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·