Syntax is the set of rules for how a Python program must be written. Python is known for clean, readable syntax: no semicolons, no curly braces, and indentation that actually matters.
What You Will Learn
- How to write and run your first program
- Identifiers and keywords
- Why indentation matters
- Comments, multi-line statements and quotes
Prerequisites
Python 3 installed. See Python Installation.
Your First Python Program
print('Hello, Machine Learning!')
Explanation: print() displays text. Save it as hello.py and run python hello.py, or run it in a Jupyter cell with Shift+Enter.
Hello, Machine Learning!
Identifiers
An identifier is the name of a variable, function or class.
| Rule | Valid | Invalid |
|---|---|---|
| Start with a letter or _ | name, _count |
1name |
| Only letters, digits, _ | total_marks |
total-marks |
| Not a keyword | my_class |
class |
Age and age are different.Keywords
import keyword
print(keyword.kwlist)
Explanation: Keywords such as if, for, def, class, True and None have special meaning and cannot be used as names. The exact list depends on your Python version.
Indentation
Python groups code into blocks using indentation. Use 4 spaces per level.
marks = 75
if marks >= 40:
print('Pass')
print('Well done')
else:
print('Fail')
Explanation: Both indented lines belong to the if block. Inconsistent indentation raises IndentationError.
Pass Well done
Comments
# single-line comment
print('Hi') # comment after code
"""
Triple-quoted text is often used
as a multi-line comment or docstring.
"""
Explanation: Python ignores everything after #. Use comments to explain why the code does something.
Multi-Line Statements
total = 10 + \
20 + \
30
days = ['Mon', 'Tue',
'Wed', 'Thu']
print(total, days)
Explanation: A backslash continues a line. Inside (), [] or {} you can break lines without it, which is the preferred style.
60 ['Mon', 'Tue', 'Wed', 'Thu']
Quotes
a = 'single'
b = "double"
c = '''triple quotes
span lines'''
print("It's easy")
Explanation: Single and double quotes are the same. Triple quotes allow text over several lines.
Taking Input
name = input('Enter your name: ')
print('Hello', name)
Explanation: input() always returns a string.
Common Errors
| Problem | Cause and fix |
|---|---|
IndentationError |
Indent the line after if/for/def/class consistently with 4 spaces. |
SyntaxError: invalid syntax |
Usually a missing : or an unclosed bracket or quote. |
NameError: name 'Print' is not defined |
Python is case-sensitive; use print. |
Practice Exercises
- Print your name, city and favourite language on three lines.
- Write if/else that prints Even or Odd.
- Check if
lambdais a keyword withkeyword.iskeyword().
Interview Questions
Q: How does Python define blocks?
By indentation instead of braces.
Q: What does input() return?
A string.
Summary
Python uses indentation for blocks, # for comments, case-sensitive names, and no semicolons.
Machine Learning Tutorials, Courses and Certifications