Python Syntax and First Program
# 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)
python id="py3_ex2" name = "Alice" Name = "Bob" NAME = "Charlie"
print(name) # Alice print(Name) # Bob print(NAME) # Charlie
python id="py3_ex3" total = 10 + 20 + 30 + \ 40 + 50 + 60
print(f"Total: {total}") # Total: 210
python id="py3_ex4" total = (10 + 20 + 30 + 40 + 50 + 60)
print(f"Total: {total}") # Total: 210
python id="py3_ex5" a = 10; b = 20; print(a + b) # Works but avoid this style
Code Block Comparison: ┌─────────────────┐ ┌─────────────────┐ │ Java/C++/JS: │ │ Python: │ │ │ │ │ │ if (x > 5) { │ │ if x > 5: │ │ print(x); │ │ print(x) │ │ print("Hi");│ │ print("Hi")│ │ } │ │ │ └─────────────────┘ └─────────────────┘ Uses { } Uses 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!")
python id="py3_ex7" # ❌ WRONG — inconsistent indentation if True: print("Hello") print("World") # IndentationError!
IndentationError: unexpected indent
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}")
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!")
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_)
python id="py3_ex11" print("Hello, World!") print(42) print(3.14) print(True)
Hello, World! 42 3.14 True
python id="py3_ex12" # Separate values with commas print("Name:", "Alice", "Age:", 25)
Name: Alice Age: 25
python id="py3_ex13" print("Apple", "Banana", "Cherry", sep=", ") print("2025", "01", "15", sep="-") print("Python", "is", "awesome", sep=" ❤️ ")
Apple, Banana, Cherry 2025-01-15 Python ❤️ is ❤️ awesome
python id="py3_ex14" print("Loading", end="") print(".", end="") print(".", end="") print(".", end="") print(" Done!")
Loading.... Done!
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!')
Line 1 Line 2 Line 3 Name Age City Alice 25 New York He said "Hello!" It's Python!
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}")
======================================== 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! ========================================
python id="py3_ex17" import this
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.
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}")
======================================== 🧮 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. IndentationError: Mixing tabs and spaces. Configure your editor to use 4 spaces.
-
2.
Forgetting the colon: if
,for,while,def, andclassstatements must end with:.
-
3.
Mismatched quotes: Starting with "
and ending with'causes a SyntaxError.
-
4.
Forgetting parentheses in print(): In Python 3, print
is a function:print("Hello"), notprint "Hello".
-
5.
Using reserved words as variable names: Words like print
,if,for,classcannot 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. Write a program that prints your name, city, and favorite food on separate lines.
-
2.
Use sep
andendparameters to print a custom formatted date.
- 3. Write a program with at least 5 comments explaining each step.
- 4. Create a multi-line string that displays a poem or quote.
- 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. What is indentation in Python and why is it important?
- 2. What is the difference between comments and docstrings?
attribute of functions/classes and can be accessed programmatically.
-
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.
-
4.
Can you write multiple statements on one line in Python?
*Answer:* Yes, using semicolons (;), but it's discouraged as it reduces readability.
-
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! 🚀