What is Python?
Python is a high-level, interpreted, and general-purpose programming language designed for readability and simplicity. Created by Guido van Rossum in 1991, it emphasizes code clarity and uses English-like syntax. Unlike compiled languages (like C++), Python code is executed line-by-line by an interpreter, making it ideal for rapid development and prototyping.
When you run a Python script:
# Script to automate file renaming
import os
for filename in os.listdir("."):
if filename.endswith(".txt"):
os.rename(filename, filename.replace("old_", "new_"))
# Simple web server (one line!) python -m http.server 8000
# Data analysis with pandas (requires pip install pandas)
import pandas as pd
data = pd.read_csv("sales.csv")
print(data.head())
x = 5, and Python infers x is an integer.import this), emphasizing clarity and simplicity.To begin programming in Python, you need to install the Python interpreter and choose a suitable development environment.
python from the command line.python --version
If you see Python 3.12.x, youβre good!
'python' is not recognized', Python wasn't added to PATH. Reinstall and check the box!
Python projects often depend on different versions of libraries. To avoid conflicts, use virtual environments:
# Create a virtual environment python -m venv myproject_env # Activate it (Windows) myproject_env\Scripts\activate # Activate it (macOS/Linux) source myproject_env/bin/activate # Now install packages safely pip install requests
Deactivate with: deactivate
| Tool | Pros | Cons |
|---|---|---|
| VS Code | Free, lightweight, excellent Python extension, IntelliSense, debugger, Jupyter support | Requires setup (extensions) |
| PyCharm Community | Full IDE features: refactoring, testing, database tools, built-in terminal | Heavy on RAM, slower startup |
| Jupyter Notebook | Perfect for data science, visualizations, step-by-step execution | Not ideal for large applications or scripting |
| IDLE | Built-in, no setup needed | Minimal features, outdated UI |
Interactive Mode: Type python in terminal β you enter REPL (Read-Eval-Print Loop):
>>> print("Hello!")
Hello!
>>> 2 + 3
5
>>> exit()
Script Mode: Save code in a file (e.g., hello.py):
name = input("Enter your name: ")
print(f"Welcome, {name}!")
# Run in terminal:
python hello.py
python -i script.py to run script AND stay in interactive mode afterward.
Create a file called calculator.py:
# calculator.py
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Sum: {num1 + num2}")
print(f"Product: {num1 * num2}")
Run it:
python calculator.py Enter first number: 5.5 Enter second number: 3 Sum: 8.5 Product: 16.5
venv\Scripts\activate. Always use source on Unix systems.python -m venv myenv do?-m flag runs a module as a script. venv is a standard library module for creating virtual environments.python script.py and double-clicking the file in Windows Explorer?input("Press Enter to exit...") at the end of your script.Pythonβs syntax is intentionally minimalistic and readable. Unlike C, Java, or JavaScript, Python uses indentation instead of braces to define code blocks.
Python uses whitespace (spaces or tabs) to indicate blocks. This enforces clean, readable code.
if x > 10:
print("x is greater than 10")
y = x * 2
print(y)
print("This runs regardless")
if x > 10:
print("x is greater than 10") # β IndentationError: expected an indented block
Single-line comments start with #:
# This is a comment x = 5 # This comment explains the variable
Multi-line strings are often used as docstrings (documentation) for functions, classes, or modules:
""" This is a multi-line string used as a docstring. It does not cause an error, but it's ignored unless assigned. """
Long lines can be broken using:
\(), brackets [], or braces {} (preferred)# Explicit (avoid if possible)
total = 1 + 2 + 3 + \
4 + 5 + 6
# Implicit (recommended)
total = (1 + 2 + 3 +
4 + 5 + 6)
# Also works with lists
fruits = [
"apple",
"banana",
"cherry"
]
Optional in Python. You can write multiple statements on one line using semicolons:
x = 5; y = 10; z = x + y print(z) # Output: 15
These words have special meaning and cannot be used as variable names:
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
class = 5 β SyntaxError!
Python is case-sensitive:
name = "Alice" Name = "Bob" NAME = "Charlie" print(name) # Alice print(Name) # Bob print(NAME) # Charlie
Spaces around operators improve readability:
# Good result = a + b if x > 5: # Avoid (but valid) result=a+b if x>5:
# Function definition with proper structure
def calculate_area(length, width):
"""Calculate area of rectangle."""
area = length * width
return area
# Call function
area = calculate_area(10, 5)
print(f"Area: {area}")
# Conditional logic
if area > 50:
print("Large room")
elif area >= 20:
print("Medium room")
else:
print("Small room")
if x > 5:
print("x is big")
IndentationError β Python expects an indented block after if.class = 10
class, def, return) cannot be used as identifiers.a = 10 A = 20 print(a + A)
a and A are two different variables: 10 + 20 = 30.In Python, variables are labels that point to objects in memory. You donβt declare types β Python infers them dynamically.
x = 5 # x is int x = "hello" # Now x is str x = [1, 2, 3] # Now x is list x = None # Now x is NoneType
| Type | Example | Description |
|---|---|---|
int |
42, -7, 0 |
Integers β unlimited precision |
float |
3.14, -0.001, 2.0 |
Floating-point numbers (double precision) |
str |
"Hello", 'Python', '''multi-line''' |
Immutable sequences of Unicode characters |
bool |
True, False |
Boolean values β used in logic |
None |
value = None |
Represents absence of value β equivalent to null in other languages |
print(type(42)) #print(type("Hi")) # print(type(3.14)) # print(type(True)) # print(type(None)) #
valid_name β _my_var β name123 β 123name β (starts with digit) class β (keyword) first-name β (hyphen not allowed)
num_str = "123"
num_int = int(num_str) # β 123
num_float = float(num_str) # β 123.0
text = str(456) # β "456"
boolean = bool(0) # β False
boolean = bool(1) # β True
boolean = bool("") # β False (empty string)
boolean = bool(" ") # β True (non-empty)
int("abc") β ValueError: invalid literal for int() with base 10
a = 10 b = a # b points to same object as a print(id(a)) # Same memory address as id(b) print(id(b)) a = 20 # Now a points to new object print(b) # Still 10 β b unchanged
# Simultaneous assignment x, y, z = 1, 2, 3 print(x, y, z) # 1 2 3 # Swapping values a, b = 5, 10 a, b = b, a print(a, b) # 10 5
# Student grade tracker
name = "Maria"
age = 19
gpa = 3.8
is_enrolled = True
graduation_year = None
print(f"Student: {name}, Age: {age}, GPA: {gpa}")
print(f"Enrolled: {is_enrolled}, Grad Year: {graduation_year}")
# Convert user input
user_input = input("Enter your age: ")
age_as_int = int(user_input) # Converts string to integer
print(f"You will be {age_as_int + 1} next year.")
x = "5" y = 3 print(x + y)
int(x) + y or x + str(y).NoneType?None has type NoneType. All others are strings, integers, booleans.bool("0") evaluate to?"" is falsy.a = 10 b = a a = 20 print(b)
b = a, b references the same object (10). When you change a to 20, a points to a new object β b remains unchanged.second_place, place_2.Operators perform operations on variables and values. Python supports arithmetic, comparison, logical, assignment, identity, and membership operators.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 4 |
6 |
* |
Multiplication | 7 * 2 |
14 |
/ |
Division | 15 / 3 |
5.0 |
// |
Floor Division | 15 // 2 |
7 |
% |
Modulus | 17 % 5 |
2 |
** |
Exponentiation | 2 ** 3 |
8 |
Python follows PEMDAS:
()**+x, -x* / // %+ -result = 2 + 3 * 4 ** 2 # Step-by-step: 4**2 = 16 β 3*16 = 48 β 2+48 = 50 print(result) # 50
== Equal != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal
x = 5 y = 10 print(x == y) # False print(x != y) # True print(x < y) # True
and | Returns True if both operands are true |
or | Returns True if at least one operand is true |
not | Negates the boolean value |
age = 18 has_license = True print(age >= 18 and has_license) # True print(age < 18 or has_license) # True print(not has_license) # False
x = 10 x += 5 # x = x + 5 β 15 x -= 3 # x = x - 3 β 12 x *= 2 # x = x * 2 β 24 x /= 4 # x = x / 4 β 6.0 x //= 2 # x = x // 2 β 3.0 x %= 2 # x = x % 2 β 1.0
Check if two variables refer to the same object in memory.
a = [1, 2] b = a c = [1, 2] print(a is b) # True β same object print(a is c) # False β different objects, even though content is same print(a == c) # True β content equality
is only to compare with None: if value is None:
Check if a value exists in a sequence (list, string, tuple, etc.)
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
text = "Hello World"
print("World" in text) # True
print("w" in text) # False (case-sensitive)
# Calculate BMI
weight_kg = 70
height_m = 1.75
bmi = weight_kg / (height_m ** 2)
print(f"BMI: {bmi:.2f}")
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
print(f"Category: {category}")
# Check eligibility
is_adult = age >= 18
has_id = True
can_vote = is_adult and has_id
print(f"Can vote: {can_vote}")
10 // 3?// returns the largest integer less than or equal to the result: 10 Γ· 3 = 3.33 β floor is 3.5 == "5" evaluate to?5 is an integer, and "5" is a string. Python does not auto-convert types for ==.x = 3 y = 2 z = x ** y + 1 print(z)
3 ** 2 = 9, then 9 + 1 = 10? Wait β correction: 3Β² = 9, +1 = 10? Let me recalculate...3 ** 2 = 9, then 9 + 1 = 10.not (True and False)?True and False β False β not False β True.True?==), but not the same object (is). String literals may be interned, so A might be True, but it's implementation-dependent. B is reliably True.Input/output (I/O) allows interaction between your program and the user or external data sources.
print() FunctionThe print() function outputs text to the console.
print("Hello, World!") # Basic
print("Age:", 25) # Multiple args β space separated
print("Name:", name, "Score:", score, sep="-") # Custom separator
print("First", end=" ") # No newline
print("Second") # Output: "First Second"
# F-strings (formatted strings) β MOST COMMON IN MODERN PYTHON
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
print(f"Pi β {3.14159:.2f}") # Format to 2 decimals
print(f"{1000:,}") # Comma separator β 1,000
input() FunctionAlways returns a string. You must convert manually.
name = input("Enter your name: ") # Returns string
age_str = input("Enter your age: ")
age = int(age_str) # Convert to integer
# One-liner version
age = int(input("Enter your age: "))
# β Wrong
num1 = input("Number 1: ") # "5"
num2 = input("Number 2: ") # "3"
print(num1 + num2) # Output: "53" β string concatenation!
# β
Correct
num1 = float(input("Number 1: "))
num2 = float(input("Number 2: "))
print(num1 + num2) # Output: 8.0
# .format()
print("Hello {}, you are {} years old.".format(name, age))
# %-formatting (old style β avoid in new code)
print("Hello %s, you are %d years old." % (name, age))
# calculator.py
print("=== Simple Calculator ===")
num1 = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
if num2 == 0:
print("Error: Cannot divide by zero!")
exit()
result = num1 / num2
else:
print("Invalid operator!")
exit()
print(f"Result: {result}")
# Read a text file
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Write to a file
with open("output.txt", "w") as f:
f.write("Hello from Python!\n")
f.write("This is line 2.\n")
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("β Please enter a valid integer.")
print(f"You entered: {age}")
try-except to handle conversion errors gracefully.
print("Hello", "World", sep="---")
sep parameter defines the separator between arguments. Default is space.input()?input() always returns a string.x = 5
y = 10
print(f"The sum of {x} and {y} is {x+y}.")
{x+y} becomes 15.number = input("Enter a number: ")
print(number * 3)
And user enters: 4
input() returns a string, multiplying a string by 3 repeats it: "4" * 3 = "444".ValueError when converting strings to numbers to prevent crashes.