# Variables and Data Types
name = "John" # String
age = 25 # Integer
height = 1.75 # Float
is_student = True # Boolean
# Basic Input and Output
print("Hello, World!")
name = input("Enter your name: ")
print("Hello,", name)
# Conditional Statements
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Conditional Statements
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Loops
for i in range(5):
print(i)
while condition:
# Code block
# Lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
# Functions
def greet(name):
print("Hello,", name)
greet("Alice")
# Dictionaries
person = {"name": "John", "age": 25, "city": "New York"}
print(person["name"])
# Dictionaries
person = {"name": "John", "age": 25, "city": "New York"}
print(person["name"])
# List Comprehensions
squared_numbers = [x**2 for x in range(1, 6)]
print(squared_numbers)
# Classes and Objects
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
my_car = Car("Toyota", "Corolla")
print(my_car.make, my_car.model)
# Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
# Modules and Packages
import math
print(math.sqrt(16))
# File Handling
with open("data.txt", "r") as file:
data = file.read()
print(data)
Why Use Virtual Environments?
- Isolation: Each virtual environment is self-contained, with its own Python interpreter and packages, preventing conflicts between different projects.
- Dependency Management: Allows you to specify project-specific dependencies without affecting other projects.
- Portability: Virtual environments can be easily shared or recreated, ensuring consistent environments across different systems.
# Create - This command creates a new directory named myenv containing the virtual environment.
python -m venv myenv
# Activate
source myenv/bin/activate
# Within the virtual emvironment, any Python package can be installed using 'pip' and will be specific to that environment.
pip install package_name
# Deactivate:
deactivate
Best Practices
- Use Virtual Environments for Each Project: Create a separate virtual environment for each new Python project to maintain isolation and manage dependencies effectively.
- Include Virtual Environment in Version Control: It's a good practice to include the requirements.txt file generated by pip freeze in your version control system. This file lists all the packages installed in the virtual environment, making it easy for collaborators to recreate the same environment.