0% found this document useful (0 votes)
41 views23 pages

CHEATSHEET

The document defines various Python programming concepts including variables, data types, strings, lists, dictionaries, functions, classes, modules, file handling, exception handling and more. Key points covered include defining variables and assigning values, built-in data types, string formatting and manipulation methods, list/dictionary indexing and slicing, conditionals and loops, defining and calling functions, handling exceptions, opening and reading/writing files, and defining classes and objects.

Uploaded by

Nehemiah Garcia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views23 pages

CHEATSHEET

The document defines various Python programming concepts including variables, data types, strings, lists, dictionaries, functions, classes, modules, file handling, exception handling and more. Key points covered include defining variables and assigning values, built-in data types, string formatting and manipulation methods, list/dictionary indexing and slicing, conditionals and loops, defining and calling functions, handling exceptions, opening and reading/writing files, and defining classes and objects.

Uploaded by

Nehemiah Garcia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

# Variables and Data Types

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

for item in iterable:


# 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

# break with else


for i in range(5):
print(i)
if i == 2:
break
else:
print("Loop completed without encountering a break statement.")

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)

# Variable Number of Arguments


def print_args(*args):
"""Print variable number of arguments."""
for arg in args:
print(arg)

print_args(1, 2, "three")

# Keyword Arguments
def person_info(name, age, city):
"""Print person information."""
print(f"Name: {name}, Age: {age}, City: {city}")

person_info(age=25, name="Alice", city="Wonderland")

# 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

# Classes and Objects


class MyClass:
def __init__(self, parameter):
self.attribute = parameter

def method(self):
# code block

# Modules and Packages


import module_name
from module_name import function_name

# 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()

# Open file in read mode


with open("filename.txt", "r") as file:
content = file.read()

# Open file in write mode (creates if not exists, truncates if exists)


with open("new_file.txt", "w") as file:
file.write("Hello, World!")

# Open file in append mode (creates if not exists, appends if exists)


with open("existing_file.txt", "a") as file:
file.write("New content\n")

# Open file in binary mode


with open("binary_file.bin", "rb") as file:
binary_data = file.read()

# Read the entire content


with open("filename.txt", "r") as file:
content = file.read()
# Read line by line
with open("filename.txt", "r") as file:
for line in file:
print(line.strip()) # strip removes leading/trailing whitespaces

# Read all lines into a list


with open("filename.txt", "r") as file:
lines = file.readlines()

# Write a single line to a file


with open("new_file.txt", "w") as file:
file.write("Hello, World!\n")

# Write multiple lines to a file


with open("new_file.txt", "w") as file:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
# Seek to a specific position in the file
with open("filename.txt", "r") as file:
file.seek(5) # Move the cursor to the 6th character
content = file.read()

# Get the current position of the cursor


with open("filename.txt", "r") as file:
position = file.tell()
print(f"Current position: {position}")

# 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"

# Raw Strings (ignores escape characters)


raw_string = r"This is a raw string with \n no escape characters."

# 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")

# Manipulation and Replacement


centered_string = orig_str.center(20, "*")
padded_string = orig_str.ljust(20, "-")
rjust_string = orig_str.rjust(20, "*")
padded_right_string = orig_str.zfill(20)

# 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()

# Other String Methods


stripped_string = orig_str.strip()
lstripped_string = orig_str.lstrip()
rstripped_string = orig_str.rstrip()

replaced_string = orig_str.replace("l", "L")


partitioned_string = orig_str.partition(",")
splitted_list = orig_str.split(",")
initial_val = 10 while True:
while initial_val > 0: answer = input("Enter the password: ")
if initial_val == 5: if answer.upper() == "SHAZAM":
break break
print(initial_val) print("You may continue.")
initial_val -= 1
letters = ['P', 'y', 't', 'h', 'o', 'n'] num = 5
language = "" while True:
num = 2 * num
for letter in letters: if num % 4 == 0:
language += letter break
print(num)
print(language)
OUTPUT: 20
num = 3 total = 0 total = 0
while num < 15: num = 1 num = 1
num += 5 while True: while num < 5:
print(num) total += num total += num
num += 1 num += 1
OUTPUT: 18 if num == 10: print(total)
break
print(total) OUTPUT: 10

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:

OUTPUT: Atlantic, Pacific, Antarctic

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

Yes. They performed on the Ed Sullivan show in 1964.


You answered correctly in 3 tries.
q = 1 ## Display the numbers from 1 through
while q != 0: 5.
q = q-2
print(q) num = 0
while True:
#output will never be 0, it will num += 1
continue printing. print(num)
if num == 5:
break
list1 = ['H', 'e', 'l', 'l', 'o'] list1 = ['a', 'b', 'c', 'd']
i = 0 i = 0
while i < len(list1): while True:
print(list1[i]) print(list1[i])
i += 1 if i == len(list1) - 1:
break
Output: i += 1

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:

coeff_of_restitution = float(input("Enter coefficient of restitution: "))


initial_height = float(input("Enter initial height in meters: "))

total_distance = 0
height = initial_height
bounces = 0

while height >= 0.1:


total_distance += height
height *= coeff_of_restitution
total_distance += height
bounces += 1

print(f"Number of bounces: {bounces}")


print(f"Meters traveled: {total_distance:.2f}")

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

print("The GCD is:", m)

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

while current_population < target_population:


current_population *= (1 + growth_rate)
years_to_reach_target += 1

print(f"World population will be {target_population} billion in the year {2011 +


years_to_reach_target}.")

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

while current_quantity >= threshold_quantity:


current_quantity *= 0.5
time += half_life

# Output the result


