Debugging
print() (Debug)
Syntax: print('Debug Info:', variable)
Description: The most common way to debug. Print variable values at different steps to see what is
happening.
Example:
x = 10\nprint('Debug: x is currently', x)\nx += 5\nprint('Debug: x is now', x)
assert
Syntax: assert condition, message
Description: Checks a condition. If it is False, it raises an AssertionError with your message.
Example:
x = -1\n# This will trigger an error because x is not > 0\nassert x > 0, 'x must be
positive'
try...except
Syntax: try:\n # code\nexcept Error:\n # handle error
Description: Catches errors so the program continues running instead of crashing.
Example:
try:\n val = int('abc')\nexcept ValueError:\n print('Error: Could not convert to
number')
raise
Syntax: raise ErrorType('Message')
Description: Manually triggers an exception when something goes wrong.
Example:
age = -5\nif age < 0:\n raise ValueError('Age cannot be negative')
type()
Syntax: type(object)
Description: Returns the data type of a variable. Essential for fixing 'TypeErrors'.
Example:
x = 5\ny = '5'\nprint(type(x))\nprint(type(y))
dir()
Syntax: dir(object)
Description: Returns a list of all valid attributes and methods for that object.
Example:
my_list = []\n# Shows all things you can do to a list\nprint(dir(my_list))
help()
Syntax: help(object)
Description: Prints the documentation for a specific object or function.
Example:
# Shows help docs for the len function\nhelp(len)
breakpoint()
Syntax: breakpoint()
Description: Pauses the program and enters the debugger.
Example:
print('Start')\n# breakpoint() would pause here in VS Code\nprint('End')
Decisions
if
Syntax: if condition:
Description: Executes a block of code if the condition is true.
Example:
if 5 > 3:\n print('Yes')
if-else (ternary)
Syntax: val if cond else other
Description: One line conditional assignment.
Example:
print('Yes') if 5 > 3 else print('No')
elif
Syntax: elif condition:
Description: Used in conditional statements, stands for 'else if'.
Example:
x = 10\nif x > 10: print('A')\nelif x == 10: print('B')
and
Syntax: cond1 and cond2
Description: Logical AND: True only if both operands are true.
Example:
print(True and False)
or
Syntax: cond1 or cond2
Description: Logical OR: True if at least one operand is true.
Example:
print(True or False)
not
Syntax: not condition
Description: Logical NOT: Reverses the result.
Example:
print(not True)
in (list)
Syntax: value in list
Description: Membership operator.
Example:
print(3 in [1, 2, 3])
not in
Syntax: value not in list
Description: Membership operator checking absence.
Example:
print(5 not in [1, 2, 3])
Files
open()
Syntax: open(filename, mode)
Description: Opens a file (Note: Browser simulation).
Example:
# In browser, we simulate\nprint('Opening file object...')
read()
Syntax: [Link]()
Description: Reads the content of the file.
Example:
# [Link]()
readline()
Syntax: [Link]()
Description: Reads one line from the file.
Example:
# [Link]()
readlines()
Syntax: [Link]()
Description: Returns a list containing each line in the file.
Example:
# [Link]()
write()
Syntax: [Link](str)
Description: Writes a string to the file.
Example:
# [Link]('Hello')
close()
Syntax: [Link]()
Description: Closes the file.
Example:
# [Link]()
with statement
Syntax: with open() as f:
Description: Context manager to automatically close files.
Example:
# with open('[Link]') as f:\n# data = [Link]()
Functions
def
Syntax: def name():
Description: Keyword used to define a function.
Example:
def add(a, b):\n return a + b\nprint(add(2, 3))
return
Syntax: return value
Description: Exits a function and optionally returns a value.
Example:
def f():\n return 10\nprint(f())
Default Parameter
Syntax: def f(a=val):
Description: Function parameter with a default value.
Example:
def f(a=5):\n return a\nprint(f())
*args
Syntax: def f(*args):
Description: Arbitrary number of arguments (passed as tuple).
Example:
def sum_all(*args):\n return sum(args)\nprint(sum_all(1, 2, 3))
**kwargs
Syntax: def f(**kwargs):
Description: Arbitrary number of keyword arguments (passed as dict).
Example:
def f(**kwargs):\n return kwargs\nprint(f(a=1, b=2))
lambda
Syntax: lambda args: expression
Description: Small anonymous function.
Example:
square = lambda x: x**2\nprint(square(4))
GUI
[Link]()
Syntax: root = [Link]()
Description: Creates the main window.
Example:
import turtle\n# Tkinter is limited in browser.\n# We use Turtle for visual demo:\nt =
[Link]()\[Link](100)
[Link]()
Syntax: [Link](root, text='')
Description: Widget to display text.
Example:
# [Link](root, text='Hi').pack()
[Link]()
Syntax: [Link](root, command=cmd)
Description: Widget to capture clicks.
Example:
# [Link](root, text='Click', command=func).pack()
[Link]()
Syntax: [Link](root)
Description: Widget for single-line text input.
Example:
# [Link](root).pack()
[Link]()
Syntax: [Link]()
Description: Runs the application.
Example:
# [Link]()
Libraries
import
Syntax: import module
Description: Imports a module.
Example:
import math\nprint([Link])
from...import
Syntax: from module import func
Description: Imports specific parts of a module.
Example:
from math import sqrt\nprint(sqrt(9))
[Link]()
Syntax: [Link](x)
Description: Returns square root.
Example:
import math\nprint([Link](16))
[Link]()
Syntax: [Link](x)
Description: Rounds a number up to the nearest integer.
Example:
import math\nprint([Link](2.3))
[Link]()
Syntax: [Link](x)
Description: Rounds a number down to the nearest integer.
Example:
import math\nprint([Link](2.7))
[Link]()
Syntax: [Link](x)
Description: Returns the factorial of a number.
Example:
import math\nprint([Link](5))
[Link]()
Syntax: [Link](a, b)
Description: Returns a random integer between a and b.
Example:
import random\nprint([Link](1, 5))
[Link]()
Syntax: [Link](seq)
Description: Returns a random element from a sequence.
Example:
import random\nprint([Link]([1, 2, 3]))
[Link]
Syntax: [Link]()
Description: Returns the current local date.
Example:
from datetime import date\nprint([Link]())
Lists
.append()
Syntax: [Link](elm)
Description: Adds an element at the end of the list.
Example:
l = [1, 2]\[Link](3)\nprint(l)
.insert()
Syntax: [Link](pos, elm)
Description: Adds an element at the specified position.
Example:
l = [1, 3]\[Link](1, 2)\nprint(l)
.remove()
Syntax: [Link](elm)
Description: Removes the first item with the specified value.
Example:
l = [1, 2, 3]\[Link](2)\nprint(l)
.pop()
Syntax: [Link](pos)
Description: Removes the element at the specified position (default last).
Example:
l = [1, 2, 3]\nprint([Link]())
.sort()
Syntax: [Link]()
Description: Sorts the list in ascending order.
Example:
l = [3, 1, 2]\[Link]()\nprint(l)
.reverse()
Syntax: [Link]()
Description: Reverses the order of the list.
Example:
l = [1, 2, 3]\[Link]()\nprint(l)
List Length
Syntax: len(list)
Description: Returns the number of elements in the list.
Example:
print(len([1, 2, 3]))
List Slicing
Syntax: list[start:end]
Description: Access a range of items in a list.
Example:
l = [1, 2, 3, 4]\nprint(l[1:3])
List Concatenation
Syntax: list1 + list2
Description: Joins two lists.
Example:
print([1, 2] + [3, 4])
List Repetition
Syntax: list * num
Description: Repeats the list.
Example:
print([0] * 3)
Loops
for
Syntax: for i in iterable:
Description: Iterates over a sequence.
Example:
for i in range(3):\n print(i)
while
Syntax: while condition:
Description: Executes a set of statements as long as a condition is true.
Example:
i=0\nwhile i<3:\n print(i)\n i+=1
break
Syntax: break
Description: Stops the loop.
Example:
for i in range(5):\n if i==3: break\n print(i)
continue
Syntax: continue
Description: Stops the current iteration of the loop and continues with the next.
Example:
for i in range(5):\n if i==3: continue\n print(i)
pass
Syntax: pass
Description: Null statement; does nothing. Used as a placeholder.
Example:
for i in range(3):\n pass
Nested Loop
Syntax: for x in .. for y in ..
Description: Loop inside a loop.
Example:
for i in range(2):\n for j in range(2):\n print(i, j)
Strings
.lower()
Syntax: [Link]()
Description: Converts a string into lower case.
Example:
text = 'Hello'\nprint([Link]())
.upper()
Syntax: [Link]()
Description: Converts a string into upper case.
Example:
text = 'Hello'\nprint([Link]())
.title()
Syntax: [Link]()
Description: Converts the first character of each word to upper case.
Example:
text = 'hello world'\nprint([Link]())
.capitalize()
Syntax: [Link]()
Description: Converts the first character to upper case.
Example:
text = 'hello'\nprint([Link]())
.swapcase()
Syntax: [Link]()
Description: Swaps cases, lower becomes upper and vice versa.
Example:
text = 'Hi There'\nprint([Link]())
.strip()
Syntax: [Link]()
Description: Removes any whitespace from the beginning and the end.
.lstrip()
Syntax: [Link]()
Description: Removes leading (left) whitespace.
.rstrip()
Syntax: [Link]()
Description: Removes trailing (right) whitespace.
.replace()
Syntax: [Link](old, new)
Description: Replaces a specified value with another value.
Example:
text = 'hi hi'\nprint([Link]('hi', 'yo'))
.split()
Syntax: [Link](separator)
Description: Splits the string at the specified separator, returning a list.
Example:
text = 'a b c'\nprint([Link]())
.join()
Syntax: [Link](iterable)
Description: Joins the elements of an iterable to the end of the string.
Example:
mylist = ['a', 'b']\nprint(' '.join(mylist))
.startswith()
Syntax: [Link](value)
Description: Returns true if the string starts with the specified value.
Example:
print('hello'.startswith('he'))
.endswith()
Syntax: [Link](value)
Description: Returns true if the string ends with the specified value.
Example:
print('hello'.endswith('lo'))
.find()
Syntax: [Link](value)
Description: Searches the string for a specified value and returns the position.
Example:
print('hello'.find('lo'))
.count()
Syntax: [Link](value)
Description: Returns the number of times a specified value occurs in a string.
Example:
print('hello'.count('l'))
len()
Syntax: len(object)
Description: Returns the length of an object.
Example:
print(len('hello'))
Concatenation (+)
Syntax: str1 + str2
Description: Combines two strings together.
Example:
print('Hi ' + 'there')
Repetition (*)
Syntax: str * number
Description: Repeats the string a specified number of times.
Example:
print('A' * 3)
in (String)
Syntax: value in string
Description: Returns True if a value is present in the string.
Example:
print('he' in 'hello')
Slicing
Syntax: string[start:end]
Description: Returns a substring from start index to end index.
Example:
print('hello'[1:4])
.isalnum()
Syntax: [Link]()
Description: Returns True if all characters in the string are alphanumeric.
Example:
print('abc123'.isalnum())
.isalpha()
Syntax: [Link]()
Description: Returns True if all characters in the string are in the alphabet.
Example:
print('abc'.isalpha())
.isdigit()
Syntax: [Link]()
Description: Returns True if all characters in the string are digits.
Example:
print('123'.isdigit())
.isspace()
Syntax: [Link]()
Description: Returns True if all characters in the string are whitespaces.
Example:
print(' '.isspace())
.islower()
Syntax: [Link]()
Description: Returns True if all characters in the string are lower case.
Example:
print('abc'.islower())
.isupper()
Syntax: [Link]()
Description: Returns True if all characters in the string are upper case.
Example:
print('ABC'.isupper())
Variables
int()
Syntax: int(value)
Description: Converts a value to an integer.
Example:
print(int('5') + 5)
float()
Syntax: float(value)
Description: Converts a value to a float number.
Example:
print(float('3.14'))
str()
Syntax: str(value)
Description: Converts a value to a string.
Example:
print('Value: ' + str(100))
type()
Syntax: type(object)
Description: Returns the type of the object.
Example:
print(type(10))
round()
Syntax: round(number, digits)
Description: Rounds a number to a specified number of digits.
Example:
print(round(3.14159, 2))
abs()
Syntax: abs(number)
Description: Returns the absolute value of a number.
Example:
print(abs(-5))
divmod()
Syntax: divmod(x, y)
Description: Returns the quotient and the remainder when x is divided by y.
Example:
print(divmod(7, 3))
pow()
Syntax: pow(base, exp)
Description: Returns the value of x to the power of y.
Example:
print(pow(2, 3))
Exponent (**)
Syntax: x ** y
Description: Power operator.
Example:
print(2 ** 3)
Modulo (%)
Syntax: x % y
Description: Returns the remainder of division.
Example:
print(7 % 3)
Floor Division (//)
Syntax: x // y
Description: Divides and returns the integer value of the quotient.
Example:
print(7 // 3)
Addition (+)
Syntax: x + y
Description: Adds two values.
Example:
print(2 + 3)
Subtraction (-)
Syntax: x - y
Description: Subtracts one value from another.
Example:
print(5 - 2)
Multiplication (*)
Syntax: x * y
Description: Multiplies two values.
Example:
print(3 * 4)
Division (/)
Syntax: x / y
Description: Divides two values (always returns float).
Example:
print(10 / 2)
Equal (==)
Syntax: x == y
Description: Checks if values are equal.
Example:
print(5 == 5)
Not Equal (!=)
Syntax: x != y
Description: Checks if values are not equal.
Example:
print(5 != 3)
Greater Than (>)
Syntax: x > y
Description: Checks if left operand is greater than right.
Example:
print(5 > 3)
Less Than (<)
Syntax: x < y
Description: Checks if left operand is less than right.
Example:
print(5 < 3)
Greater/Equal (>=)
Syntax: x >= y
Description: Checks if left operand is greater than or equal to right.
Example:
print(5 >= 5)
Less/Equal (<=)
Syntax: x <= y
Description: Checks if left operand is less than or equal to right.
Example:
print(3 <= 5)