CHEATSHEET
CHEATSHEET
variable_name = value
integer = 42
float_number = 3.14
string = "Hello, World!"
# String
string_variable = "Hello, World!"
multiline_string = """This is a
multiline string."""
# Boolean
boolean_variable = True
# Lists
list_variable = [1, 2, 3, "four", 5.0]
nested_list = [[1, 2, 3], [4, 5, 6]]
# Tuples
tuple_variable = (1, 2, 3, "four", 5.0)
# Sets
set_variable = {1, 2, 3, 3, 4}
# Dictionaries
dict_variable = {"key1": "value1", "key2": 42}
nested_dict = {"person": {"name": "John", "age": 30}}
# None Type
none_variable = None
# Type Conversion
int_from_float = int(3.14)
float_from_int = float(42)
str_from_int = str(42)
# Type Checking
is_integer = isinstance(integer_variable, int)
is_string = isinstance(string_variable, str)
is_list = isinstance(list_variable, list)
# Variable Assignment
x = y = z = 0
# Variable Unpacking
a, b, c = 1, 2, 3
# Dynamic Typing
dynamic_variable = 42
dynamic_variable = "Now I'm a string!"
# Control Flow
if condition:
# code block
elif another_condition:
# code block
else:
# code block
while condition:
# code block
# continue
for i in range(5):
if i == 2:
continue # Skips the rest of the loop body for i=2
print(i)
while condition:
# code block
if some_condition:
continue # Skips the rest of the loop body
# more code
# break
for i in range(5):
if i == 3:
break # Exits the loop when i=3
print(i)
while condition:
# code block
if some_condition:
break # Exits the loop when some_condition is True
# more code
while condition:
# code block
if some_condition:
break
else:
print("While loop completed without encountering a break statement.")
# Functions
def function_name(parameter1, parameter2=default_value):
# code block
return result
# Function Definition
def greet(name):
"""Print a greeting message."""
print(f"Hello, {name}!")
# Function Call
greet("Alice")
# Default Parameters
def greet(name, greeting="Hello"):
"""Print a custom greeting message."""
print(f"{greeting}, {name}!")
# Function Call
greet("Bob")
greet("Charlie", "Hi")
# Return Statement
def add_numbers(a, b):
"""Return the sum of two numbers."""
return a + b
result = add_numbers(3, 4)
print(result)
print_args(1, 2, "three")
# Keyword Arguments
def person_info(name, age, city):
"""Print person information."""
print(f"Name: {name}, Age: {age}, City: {city}")
# Lambda Functions
square = lambda x: x**2
result = square(5)
print(result)
# Docstrings
def example_function(parameter):
"""
This is a docstring.
Parameters:
- parameter: Description of the parameter.
Returns:
Description of the return value.
"""
# Function code
help(example_function)
# Recursive Functions
def factorial(n):
"""Calculate the factorial of a number."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(result)
# Function Annotations
def greet(name: str) -> None:
"""Print a greeting message."""
print(f"Hello, {name}!")
# Function Call
greet("Eve")
# Function Scope
global_variable = 10
def modify_global_variable():
"""Modify a global variable."""
global global_variable
global_variable += 5
modify_global_variable()
print(global_variable)
# Lists
my_list = [1, 2, 3, "four", 5.0]
list_length = len(my_list)
list_append = my_list.append(6)
list_slice = my_list[1:4]
# Dictionaries
my_dict = {"key1": "value1", "key2": 42}
dict_value = my_dict["key1"]
dict_keys = my_dict.keys()
dict_values = my_dict.values()
# Strings
string_length = len("Hello")
string_concatenation = "Hello" + " " + "World"
string_formatting = "Value: {}".format(variable)
# File Handling
with open("filename.txt", "r") as file:
content = file.read()
# or file.write(data)
# Exception Handling
try:
# code block
except SomeException as e:
# handle exception
def method(self):
# code block
# Input/Output
print("Hello, World!")
input_value = input("Enter something: ")
# Math
abs_value = abs(-5)
max_value = max(1, 2, 3)
min_value = min(1, 2, 3)
round_value = round(3.14159, 2)
# List/Dictionary Manipulation
len_list = len([1, 2, 3])
len_dict = len({"a": 1, "b": 2})
sorted_list = sorted([3, 1, 2])
# File Handling
with open("filename.txt", "r") as file:
lines = file.readlines()
# Handling Exceptions
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"An error occurred: {e}")
# Miscellaneous
range_values = range(5) # creates a range from 0 to 4
sum_values = sum([1, 2, 3])
# Escape Characters
escaped_string = "This is a string with escape characters: \nNew Line, \tTab, \\
Backslash, \"Double Quote, \'Single Quote"
# Case Transformation
orig_str = "hello, world!"
capitalized_string = orig_str.capitalize()
casefolded_string = orig_str.casefold()
uppercased_string = orig_str.upper()
lowercased_string = orig_str.lower()
titlecased_string = orig_str.title()
# String Formatting:
formatted_string = "The value is {}".format(value)
formatted_string_with_placeholder = "Value: {:.2f}".format(float_value)
# Searching and Counting
index_of_substring = orig_str.find("lo")
count_of_substring = orig_str.count("o")
ends_with_check = orig_str.endswith("ld")
starts_with_check = orig_str.startswith("he")
# Character Testing
is_alphanumeric = orig_str.isalnum()
is_alpha = orig_str.isalpha()
is_numeric = orig_str.isnumeric()
is_decimal = orig_str.isdecimal()
is_digit = orig_str.isdigit()
is_identifier = orig_str.isidentifier()
is_lower = orig_str.islower()
is_upper = orig_str.isupper()
is_title = orig_str.istitle()
OUTPUT: 45
list1 = [2, 4, 6, 8]
total = 0
while list1:
total += list1[0]
list1 = list1[1:]
print(total)
OUTPUT: 20
oceans = ["Atlantic", "Pacific", list1 = ['a', 'b', 'c', 'd']
"Indian", "Arctic", "Antarctic"] i = 0
i = len(oceans) - 1 while True:
while i >= 0: print(list1[i]*i)
if len(oceans[i]) < 7: i = i + 1
del oceans[i] if i == len(list1):
i = i-1 break
print(", ".join(oceans)) OUTPUT:
numTries = 0
year = 0
while (numTries < 7) and (year != 1964):
numTries += 1
year = int(input("Try #" + str(numTries) + ": In what year " + "did the
Beatles invade the U.S.? "))
if year == 1964:
print("\nYes. They performed on the Ed Sullivan show in 1964.")
print("You answered correctly in " + str(numTries) + " tries.")
elif year < 1964:
print("Later than", year)
else: # year > 1964
print("Earlier than", year)
if (numTries == 7) and (year != 1964):
print("\nYour 7 tries are up. The answer is 1964.")
OUTPUT:
Try #1: In what year did the Beatles invade the U.S.? 1950
Later than 1950
Try #2: In what year did the Beatles invade the U.S.? 1970
Earlier than 1970
Try #3: In what year did the Beatles invade the U.S.? 1964
Output:
sum = 0 L = [2, 4, 6, 8]
total = 0
for _ in range(3):
num = int(input("Enter a number: ")) for num in L:
sum += num total += num
print(sum) print(total)
Output: Output: 20
Enter a number: 8
Enter a number: 3
Enter a number: 17
28
print("Celsius Fahrenheit")
for c in range(10, 31, 5):
f = (9/5) * c + 32
print(f"{c:2}{'':12}{f:.2f}")
Output:
total_distance = 0
height = initial_height
bounces = 0
Output:
Enter coefficient of restitution: .7
Enter initial height in meters: 8
Number of bounces: 13
Meters traveled: 44.89
m = int(input("Enter the first positive integer (m): "))
n = int(input("Enter the second positive integer (n): "))
if m < n:
m, n = n, m
while n != 0:
t = n
n = m % n
m = t
Output:
Enter the first positive integer (m): 30
Enter the second positive integer (n): 35
The GCD is: 5
n = int(input("Enter a positive integer (>1): ")) year = 1980
year2 = 2025
f = 2 age = int(year2) - int(year)
print(f"Person will be {age}
print("Prime factors are:", end=' ') in the year {present}")
while n > 1:
if n % f == 0: Output: Person will be 45 in
print(f, end=' ') the year 2025
n = n // f
else:
f += 1
print()
Output:
Enter a positive integer (>1): 2345
Prime factors are: 5 7 67
initial_population = 7
growth_rate = 0.011
target_population = 8
years_to_reach_target = 0
current_population = initial_population
Output:
World population will be 8 billion in the year 2024.
initial_quantity = 100
half_life = 28
threshold_quantity = 1
current_quantity = initial_quantity
time = 0
current_cpi = initial_cpi
years = 0
balance = loan_amount
months = 0
balance = 0
months = 0
balance = initial_deposit
months = 0
quantity = initial_quantity
years = 0
n = 1
probability_no_shared_birthday = (364 / 365) ** n
print(f"With {n} students, the probability is greater than 50% that someone has
the same birthday as you.")
Output: With 253 students, the probability is greater than 50% that someone has
the same birthday as you.
initial_deposit = int(input("Enter amount of deposit: "))
annual_interest_rate = 0.036
monthly_interest_rate = annual_interest_rate / 12
monthly_withdrawal = 600
target_balance = 600
balance = initial_deposit
months = 0
Output:
Enter amount of deposit: 10000
Balance will be $73.91 after 17 months.
china_population_2014 = 1.37e9
china_growth_rate = 0.0051
india_population_2014 = 1.26e9
india_growth_rate = 0.0135
t = 0
Output: India's population will exceed China's population in the year 2025.
initial_temperature = 212
room_temperature = 70
cooling_constant = 0.079
target_temperature = 150
while True:
print("\nOptions:")
print("1. Make a Deposit")
print("2. Make a Withdrawal")
print("3. Obtain Balance")
print("4. Quit")
if choice == "1":
deposit_amount = float(input("Enter amount of deposit: $"))
account_balance += deposit_amount
print("Deposit Processed.")
elif choice == "2":
withdrawal_amount = float(input("Enter amount of withdrawal: $"))
max_withdrawal = 1500
if withdrawal_amount > max_withdrawal:
print(f"Denied. Maximum withdrawal is ${max_withdrawal:.2f}")
else:
account_balance -= withdrawal_amount
print("Withdrawal Processed.")
elif choice == "3":
print(f"Balance: ${account_balance:.2f}")
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid selection. Please choose a number between 1 and 4.")
TYPES OF EXCEPTIONS:
SyntaxError:
Function: Raised when there is a syntax error in the code.
Example: Missing a colon after an if statement.
IndentationError:
Function: Raised when there is an incorrect indentation.
Example: Inconsistent indentation within the same block.
NameError:
Function: Raised when a local or global name is not found.
Example: Using a variable before it is defined.
TypeError:
Function: Raised when an operation or function is applied to an object of an
inappropriate type.
Example: Trying to concatenate a string and an integer without conversion.
ValueError:
Function: Raised when a built-in operation or function receives an argument with
the correct type but an inappropriate value.
Example: Converting a string to an integer where the string does not represent a
valid integer.
IndexError:
KeyError:
Function: Raised when a dictionary key is not found.
Example: Trying to access a non-existent key in a dictionary.
FileNotFoundError:
Function: Raised when a file or directory is requested but cannot be found.
Example: Trying to open a file that doesn't exist.
ZeroDivisionError:
Function: Raised when the second operand of a division or modulo operation is
zero.
Example: Attempting to divide a number by zero.
AttributeError:
Function: Raised when an attribute reference or assignment fails.
Example: Accessing an attribute that doesn't exist on an object.
ImportError:
Function: Raised when an import statement fails to find the module definition or
when a from ... import statement fails to find a name that is to be imported.
Example: Trying to import a module that doesn't exist.
while True:
print("Metric Conversion:")
print("\tSelection:")
print("\t\ta. mm <-> cm")
print("\t\tb. cm <-> inch")
print("\t\tc. inch <-> ft")
print("\t\td. ft <-> yard")
print("\t\te. exit")
if choice == 'a':
print(f"\nYour choice is {choice}")
print("\tChoose to convert:")
print("\t\t1. mm -> cm")
print("\t\t2. cm -> mm")
choice2 = input("\t\tSelect choice: ")
if choice2 == '1':
while True:
try:
num = float(input("\t\tEnter a number to convert: "))
res = num / 10
print(f"\t\tmm to cm conversion is {num:.2f}mm =
{res:.2f}cm")
break
except ValueError:
print("Invalid input. Please enter a number.")
elif choice2 == '2':
while True:
try:
num = float(input("\t\tEnter a number to convert: "))
res = num * 10
print(f"\t\tcm to mm conversion is {num:.2f}cm =
{res:.2f}mm")
break
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("You have entered an invalid value.\n")
continue