
Open your terminal or command prompt and type:
python --version
# or
python3 --version
You should see a version number (e.g., Python 3.9.7).
Create a file named hello.py with the following content:
print("Hello, World!")
Run it from the terminal:
python hello.py
Python is dynamically typed, meaning you don't need to declare variable types explicitly.
# Integer
age = 25
# Float
price = 19.99
# String
name = "Alice"
# Boolean
is_student = True
Use # for single-line comments.
# This is a comment and will be ignored by the interpreter
Python has four built-in data structures: List, Tuple, Set, and Dictionary.
Ordered, mutable collections.
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # Add an item
print(fruits[0]) # Access first item: "apple"
Ordered, immutable collections.
coordinates = (10.0, 20.0)
# coordinates[0] = 5.0 # This will cause an error!
Key-value pairs.
person = {
"name": "Bob",
"age": 30,
"is_employed": True
}
print(person["name"]) # Output: Bob
Unordered collections of unique elements.
unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
For Loop: Iterates over a sequence.
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
While Loop: Repeats as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
Functions allow you to reuse code. Use the def keyword.
def greet(name):
"""This function greets the person passed in as a parameter."""
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Output: Hello, Alice!
Python provides built-in functions to read from and write to files. The key concept here is the Context Manager (with statement), which ensures files are properly closed after operations, even if an error occurs.
Use the open() function with mode 'w' (write) or 'a' (append).
# Mode 'w' overwrites the file if it exists, or creates a new one
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
print("File written successfully.")
Modes Reference:
- 'w': Write mode (overwrites existing content).
- 'a': Append mode (adds to the end of the file).
- 'r': Read mode (default, raises error if file doesn't exist).
Use mode 'r' to read content.
# Reading the entire file content
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line (useful for large files)
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes the newline character
For most text files, the examples above work perfectly. However, if you are dealing with images, audio, or other non-text data, you must use binary mode by adding a b to the mode string (e.g., 'rb', 'wb').
# Example: Copying an image file
with open('source.jpg', 'rb') as f_source:
with open('destination.jpg', 'wb') as f_dest:
f_dest.write(f_source.read())
A virtual environment is a self-contained directory tree that includes a Python installation for a particular version of Python, plus a number of additional packages.
pandas==1.3.0 and Project B needs pandas==2.0.0). Virtual environments prevent conflicts.Python includes a module called venv (since Python 3.3) to create virtual environments.
Navigate to your project directory in the terminal and run:
python -m venv venv
This creates a folder named venv in your current directory. You can name it anything you like (e.g., .venv, env).
On macOS/Linux:
source venv/bin/activate
On Windows (Command Prompt):
venv\Scripts\activate.batvenv\Scripts\Activate.ps1
pip install requests
python my_script.py
deactivate
pip freeze > requirements.txt
pip install -r requirements.txt