Python Syntax
Python is known for its clean and readable syntax. It emphasizes code readability and allows developers to write fewer lines of code compared to other programming languages.
Basic Syntax Structure
Python uses indentation instead of curly braces {} to define blocks of code.
Example:
if 5 > 2:
print("Five is greater than two!")
- Indentation is crucial in Python. Missing or incorrect indentation will raise an error.
Comments
Single-line comment:
# This is a comment
print("Hello, World!")
Multi-line comment (using triple quotes):
"""
This is a
multi-line comment
"""
print("Hello again!")
Variables
Python does not require you to declare the type of a variable.
x = 10 # integer
y = "Hello" # string
z = 3.14 # float
Multiple assignment:
a, b, c = 1, 2, 3
Data Types
Some common data types in Python:
int: Integerfloat: Floating pointstr: Stringbool: Booleanlist: List of itemstuple: Immutable listdict: Key-value pairset: Unique unordered collection
num = 10 # int
name = "Alice" # str
items = [1, 2, 3] # list
person = {"name": "Bob", "age": 25} # dict
Conditionals
age = 18
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")
Loops
for loop:
for i in range(5):
print(i)
while loop:
count = 0
while count < 5:
print(count)
count += 1
Functions
Functions are defined using the def keyword.
def greet(name):
print("Hello, " + name)
greet("Alice")
Return statement:
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5
Modules and Imports
You can import built-in or custom modules.
import math
print(math.sqrt(16)) # Output: 4.0
Operators
Arithmetic Operators:
+ - * / // % **
Comparison Operators:
== != > < >= <=
Logical Operators:
and or not
Indentation Rules
Python uses 4 spaces (by convention) for indentation. Do not mix tabs and spaces.
Incorrect:
if True:
print("Hello") # IndentationError
Correct:
if True:
print("Hello")
Conclusion
Python syntax is simple, readable, and beginner-friendly. With its use of indentation and minimalistic style, it allows you to focus on solving problems rather than worrying about complex syntax rules.
📌 Note: Make sure your Python files have the
.pyextension and you're using Python 3.x version for compatibility with modern features.