print(f"The decay time is {time} years.")

Output: The decay time is 196 years.


initial_cpi = 238.25
growth_rate = 0.025
target_cpi = initial_cpi * 2

current_cpi = initial_cpi
years = 0

while current_cpi < target_cpi:


current_cpi *= 1 + growth_rate
years += 1

print(f"Consumer prices will double in {years} years.")

Output: Consumer prices will double in 29 years.


loan_amount = 15000
annual_interest_rate = 0.06
monthly_interest_rate = annual_interest_rate / 12
monthly_payment = 290.00

balance = loan_amount
months = 0

while balance >= loan_amount / 2:


balance = (1 + monthly_interest_rate) * (balance - monthly_payment)
months += 1

print(f"Loan will be half paid off after {months} months.")


Output: Loan will be half paid off after 33 months.
monthly_deposit = 100
annual_interest_rate = 0.03
monthly_interest_rate = annual_interest_rate / 12
target_balance = 3000

balance = 0
months = 0

while balance <= target_balance:


balance = (1 + monthly_interest_rate) * balance + monthly_deposit
months += 1

print(f"Annuity will be worth more than ${target_balance} after {months}


months.")

Output: Annuity will be worth more than $3000 after 29 months.


initial_deposit = 10000
annual_interest_rate = 0.036
monthly_interest_rate = annual_interest_rate / 12
monthly_withdrawal = 600
target_balance = 600

balance = initial_deposit
months = 0

while balance >= target_balance:


balance = (1 + monthly_interest_rate) * balance - monthly_withdrawal
months += 1

print(f"Balance will be ${balance:.2f} after {months} months.")

Output: Balance will be $73.91 after 17 months.


initial_quantity = 1
decay_rate = 0.00012
half_quantity = initial_quantity / 2

quantity = initial_quantity
years = 0

while quantity >= half_quantity:


quantity *= (1 - decay_rate)
years += 1
print(f"Carbon-14 has a half-life of {years} years.")

Output: Carbon-14 has a half-life of 5776 years.


probability_threshold = 0.5

n = 1
probability_no_shared_birthday = (364 / 365) ** n

while probability_no_shared_birthday > probability_threshold:


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

while balance >= target_balance:


balance = (1 + monthly_interest_rate) * balance - monthly_withdrawal
months += 1

print(f"Balance will be ${balance:.2f} after {months} months.")

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

while india_population_2014 <= china_population_2014:


china_population_2014 *= 1 + china_growth_rate
india_population_2014 *= 1 + india_growth_rate
t += 1

print(f"India's population will exceed China's population in the year {2014 +


t}.")

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

time = -1 / cooling_constant * (-((target_temperature - room_temperature) /


(initial_temperature - room_temperature)))

print(f"The coffee will cool to below {target_temperature} degrees in


{round(time)} minutes.")

Output: The coffee will cool to below 150 degrees in 7 minutes.


account_balance = 1000

while True:
print("\nOptions:")
print("1. Make a Deposit")
print("2. Make a Withdrawal")
print("3. Obtain Balance")
print("4. Quit")

choice = input("Make a selection from the options menu: ")

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:

Function: Raised when a sequence subscript is out of range.


Example: Trying to access an element in a list using an index that doesn't exist.

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")

choice = input("\tSelect Choice: ")


choice = choice.lower()

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

elif choice == 'b':


print(f"\nYour choice is {choice}")
print("\tChoose to convert:")
print("\t\t1. cm -> inch")
print("\t\t2. inch -> cm")
choice2 = input("\t\tSelect choice: ")
if choice2 == '1':
while True:
try:
num = float(input("\t\tEnter a number to convert: "))
res = num / 2.54
print(f"\t\tcm to inch conversion is {num:.2f}cm =
{res:.2f}inch")
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 * 2.54
print(f"\t\tinch to cm conversion is {num:.2f}inch =
{res:.2f}cm")
break
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("You have entered an invalid value.\n")
continue

elif choice == 'c':


print(f"\nYour choice is {choice}")
print("\tChoose to convert:")
print("\t\t1. inch -> ft")
print("\t\t2. ft -> inch")
choice2 = input("\t\tSelect choice: ")
if choice2 == '1':
while True:
try:
num = float(input("\t\tEnter a number to convert: "))
res = num / 12
print(f"\t\tinch to ft conversion is {num:.2f}inch =
{res:.2f}ft")
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 * 12
print(f"\t\tft to inch is {num:.2f}ft = {res:.2f}inch")
break
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("You have entered an invalid value.\n")
continue

elif choice == 'd':


print(f"\nYour choice is {choice}")
print("\tChoose to convert:")
print("\t\t1. ft -> yard")
print("\t\t2. yard -> ft")
choice2 = input("\t\tSelect choice: ")
if choice2 == '1':
while True:
try:
num = float(input("\t\tEnter a number to convert: "))
res = num / 3
print(f"\t\tft to yard conversion is {num:.2f}ft =
{res:.2f}yard")
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 * 3
print(f"\t\tyard to ft conversion is {num:.2f}yard =
{res:.2f}ft")
break
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("You have entered an invalid value.\n")
continue

elif choice == 'e':


print("Thank you for using my Metric Conversion. Bye!")
break
else:
print("You have entered an invalid value.\n")
continue

choice3 = input("\nDo you want another conversion (Y/N): ")


choice3 = choice3.lower()
if choice3 == "y" or choice3 == "yes":
continue
elif choice3 == "n" or choice3 == "no":
print("Thank you for using my Metric Conversion. Bye!")
break
else:
print("You have entered an invalid value.\n")
continue

You might also like