Python: Basics 1

Contents

Installing Python, pip, and Virtual Environments

Learn how to install Python, use pip to manage packages, and set up virtual environments (venv, virtualenv).

# Verify Python installation
python --version
python3 --version   # Linux/macOS

# Install packages with pip
pip install requests

# Create virtual environment (venv)
python -m venv myenv

# Activate (Windows)
myenv\Scripts\activate
# Activate (macOS/Linux)
source myenv/bin/activate

# Deactivate
deactivate

Running Python Scripts, REPL, and IPython

How to run Python scripts, use the interactive REPL, and leverage IPython for enhanced interactivity.

# hello.py
print("Hello, Python World!")

# Run script
python hello.py

# Start Python REPL
python
# In REPL:
>>> print("Hello in REPL")

# Install and run IPython
pip install ipython
ipython

Basic Syntax: Variables & Data Types

Understand Python's basic syntax, variables, and core data types (int, float, bool, str).

# Integer
x = 5
print(type(x))  # 

# Float
y = 3.14
print(type(y))  # 

# Boolean
is_valid = True
print(type(is_valid))  # 

# String
name = "Alice"
print(type(name))  # 

Strings & Formatting

Learn about Python strings, f-strings, format(), and the % operator for formatting.

name = "Bob"
age = 30

# f-string
print(f"Hello, my name is {name} and I am {age} years old.")

# format()
print("Hello, my name is {} and I am {} years old.".format(name, age))

# old % formatting
print("Hello, my name is %s and I am %d years old." % (name, age))

Operators: Arithmetic, Logical, Bitwise

Explore Python's arithmetic, logical, and bitwise operators in depth.

# Arithmetic
a = 10
b = 3

print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # 3.333...
print(a // b)  # 3 (floor division)
print(a % b)   # 1 (modulo)
print(a ** b)  # 1000 (exponent)

# Logical
x = True
y = False

print(x and y)  # False
print(x or y)   # True
print(not x)    # False

# Bitwise
a = 5      # 0b0101
b = 3      # 0b0011

print(a & b)   # 1 (0b0001)
print(a | b)   # 7 (0b0111)
print(a ^ b)   # 6 (0b0110)
print(~a)      # -6 (inverts bits)
print(a << 1)  # 10 (shift left)
print(a >> 1)  # 2  (shift right)