Python Basics Cheat Sheet
Hello World:
print("Hello, World!")
Variables and Data Types:
# Declaring variables
age = 25
pi = 3.14159
name = "John Smith"
# Initializing variables
count = 0
isTrue = True
Operators:
# Arithmetic operators
sum = 5 + 3
difference = 10 - 4
division = 15 / 2
remainder = 15 % 2
product = 4 * 6
# Relational operators
isEqual = (5 == 5)
isGreater = (10 > 5)
isLessThanOrEqual = (15 <= 20)
# Logical operators
logicalAnd = True and False
logicalOr = True or False
logicalNot = not True
Conditional Statements:
# If statement
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
# Elif statement
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if all conditions are false
Loops:
# While loop
while condition:
# Code to execute while the condition is true
# For loop
for item in iterable:
# Code to execute repeatedly for each item in the iterable
# Range function with for loop
for i in range(start, stop, step):
# Code to execute repeatedly with the range of values
Lists:
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Accessing list elements
firstElement = numbers[0]
# Modifying list elements
numbers[0] = 10
# List length
length = len(numbers)
# Adding elements to a list
numbers.append(6)
# Removing elements from a list
numbers.remove(4)
Functions:
# Function definition
def function_name(parameters):
# Code to execute
# Function with return value
def multiply(a, b):
result = a * b
return result
# Function call
function_name(arguments)
Classes and Objects:
# Class definition
class MyClass:
def __init__(self, my_variable):
self.my_variable = my_variable
def my_method(self):
# Code to execute
# Creating an object
my_object = MyClass(10)
# Accessing object attributes
my_variable_value = my_object.my_variable
# Calling object methods
my_object.my_method()