Master Python - a powerful, versatile programming language used for web development, data science, AI, and more
Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.
print("Hello, World!")
To start programming in Python, you need to install Python and optionally set up a development environment.
python --version
in terminalOption | Description |
---|---|
IDLE | Python's built-in IDE |
PyCharm | Professional Python IDE by JetBrains |
VS Code | Lightweight editor with Python extension |
Jupyter Notebook | Interactive computing environment |
Online Editors | Replit, Google Colab, PythonAnywhere |
python
in terminal.py
file and run with python filename.py
# Create hello.py
print("Python is working!")
# Run in terminal:
# python hello.py
Python syntax is clean and easy to read with significant whitespace (indentation) for code blocks.
# This is a comment
def main(): # Function definition
# Indented block
print("Hello")
if __name__ == "__main__":
main() # Function call
Component | Description | Example |
---|---|---|
Comments | Explanatory notes | # Single-line comment |
Variables | Store data values | x = 5 |
Functions | Reusable code blocks | def greet(): ... |
Indentation | Defines code blocks | if x > 0: |
Print Output | Display to console | print("Hello") |
# Simple calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Sum: {num1 + num2}")
print(f"Product: {num1 * num2}")
Python has several built-in data types:
Data Type | Description | Example |
---|---|---|
int |
Integer numbers | x = 5 |
float |
Decimal numbers | y = 3.14 |
str |
Text (strings) | name = "Alice" |
bool |
Boolean (True/False) | is_active = True |
list |
Ordered, mutable sequence | colors = ["red", "green"] |
tuple |
Ordered, immutable sequence | point = (10, 20) |
dict |
Key-value pairs | person = {"name": "John"} |
set |
Unordered, unique elements | unique = {1, 2, 3} |
x = 5 # int
y = float(x) # 5.0
z = str(x) # "5"
# Checking data types
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type({"a": 1})) # <class 'dict'>
Variables are containers for storing data values. In Python, variables are created when you assign a value to them.
variable_name = value
# Different variable types
name = "Alice" # String
age = 25 # Integer
height = 5.9 # Float
is_student = True # Boolean
age
and Age
are different)if
, while
)user_age
instead of ua
)# Assign multiple values
x, y, z = "Orange", "Banana", "Cherry"
# Assign same value
a = b = c = "Apple"
Python has various operators for different operations:
Operator | Description | Example |
---|---|---|
+ |
Addition | 5 + 3 → 8 |
- |
Subtraction | 5 - 3 → 2 |
* |
Multiplication | 5 * 3 → 15 |
/ |
Division | 5 / 3 → 1.666... |
% |
Modulus | 5 % 3 → 2 |
** |
Exponentiation | 5 ** 3 → 125 |
// |
Floor division | 5 // 3 → 1 |
Operator | Description | Example |
---|---|---|
== |
Equal | 5 == 3 → False |
!= |
Not equal | 5 != 3 → True |
> |
Greater than | 5 > 3 → True |
< |
Less than | 5 < 3 → False |
>= |
Greater than or equal | 5 >= 3 → True |
<= |
Less than or equal | 5 <= 3 → False |
Operator | Description | Example |
---|---|---|
and |
Returns True if both statements are true | x > 3 and x < 10 |
or |
Returns True if one of the statements is true | x > 3 or x < 10 |
not |
Reverse the result | not(x > 3) |
# Operator examples
a = 10
b = 20
print(f"a + b = {a + b}")
print(f"a < b: {a < b}")
print(f"a == 10 and b == 20: {a == 10 and b == 20}")
Conditional statements are used to perform different actions based on different conditions.
if condition:
# code to execute if condition is True
if condition:
# code if True
else:
# code if False
if condition1:
# code if condition1 True
elif condition2:
# code if condition2 True
else:
# code if all False
value_if_true if condition else value_if_false
# Grade calculator
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # B
# Ternary example
result = "Pass" if score >= 60 else "Fail"
Loops are used to execute a block of code repeatedly.
while condition:
# code to execute
for item in sequence:
# code to execute
break
- Terminates the loopcontinue
- Skips current iterationpass
- Placeholder for empty block# while loop
i = 1
while i <= 5:
print(i)
i += 1
# for loop with range
for num in range(1, 6):
if num == 3:
continue
print(num)
# for loop with list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Functions are blocks of reusable code that perform a specific task.
def function_name(parameters):
"""docstring"""
# function body
return value
function_name(arguments)
# Function definition
def greet(name):
"""This function greets the person passed in"""
return f"Hello, {name}!"
# Function call
message = greet("Alice")
print(message) # Hello, Alice!
def greet(name="Guest"):
print(f"Hello, {name}!")
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
square = lambda x: x * x
print(square(5)) # 25
Lists are ordered, mutable collections of items (can contain mixed types).
my_list = [1, 2, 3]
empty_list = []
mixed_list = [1, "Hello", 3.4]
Operation | Description | Example |
---|---|---|
Indexing | Access item by index | my_list[0] → 1 |
Slicing | Get sublist | my_list[1:3] → [2, 3] |
Append | Add item to end | my_list.append(4) |
Insert | Insert at position | my_list.insert(1, 5) |
Remove | Remove item | my_list.remove(2) |
Pop | Remove and return item | my_list.pop() → 3 |
Length | Number of items | len(my_list) → 3 |
# List operations
fruits = ["apple", "banana", "cherry"]
# Access elements
print(fruits[1]) # banana
# Change element
fruits[0] = "orange"
# Add elements
fruits.append("grape")
# Remove element
fruits.remove("banana")
# Loop through list
for fruit in fruits:
print(fruit)
squares = [x**2 for x in range(10)]
even_numbers = [x for x in range(20) if x % 2 == 0]
Tuples are ordered, immutable collections of items (can contain mixed types).
my_tuple = (1, 2, 3)
empty_tuple = ()
single_item = (5,) # Note the comma
Operation | Description | Example |
---|---|---|
Indexing | Access item by index | my_tuple[0] → 1 |
Slicing | Get subtuple | my_tuple[1:3] → (2, 3) |
Count | Count occurrences | my_tuple.count(2) → 1 |
Index | Find index of item | my_tuple.index(3) → 2 |
Length | Number of items | len(my_tuple) → 3 |
# Tuple operations
colors = ("red", "green", "blue")
# Access elements
print(colors[1]) # green
# Unpacking
r, g, b = colors
print(g) # green
# Immutable - this will error
# colors[0] = "yellow"
Dictionaries are unordered collections of key-value pairs.
my_dict = {"name": "John", "age": 30}
empty_dict = {}
with_dict = dict(name="John", age=30)
Operation | Description | Example |
---|---|---|
Access | Get value by key | my_dict["name"] → "John" |
Add/Update | Add or change item | my_dict["city"] = "NY" |
Remove | Remove item | del my_dict["age"] |
Keys | Get all keys | my_dict.keys() |
Values | Get all values | my_dict.values() |
Items | Get key-value pairs | my_dict.items() |
Length | Number of items | len(my_dict) → 2 |
# Dictionary operations
person = {
"name": "Alice",
"age": 25,
"city": "London"
}
# Access value
print(person["name"]) # Alice
# Add new key-value
person["email"] = "alice@example.com"
# Loop through dictionary
for key, value in person.items():
print(f"{key}: {value}")
squares = {x: x**2 for x in range(6)}
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
Sets are unordered collections of unique elements.
my_set = {1, 2, 3}
empty_set = set() # Not {}
from_list = set([1, 2, 3])
Operation | Description | Example |
---|---|---|
Add | Add element | my_set.add(4) |
Remove | Remove element | my_set.remove(2) |
Union | Combines sets | set1 | set2 |
Intersection | Common elements | set1 & set2 |
Difference | Elements in set1 not in set2 | set1 - set2 |
Symmetric Difference | Elements in either set but not both | set1 ^ set2 |
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union
print(a | b) # {1, 2, 3, 4, 5, 6}
# Intersection
print(a & b) # {3, 4}
# Difference
print(a - b) # {1, 2}
# Symmetric difference
print(a ^ b) # {1, 2, 5, 6}
Strings in Python are sequences of Unicode characters.
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = """Multi-line
string"""
Operation | Description | Example |
---|---|---|
Concatenation | Combine strings | "Hello" + "World" → "HelloWorld" |
Repetition | Repeat string | "Hi" * 3 → "HiHiHi" |
Indexing | Get character | "Hello"[1] → 'e' |
Slicing | Get substring | "Hello"[1:4] → 'ell' |
Length | Number of characters | len("Hello") → 5 |
Formatting | Insert values | f"Hello {name}" |
s = " Hello World! "
s.strip() # "Hello World!"
s.lower() # " hello world! "
s.upper() # " HELLO WORLD! "
s.replace("H", "J") # " Jello World! "
s.split() # ['Hello', 'World!']
s.find("World") # 6
# String formatting
name = "Alice"
age = 25
# f-strings (Python 3.6+)
print(f"My name is {name} and I'm {age} years old.")
# String methods
text = " Python is awesome! "
print(text.strip())
print(text.lower())
print(text.replace("awesome", "great"))
Python provides functions for creating, reading, updating, and deleting files.
Mode | Description |
---|---|
'r' |
Read (default) |
'w' |
Write (creates new or truncates) |
'a' |
Append |
'x' |
Create (fails if exists) |
'b' |
Binary mode |
't' |
Text mode (default) |
'+' |
Updating (read/write) |
# Open and read
with open("file.txt", "r") as file:
content = file.read()
# Write to file
with open("file.txt", "w") as file:
file.write("Hello World!")
# Read line by line
with open("file.txt") as file:
for line in file:
print(line.strip())
# Write to file
with open("example.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
# Read from file
with open("example.txt", "r") as file:
print("File content:")
print(file.read())
Exceptions are errors that occur during program execution. Python provides ways to handle them gracefully.
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to run if no exception
finally:
# Code that always runs
Exception
- Base class for all exceptionsValueError
- Invalid valueTypeError
- Invalid operationIndexError
- Invalid sequence indexKeyError
- Dictionary key not foundFileNotFoundError
- File doesn't existZeroDivisionError
- Division by zerotry:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("Division successful")
finally:
print("Execution complete")
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
Python supports object-oriented programming with classes and objects.
class ClassName:
# Class attribute
class_attr = value
# Constructor
def __init__(self, param1, param2):
# Instance attributes
self.param1 = param1
self.param2 = param2
# Instance method
def method(self):
# method body
return self.param1
obj = ClassName(arg1, arg2)
class Dog:
# Class attribute
species = "Canis familiaris"
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
# Another instance method
def speak(self, sound):
return f"{self.name} says {sound}"
# Create objects
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
print(buddy.description())
print(miles.speak("Woof Woof"))
class ChildClass(ParentClass):
def __init__(self, param1, param2):
super().__init__(param1) # Call parent constructor
self.param2 = param2
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
# String representation
def __str__(self):
return f"{self.title} by {self.author}"
# Length of book title
def __len__(self):
return len(self.title)
Modules are Python files containing reusable code. Packages are collections of modules.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
# main.py
import mymodule
print(mymodule.greet("Alice"))
print(mymodule.PI)
from math import sqrt, pi
from mymodule import greet
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
math
- Mathematical functionsrandom
- Random number generationdatetime
- Date and time operationsos
- Operating system interfacessys
- System-specific parametersjson
- JSON encoding/decodingre
- Regular expressionsPython provides the datetime
module for working with dates and times.
from datetime import datetime, date, time, timedelta
# Current date and time
now = datetime.now()
# Specific date
d = date(2023, 12, 25)
# Specific time
t = time(14, 30)
# Timedelta (duration)
delta = timedelta(days=7)
# Format as string
now.strftime("%Y-%m-%d %H:%M:%S") # '2023-10-15 14:30:45'
# Parse from string
dt = datetime.strptime("2023-10-15", "%Y-%m-%d")
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
print(f"Current datetime: {now}")
# Formatting
formatted = now.strftime("%A, %B %d, %Y")
print(f"Formatted: {formatted}")
# Date arithmetic
one_week = timedelta(weeks=1)
next_week = now + one_week
print(f"Next week: {next_week}")
Python's json
module allows encoding and decoding JSON data.
import json
# Convert Python object to JSON string
json_str = json.dumps(python_obj)
# Convert JSON string to Python object
python_obj = json.loads(json_str)
# Write JSON to file
with open("data.json", "w") as f:
json.dump(python_obj, f)
# Read JSON from file
with open("data.json") as f:
data = json.load(f)
import json
# Python dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "hiking"]
}
# Convert to JSON
json_data = json.dumps(person, indent=4)
print("JSON String:")
print(json_data)
# Convert back to Python
python_obj = json.loads(json_data)
print("\nPython Object:")
print(python_obj["name"])
with
statements) for resource managementunittest
or pytest
# test_calculator.py
import unittest
from calculator import add
class TestCalculator(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertRaises(TypeError, add, 'a', 5)
if __name__ == '__main__':
unittest.main()
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length: The length of the rectangle in meters
width: The width of the rectangle in meters
Returns:
The area in square meters
Examples:
>>> calculate_area(5, 3)
15.0
"""
return length * width
Congratulations on completing this comprehensive Python programming guide! You've learned the fundamentals of Python including:
To continue your Python journey: