Python Syntax Explained: A Complete Beginner's Guide with Simple Examples
Python is one of the most popular programming languages in the world. It is widely used in web development, data analysis, artificial intelligence, machine learning, automation and many other fields.
If you are new to Python, one of the first things you need to understand is Python syntax.
But what exactly is Python syntax?
In simple words, Python syntax refers to the rules you must follow when writing Python code. These rules help Python understand your instructions and execute them correctly.
In this beginner-friendly guide, you will learn Python syntax step by step with simple examples.
What Is Python Syntax?
Python syntax is the set of rules used to write instructions in the Python programming language.
Just like English has grammar rules, Python has its own rules for writing code.
For example, look at this Python program:
print("Hello, World!")This is a simple Python statement. It tells the computer to display the text Hello, World!
Python syntax includes rules for:
- Writing statements
- Using variables
- Adding comments
- Creating strings
- Using indentation
- Writing conditions
- Creating loops
- Defining functions
- Working with data types
If you write code incorrectly, Python may display a syntax error.
1. Writing Your First Python Statement
A statement is an instruction that Python executes.
The print() function is one of the easiest ways to display information on the screen.
Example:
print("Welcome to Python")
print("Learning Python is easy")
print(100)Output:
Welcome to Python
Learning Python is easy
100Explanation:
print()displays information.- Text must be placed inside quotation marks.
- Numbers can be written without quotation marks.
You can write multiple statements on separate lines.
2. Python Is Case-Sensitive
Python is a case-sensitive programming language.
This means uppercase and lowercase letters are treated differently.
For example:
name = "Raj"
print(name)Output:
RajBut this code will produce an error:
name = "Raj"
print(Name)Why?
Because name and Name are two different identifiers in Python.
Remember these rules:
nameis different fromName.print()is correct.Print()is not the same asprint().
3. Understanding Python Indentation
Indentation means adding spaces at the beginning of a line of code.
In Python, indentation is very important because it defines a block of code.
Example:
age = 22
if age >= 18:
print("You are eligible to vote")Output:
You are eligible to voteNotice that the print() statement has spaces before it.
These spaces show that the statement belongs to the if block.
Incorrect example:
age = 22
if age >= 18:
print("You are eligible to vote")This code produces an indentation error.
Important: Python generally recommends using four spaces for each indentation level. Avoid mixing tabs and spaces.
4. Python Comments
Comments are notes written inside a program. Python ignores comments when executing code.
Comments help programmers understand what the code does.
There are two commonly used ways to write comments.
Single-line comment
Use the # symbol.
# This is a comment
print("Hello Python")Multi-line comments
Python does not have a special multi-line comment symbol. You can use multiple # lines:
# This program displays
# a welcome message
# for beginners
print("Welcome!")Triple-quoted strings are also commonly used for documentation, especially inside functions and classes.
"""
This is a documentation string.
It explains what the program does.
"""5. Python Variables
Variables are used to store information in a program.
You do not need to declare a variable type separately when creating a normal Python variable.
Example:
name = "Raj"
age = 25
salary = 30000
print(name)
print(age)
print(salary)Output:
Raj
25
30000Here:
namestores text.agestores an integer.salarystores a number.
Rules for naming Python variables:
- Variable names can contain letters, numbers and underscores.
- A variable name cannot start with a number.
- Spaces are not allowed in variable names.
- Variable names are case-sensitive.
- Python keywords cannot be used as variable names.
Valid examples:
student_name = "Alex"
age = 21
total_marks = 450Invalid example:
2name = "Alex"6. Python Data Types
Data types define the kind of information stored in a variable.
Python has several built-in data types.
| Data type | Meaning | Example |
|---|---|---|
| int | Whole numbers | age = 25 |
| float | Decimal numbers | price = 99.50 |
| str | Text | name = "Raj" |
| bool | True or False | is_active = True |
| list | Collection of items | [10, 20, 30] |
| tuple | Ordered collection | (10, 20, 30) |
| dict | Key-value pairs | {"name": "Raj"} |
| set | Unique items | {10, 20, 30} |
Example:
name = "Alex"
age = 24
height = 5.8
is_student = True
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))The type() function tells you the data type of a value.
7. Python Strings and Quotation Marks
A string is a collection of characters used to represent text.
Python allows you to create strings using single, double or triple quotation marks.
Example:
name = "Raj"
city = 'Delhi'
message = """Welcome to Python Programming"""
print(name)
print(city)
print(message)Output:
Raj
Delhi
Welcome to Python Programming
8. Python Operators
Operators are symbols that perform operations on values and variables.
Python supports different types of operators.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 10 + 5 |
- | Subtraction | 10 - 5 |
* | Multiplication | 10 * 5 |
/ | Division | 10 / 5 |
// | Floor division | 10 // 3 |
% | Modulus | 10 % 3 |
** | Exponentiation | 2 ** 3 |
Example:
a = 10
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)Output:
15
5
50
2.0Comparison operators
These operators compare two values and return either True or False.
a = 10
b = 5
print(a > b)
print(a < b)
print(a == b)
print(a != b)Output:
True
False
False
True9. Python If-Else Statements
Conditional statements allow Python to make decisions.
For example, you can check whether a person is eligible to vote.
age = 20
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")Output:
Eligible to votePython supports:
if- elif
- else
Example using elif:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")Output:
Grade B10. Python Loops
Loops help you execute the same block of code multiple times.
Python has two main types of loops:
For loop
A for loop is commonly used to iterate over a sequence.
for number in range(1, 6):
print(number)Output:
1
2
3
4
5While loop
A while loop runs as long as its condition is true.
count = 1
while count <= 5:
print(count)
count += 1Output:
1
2
3
4
511. Python Functions
Functions are reusable blocks of code that perform specific tasks.
You can create a function using the def keyword.
Example:
def greet():
print("Hello, welcome to Python")
greet()Output:
Hello, welcome to PythonYou can also pass information to a function using parameters.
def greet(name):
print("Hello", name)
greet("Raj")Output:
Hello RajFunctions make your programs easier to organise, reuse and maintain.
12. Python Lists and Dictionaries
Python provides different ways to store multiple values.
List
A list stores multiple items in one variable.
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
print(fruits[0])Output:
['Apple', 'Banana', 'Mango']
AppleDictionary
A dictionary stores information in key-value pairs.
student = {
"name": "Alex",
"age": 22,
"city": "Delhi"
}
print(student["name"])
print(student["age"])Output:
Alex
2213. Python Syntax Errors
A syntax error happens when Python cannot understand the code because it does not follow the language rules.
Example of incorrect syntax:
print("Hello Python"The closing parenthesis is missing.
Correct code:
print("Hello Python")Some common Python errors include:
| Error | Meaning |
|---|---|
| SyntaxError | Code does not follow Python syntax rules |
| IndentationError | Incorrect indentation |
| NameError | A name is not defined |
| TypeError | An operation uses an inappropriate type |
| ValueError | A value is inappropriate for an operation |
Understanding these errors will help you debug programs more effectively.
14. A Complete Python Program for Beginners
Now let's combine some of the concepts you have learned.
In this example, we will create a simple program that checks whether a student has passed or failed.
# Student result program
student_name = "Rahul"
marks = 75
print("Student Name:", student_name)
print("Total Marks:", marks)
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail")Output:
Student Name: Rahul
Total Marks: 75
Result: PassThis small program uses variables, comments, the print function, indentation and conditional statements.
Best Practices for Writing Clean Python Code
Learning syntax is important, but writing clean code is equally valuable.
Follow these beginner-friendly tips:
- Use meaningful variable names.
- Follow the four-space indentation rule.
- Write comments when they help explain your code.
- Keep your code simple and readable.
- Use lowercase names with underscores for ordinary variables and functions.
- Avoid unnecessary repeated code.
- Read error messages carefully.
- Practise writing small programs every day.
You can also follow the official Python style guide, known as PEP 8, to learn more about clean Python coding practices.
Frequently Asked Questions (FAQs)
1. What is Python syntax?
Python syntax refers to the rules used to write instructions in Python. It helps Python understand and execute your code.
2. Is Python syntax easy for beginners?
Yes. Python has a readable syntax that makes it a popular choice for beginners.
3. Why is indentation important in Python?
Indentation defines blocks of code, such as the statements inside loops, functions and conditional statements.
4. Is Python case-sensitive?
Yes. Python treats uppercase and lowercase letters differently. For example, name and Name are different identifiers.
5. What is a syntax error in Python?
A syntax error occurs when code does not follow Python's grammar rules, such as forgetting a closing parenthesis.
6. What is the difference between a statement and an expression?
A statement performs an action, while an expression produces a value. For example, x = 10 is an assignment statement, while 10 + 5 is an expression.
7. Where can I practise Python syntax?
You can practise using Python's interactive interpreter, IDLE, Visual Studio Code, Jupyter Notebook or online Python editors.
Conclusion
Python syntax is the foundation of Python programming. Before moving towards advanced topics such as data analysis, automation, machine learning and artificial intelligence, it is important to understand how Python code is written.
Start with simple statements, variables, data types, comments and indentation. Then practise conditions, loops, functions and collections.
Remember, you do not need to learn everything in one day. Write small programs, understand the output and practise regularly.
Keep learning and keep coding with ITTech Language!
Recommended next topic: Python Variables Explained with Simple Examples.






