Python Syntax
Python has a clean and simple syntax that emphasizes readability. Here’s a quick overview of Python’s key syntax features:
1. Comments
Comments in Python start with the # symbol. Python ignores anything written after the #, which is useful for adding explanations to your code.
# This is a comment
print("Hello, World!") # This prints Hello, World!
2. Variables and Assignment
You don’t need to declare variables with a type in Python. Just assign a value, and Python will infer the type.
x = 10 # Integer
name = "Alice" # String
price = 19.99 # Float
is_active = True # Boolean
3. Indentation
Python uses indentation (spaces or tabs) to define blocks of code. Indentation replaces the need for braces {} or begin/end statements found in other languages. A typical indent is 4 spaces.
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
4. Data Types
Python has several built-in data types:
- Numbers:
int,float,complexa = 10 # int b = 3.14 # float - Strings: A sequence of characters enclosed in quotes.
greeting = "Hello" - Lists: Ordered collections of items.
fruits = ["apple", "banana", "cherry"] - Tuples: Ordered, immutable collections.
point = (1, 2) - Dictionaries: Unordered collections of key-value pairs.
person = {"name": "Alice", "age": 25} - Sets: Unordered collections of unique elements.
unique_numbers = {1, 2, 3, 4}
5. Control Flow
a. if, elif, else
Conditional statements in Python are controlled using if, elif (else-if), and else.
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just turned 18!")
else:
print("You are an adult.")
b. for Loop
Used to iterate over a sequence (like lists, tuples, or strings).
for fruit in fruits:
print(fruit)
c. while Loop
Executes a block of code as long as a condition is true.
i = 1
while i <= 5:
print(i)
i += 1 # Increment i
6. Functions
Functions are defined using the def keyword. You can define your own functions with any logic inside them.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
7. Return Statement
The return keyword is used in a function to send back a result.
def add(a, b):
return a + b
result = add(3, 5) # result is 8
8. List Comprehensions
A concise way to create lists in Python.
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
9. Exception Handling
Errors can be handled using try, except, and finally.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")
finally:
print("This will always be executed.")
10. Class and Objects
Python supports object-oriented programming. You can define classes and create objects.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Rex")
my_dog.bark() # Output: Rex says Woof!
11. Lambda Functions
Lambda functions are small anonymous functions defined with the lambda keyword.
double = lambda x: x * 2
print(double(5)) # Output: 10
12. Input and Output
You can use input() to get input from the user and print() to output information.
name = input("Enter your name: ")
print(f"Hello, {name}!")
13. Importing Modules
Python allows you to import built-in and third-party modules using import.
import math
print(math.sqrt(16)) # Output: 4.0
14. File Handling
Python makes reading and writing files easy using the open() function.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, World!
These are the basic syntax rules you need to know to get started in Python. Once you’re comfortable with this, you can explore more advanced features like decorators, generators, and more!