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.