Python Programming Introduction & Installation
Cheatsheet by CodeWithHarry
Installation
WEB
Go to [Link]/downloads and install the latest version
Check Python Version Run Python
python --version python [Link]
python3 --version
py --version
Basic Hello World Syntax
PYTHON FILE
print("Hello, World!")
Python Programming Variables & Data Types
Cheatsheet by CodeWithHarry
Variables
STRING INTEGER FLOAT
name = "Harry" age = 25 price = 99.99
BOOLEAN MULTIPLE SAME VALUE
is_active = True x, y = 10, 20 a = b = c = 0
Data Types
TEXT NUMBER SEQUENCE
str int, float, complex list, tuple, range
MAPPING SET BOOLEAN
dict set, frozenset bool
Type Checking
PYTHON
x = 5
print(type(x))
print(isinstance(x, int))
Constant Naming Convention
Constant names are typically written in uppercase letters. This is a convention, not enforced!
PI = 3.14 MAX_SIZE = 100
Python Programming Operators & Type Conversion
Cheatsheet by CodeWithHarry
Operators
ARITHMETIC ASSIGNMENT COMPARISON LOGICAL
+, -, *, /, %, =, +=, -=, *=, ==, !=, >, <, >=, and, or, not
//, ** /=, %= <=
MEMBERSHIP IDENTITY
in, not in is, is not
Operator Precedence
1. PARENTHESES 2. POWER 3. MULTIPLY 4. ADD
() first ** *, /, //, % +, -
5. COMPARE 6. NOT 7. AND 8. OR
==, !=, <, >, in, not and or
is
Operator Syntax
ADD FLOOR DIV POWER EQUAL
x + y x // y x ** y x == y
LOGIC MEMBER IDENTITY
x > 10 and x < 20 "a" in "harry" x is None
Type Conversion
INTEGER (immutable) FLOAT (immutable) STRING (immutable)
int("10") float("10.5") str(100)
BOOLEAN (immutable) LIST (mutable) TUPLE (immutable)
bool(0) is False; list("abc") tuple([1, 2])
bool("False") is True
Python Programming Strings
Cheatsheet by CodeWithHarry
Create Strings
SINGLE DOUBLE MULTILINE RAW
s = 'hello' s = "hello" s = '''hello''' r"C:\new\file"
Indexing & Slicing
Assume s = "Harry"
FIRST LAST SLICE STEP
s[0] -> "H" s[-1] -> "y" s[1:4] -> "arr" s[::2] -> "Hry"
REVERSE LENGTH
s[::-1] -> "yrraH" len(s) -> 5
String Methods
Assume s = "Harry"
UPPER LOWER SPACES REPLACE
[Link]() -> [Link]() -> [Link]() -> [Link]("a",
"HARRY" "harry" "Harry" "o") -> "Horry"
SPLIT JOIN FIND
[Link]("r") -> "-".join(s) -> [Link]("r") -> 2
["Ha", "", "y"] "H-a-r-r-y"
Formatting
PYTHON
name = "Harry"
age = 25
print(f"{name} is {age}")
Python Programming Lists
Cheatsheet by CodeWithHarry
List Syntax
CREATE MIXED EMPTY LIST
lst = [1, 2, 3] lst = [1, "a", True] lst = []
LENGTH
len(lst)
Access & Slice
FIRST/LAST RANGE REVERSE
lst[0] / lst[-1] lst[1:4] lst[::-1]
List Methods
ADD ONE ADD MANY INSERT
[Link](x) adds one [Link](items) [Link](i, x)
element
REMOVE POP CLEAR
[Link](x) removes [Link]() [Link]()
first match
SORT REVERSE
[Link]() [Link]()
Comprehension
PYTHON
squares = [x*x for x in range(5)]
evens = [x for x in nums if x % 2 == 0]
Python Programming Tuples, Sets & Dictionaries
Cheatsheet by CodeWithHarry
Tuples
CREATE ONE ITEM ACCESS
t = (1, 2, 3) t = (1,) t[0], t[-1]
UNPACK
a, b = (1, 2)
Sets
CREATE EMPTY SET ADD
s = {1, 2, 3} s = set() [Link](4)
REMOVE UNION INTERSECTION
[Link](2) # error if a | b a & b
not present
[Link](2) # safer
Dictionaries
CREATE ACCESS GET
d = {"name": "Harry"} d["name"] [Link]("age")
UPDATE KEYS ITEMS
d["age"] = 25 [Link]() [Link]()
Python Programming Conditional Statements
Cheatsheet by CodeWithHarry
if / elif / else
PYTHON
if condition:
statement
elif another_condition:
statement
else:
statement
Comparisons
EQUAL/ NOT EQUAL GREATER/LESS GTE/LTE
x == y x > y x >= y
x != y x < y x <= y
Logical Conditions
AND/OR NOT TERNARY
x > 0 and x < 10 not is_active a if condition else b
x == 0 or x == 1
Match Case
PYTHON 3.10+
match value:
case 1:
print("one")
case _:
print("other")
Python Programming Loops
Cheatsheet by CodeWithHarry
for Loop
PSEUDO CODE PYTHON
for item in iterable: for i in range(5):
statement print(i)
while Loop
PSEUDO CODE PYTHON
while condition: i = 0
statement while i < 5:
i += 1
Loop Tools
RANGE BREAK CONTINUE
range(start, stop, step) break continue
PASS ENUMERATE ZIP
pass enumerate(items) zip(a, b)
Loop else
PYTHON
for x in nums:
if x == target:
break
else:
print("not found")
Python Programming Functions
Cheatsheet by CodeWithHarry
Function Syntax
PYTHON
def function_name(parameters):
return value
result = function_name(arguments)
Parameters
NORMAL DEFAULT KEYWORD
def add(a, b): def greet(name="User"): greet(name="Harry")
ARGS KWARGS ANNOTATION
def f(*args): def f(**kwargs): def add(a: int) -> int:
Lambda
PYTHON
square = lambda x: x * x
print(square(5))
Scope
LOCAL GLOBAL
x inside function global x
Python Programming Exception Handling
Cheatsheet by CodeWithHarry
try / except Full Block
PYTHON PYTHON
try: try:
risky_code() code
except Exception as e: except ValueError as e:
print(e) print(e)
else:
print("no error")
finally:
print("always runs")
Common Exceptions
VALUE TYPE INDEX
ValueError TypeError IndexError
KEY FILE ZERO DIV
KeyError FileNotFoundError ZeroDivisionError
Raise
PYTHON
if age < 0:
raise ValueError("Invalid age")
Python Programming File Handling
Cheatsheet by CodeWithHarry
Open File
READ WRITE APPEND
open("[Link]", "r") open("[Link]", "w") open("[Link]", "a")
BINARY
open("[Link]", "rb")
with Syntax
PYTHON
with open("[Link]", "r") as f:
content = [Link]()
Read / Write
READ ALL READ LINE READ LINES
[Link]() [Link]() [Link]()
WRITE
[Link]("hello")
Python Programming Object Oriented Programming
Cheatsheet by CodeWithHarry
Class Syntax
PYTHON
class Person:
def __init__(self, name):
[Link] = name
def greet(self):
print([Link])
Object Syntax
CREATE ATTRIBUTE METHOD
p = Person("Harry") [Link] [Link]()
Inheritance
PYTHON
class Student(Person):
def __init__(self, name, marks):
super().__init__(name)
[Link] = marks
Special Methods
INIT STR LEN
__init__(self) __str__(self) __len__(self)
REPR
__repr__(self)
Python Programming Modules & pip
Cheatsheet by CodeWithHarry
Import Syntax
MODULE ALIAS FROM ALL
import math import numpy as from math import from module
np sqrt import *
Module Usage
PYTHON
import math
print([Link](16))
from random import randint
print(randint(1, 10))
pip Commands
INSTALL UNINSTALL LIST
pip install package pip uninstall package pip list
FREEZE UPGRADE REQUIREMENTS
pip freeze pip install -U package pip install -r
[Link]
Virtual Environment
TERMINAL
python -m venv .venv
.venv\Scripts\activate
source .venv/bin/activate
Python Programming Useful Built-in Functions
Cheatsheet by CodeWithHarry
Data Functions
TYPE LENGTH INPUT
type(x) len(x) input("Name: ")
OUTPUT CONVERT BOOLEAN
print(x) int(), float(), str() bool(x)
Math Functions
SUM MIN MAX
sum(nums) min(nums) max(nums)
ROUND ABS POWER
round(x, 2) abs(x) pow(x, y)
Iterable Functions
RANGE ENUMERATE ZIP
range(5) enumerate(items) zip(a, b)
SORTED ANY ALL
sorted(items) any(values) all(values)
Examples
PYTHON
nums = [3, 1, 2]
print(len(nums))
print(sorted(nums))
print(sum(nums))
Python Programming Useful Built-in Functions
Cheatsheet by CodeWithHarry
USEFUL BUILT-IN FUNCTIONS
Python provides many built-in functions for common tasks.
print() len() type()
Display output Get length Get type
range() sum() min()/max()
Generate sequence Sum items Find min/max
sorted() enumerate() zip()
Sort items Index with items Combine iterables
map() filter() any()/all()
Apply function Filter items Test conditions
nums = [1, 2, 3]
print(sum(nums))
print(list(enumerate(nums)))
print(list(map(str, nums)))