Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
- Integers (int): Whole numbers (e.g.,
5
,-10
) - Floats (float): Decimal numbers (e.g.,
3.14
,-2.5
) - Strings (str): Sequence of characters (e.g.,
'hello'
,"Python"
) - Booleans (bool):
True
orFalse
- Lists (list): Ordered, mutable collections (e.g.,
[1, 2, 3]
) - Tuples (tuple): Ordered, immutable collections (e.g.,
(1, 2, 3)
) - Sets (set): Unordered, unique elements (e.g.,
{1, 2, 3}
) - Dictionaries (dict): Key-value pairs (e.g.,
{"name": "Alice", "age": 25}
)
if condition:
# Code block executes if condition is True
elif another_condition:
# Code block executes if the second condition is True
else:
# Executes if none of the above conditions are True
- For Loop: Iterates over a sequence (list, tuple, string, etc.).
for i in range(5): print(i)
- While Loop: Repeats as long as the condition is True.
i = 0 while i < 5: print(i) i += 1
Functions are reusable blocks of code that perform a specific task.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Exception handling prevents runtime errors from crashing a program.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def show_details(self):
return f"Car: {self.brand} {self.model}"
car1 = Car("Toyota", "Camry")
print(car1.show_details())
Inheritance allows a class to inherit properties and methods from another class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak() # Outputs: Dog barks
When a child class has a method with the same name as a parent class but a different implementation.
with open("data.txt", "w") as file:
file.write("This is a test file.")
with open("data.txt", "r") as file:
content = file.read()
print(content)
You can define your own exceptions by inheriting from the Exception class.
class NegativeValueError(Exception):
def __init__(self, message="Value cannot be negative"):
super().__init__(message)
try:
value = int(input("Enter a number: "))
if value < 0:
raise NegativeValueError()
except NegativeValueError as e:
print(f"Error: {e}")