Essentials of Python Programming
1. Variables and Data Types
- Variables: Containers to store data.
x = 10 # Integer
name = "Alice" # String
is_active = True # Boolean
- Data Types:
- Numeric: int, float, complex
- Sequence: list, tuple, range
- Text: str
- Mapping: dict
- Set Types: set, frozenset
- Boolean: bool
- Binary: bytes, bytearray, memoryview
2. Control Flow
- Conditional Statements:
if condition:
# code block
elif another_condition:
# code block
else:
# code block
- Loops:
- for Loop:
for i in range(5):
print(i)
- while Loop:
while condition:
# code block
- Break and Continue:
for i in range(10):
if i == 5:
break # Exit loop
if i % 2 == 0:
continue # Skip to next iteration
3. Functions
- Defining Functions:
def greet(name):
return f"Hello, {name}!"
- Lambda Functions:
square = lambda x: x**2
print(square(5))
4. Data Structures
- Lists:
fruits = ["apple", "banana", "cherry"]
[Link]("orange")
fruits[0] = "kiwi"
- Tuples:
dimensions = (200, 50)
- Dictionaries:
person = {"name": "John", "age": 30}
person["age"] = 31
- Sets:
unique_numbers = {1, 2, 3, 3}
5. Object-Oriented Programming (OOP)
- Classes and Objects:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
return f"Hi, I am {[Link]}!"
john = Person("John", 30)
print([Link]())
- Inheritance:
class Employee(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
[Link] = salary
6. File Handling
- Reading Files:
with open("[Link]", "r") as file:
content = [Link]()
- Writing Files:
with open("[Link]", "w") as file:
[Link]("Hello, World!")
7. Error Handling
- Try-Except Blocks:
try:
x=1/0
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Execution complete.")
8. Modules and Libraries
- Importing Modules:
import math
print([Link](16))
- Installing Libraries (using pip):
pip install requests
- Using Libraries:
import requests
response = [Link]("[Link]
print([Link])
9. Useful Tips
- List Comprehensions:
squares = [x**2 for x in range(10)]
- Unpacking:
a, b, *rest = [1, 2, 3, 4]
- Enumerate:
for index, value in enumerate(["a", "b", "c"]):
print(index, value)