Python Basics — Syntax & Fundamentals Exercises

3 minute read

Practice Exercises — Syntax & Fundamentals

Test your understanding of Python syntax, indentation, keywords, comments, and PEP 8 conventions with these exercises.


Exercise 1: Fix the Indentation

The following code has indentation errors. Fix them so the code runs correctly.

def greet(name):
print("Hello, " + name + "!")
    if name == "Python":
  print("Welcome back!")
Show Answer

Answer:

def greet(name):
    print("Hello, " + name + "!")
    if name == "Python":
        print("Welcome back!")

Expected output (when called with greet("Python")):

Hello, Python!
Welcome back!

Explanation: Every code block after a colon (:) must be indented by 4 spaces. The print inside def needs 4 spaces, and the print inside if needs 8 spaces (two levels).


Exercise 2: Identify the Keywords

Look at this code and list all the Python keywords used:

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

for i in range(10):
    if is_even(i) and not i == 0:
        print(i)
Show Answer

Answer: The Python keywords in this code are:

Keyword Line
def Line 1
if Line 2, Line 8
return Line 3, Line 5
True Line 3
else Line 4
False Line 5
for Line 7
in Line 7
and Line 8
not Line 8

Total: 10 keywords (with if and return used twice each).

You can verify keywords with:

import keyword
print(keyword.kwlist)

Exercise 3: Write Proper Comments

Rewrite this code with proper comments and a docstring following best practices:

def f(x, y):
    z = x * y * 0.08
    return x * y + z
Show Answer

Answer:

def calculate_total_with_tax(price, quantity):
    """Calculate the total cost including 8% sales tax.

    Args:
        price: The unit price of the item.
        quantity: The number of items purchased.

    Returns:
        The total cost including tax.
    """
    # Calculate tax at 8% rate
    tax = price * quantity * 0.08

    return price * quantity + tax

Key improvements:

  • Descriptive function name (calculate_total_with_tax instead of f)
  • Descriptive parameter names (price, quantity instead of x, y)
  • Docstring explaining what the function does, its parameters, and return value
  • Comment explaining the tax calculation
  • Descriptive variable name (tax instead of z)

Exercise 4: Fix PEP 8 Violations

This code works but has multiple PEP 8 violations. Rewrite it following PEP 8:

import sys,os
import math
from collections import OrderedDict
import json
x=10
y =20
MyList = [1,2,3,4,5]
def Calc( a,b ):
    RESULT=a+b
    return RESULT
class my_class:
    def MyMethod(self):
        pass
Show Answer

Answer:

import json
import math
import os
import sys
from collections import OrderedDict

x = 10
y = 20
my_list = [1, 2, 3, 4, 5]


def calc(a, b):
    result = a + b
    return result


class MyClass:

    def my_method(self):
        pass

Violations fixed:

Issue Before After
Multiple imports on one line import sys,os Separate lines
Import order Mixed up stdlib alphabetically, then from
No spaces around = x=10 x = 10
No space after commas [1,2,3] [1, 2, 3]
Spaces inside parentheses Calc( a,b ) calc(a, b)
Function name PascalCase Calc calc
Variable name PascalCase MyList my_list
UPPER_CASE for non-constant RESULT result
Class name snake_case my_class MyClass
Method name PascalCase MyMethod my_method
Missing blank lines No gaps 2 blank lines before def/class

Exercise 5: Identify Valid Identifiers

Which of the following are valid Python identifiers? For each invalid one, explain why.

my_variable
2nd_place
_private
class
user-name
__init__
first name
MAX_SIZE
$price
camelCase
Show Answer

Answer:

Identifier Valid? Reason
my_variable ✅ Yes Letters, underscores — valid snake_case
2nd_place ❌ No Cannot start with a digit
_private ✅ Yes Leading underscore is valid (convention for private)
class ❌ No class is a reserved keyword
user-name ❌ No Hyphens (-) are not allowed in identifiers
__init__ ✅ Yes Double underscore (“dunder”) names are valid
first name ❌ No Spaces are not allowed in identifiers
MAX_SIZE ✅ Yes Valid — convention for constants
$price ❌ No Special characters ($) are not allowed
camelCase ✅ Yes Technically valid, but PEP 8 prefers snake_case

Rule of thumb: Identifiers can contain letters (a–z, A–Z), digits (0–9), and underscores (_). They must start with a letter or underscore, and cannot be a Python keyword.

Verify a keyword:

import keyword
print(keyword.iskeyword("class"))  # True
print(keyword.iskeyword("my_var")) # False

Scoring Guide

Score Level
5/5 Excellent — You’ve mastered Python syntax fundamentals
4/5 Great — Minor gaps, review the topic you missed
3/5 Good — Review PEP 8 conventions and keywords
2/5 Needs Work — Re-read the syntax fundamentals chapter
1/5 Keep Going — Practice more and revisit indentation rules

Next chapter: Variables & Data Types →

Updated: