back

Python Cheat Sheet

Contents

  1. Variables and Data Types
  2. Input and Output
  3. Arithmetic Operators
  4. Comparison Operators
  5. Logical Operators
  6. Membership Operators
  7. If elif else
  8. String Operations
  9. Functions
  10. While Loop
  11. For Loop
  12. List and Operations
  13. Tuples
  14. Set
  15. Dictionary
  16. Exception Handling
  17. File Handling
  18. Common Built-in Functions

Variables and Data Types

name = "John"   # string  ->  str
age = 30        # number  ->  int
weight = 63.5   # number  ->  float
married = True  # Boolean ->  bool

Input and Output

# Read Input from terminal window
name = input("Enter Name")  # -> John

# Write name to terminal window
print(name) # -> John

Arithmetic Operators

x = 10
y = 3
z = x + y   # addition          -> 13
z = x - y   # subtraction       -> 7
z = x * y   # multiplication    -> 30
z = x / y   # true division     -> 3.3333
z = x // y  # floor division    -> 3
z = x ** y  # exponent          -> 1000
z = x % y   # modulo division   -> 1

Comparison Operators

x = 10
y = 5

z = (x == y)   # Equal to                  -> False
z = (x != y)   # Not equal to              -> True
z = (x > y)    # Greater than              -> True
z = (x < y)    # Less than                 -> False
z = (x >= y)   # Greater than or equal to  -> True
z = (x <= y)   # Less than or equal to     -> False

Logical Operators

x = 10
y = 5
z = 15

result = (x > y) and (z > y)    # and  -> True (both conditions true)
result = (x > y) or (z < y)     # or   -> True (any one condition true)
result = not (x > y)            # not  -> False (negate condition)

Membership Operators

fruits = ["apple", "banana", "cherry"]
name = "python"

result = "banana" in fruits          # in       -> True
result = "mango" in fruits           # in       -> False
result = "python" in name            # in       -> True
result = "java" not in name          # not in   -> True
result = "banana" not in fruits      # not in   -> False

If elif else

if number > 0:
    print(f"{number} -> Positive")
elif number == 0:
    print(f"{number} -> Zero")
else:
    print(f"{number} -> Negative")

String Operations

text = "  Hello Python World!  "

print(text.upper())                     #   HELLO PYTHON WORLD!
print(text.lower())                     #   hello python world!

print(text.strip())                     # Hello Python World!
print(text.split())                     # ['Hello', 'Python', 'World!']

fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits))                # apple, banana, cherry

print("Python".find("th"))              # 2
print("Python".find("java"))            # -1

name = "John"
print("Hello, {}".format(name))         # Hello, John
print(f"Hello, {name}!")                # Hello, John!

Functions

def greet():
    print("Hello World!")
    
def hello(name):
    print("Hello", name)        

def add(x, y):
    return x + y

def increment(x, y = 1)
    return x + y

greet()                         # Hello World!
hello("John")                   # Hello John!

total = add(10, 20)
print(total)                    # 30

result = increment(10)
print(result)                   # 11 

While Loop

i = 1                    # Start
while i <= 10:           # Stop when i > 10
    print(i)
    i = i + 1            # Step

For Loop

for i in range(1, 11, 1):     # Start -> 1, Stop -> 11, Step -> 1
    print(i)

List

  • Lists are non-primitive data type to hold multiple items.
  • Can contain any types and number of items
  • Can have duplicates
  • Mutable - Can modify values
  • Allows zero based index read and write

List Operations

numbers = [10, 30, 20, 40]

numbers.append(50)         # [10, 30, 20, 40, 50]
numbers.insert(1, 15)      # [10, 15, 30, 20, 40, 50]
numbers.extend([60, 70])   # [10, 15, 30, 20, 40, 50, 60, 70]

numbers.pop()              # removes 70
numbers.pop(2)             # removes 30

numbers.clear()            # []

nums = [4, 1, 3, 2]
nums.sort()                # [1, 2, 3, 4]
nums.reverse()             # [4, 3, 2, 1]

List Slicing

numbers = [10, 20, 30, 40, 50, 60, 70, 80]

numbers[0]        # 10
numbers[-1]       # 80
numbers[2:5:1]    # [30, 40, 50]
numbers[:4]       # [10, 20, 30, 40]
numbers[3:]       # [40, 50, 60, 70, 80]
numbers[::-1]     # [80, 70, 60, 50, 40, 30, 20, 10]  reverse

List Comprehension

numbers = [1, 2, 3, 4, 5]
print(numbers)                      # [1, 2, 3, 4, 5]

square = [x**2 for x in numbers]
print(square)                       # [1, 4, 9, 16, 25]

Tuples

  • Immutable, can not modify after creation
  • Faster than list
# Creating a tuple
colors = ("red", "green", "blue", "yellow")

print(colors)          # ('red', 'green', 'blue', 'yellow')
print(type(colors))    # <class 'tuple'>

Set

  • Can not have duplicates
  • Mutable
nums = {1, 2, 3, 4, 5}

nums.add(6)            # Add single item
nums.update([7, 8, 9]) # Add multiple items

nums.remove(3)         # Remove item (error if not found)
nums.discard(10)       # Remove item (no error if not found)

print(len(nums))       # 8

Dictionary

  • Key, Value Pairs
  • Commonly used as look-up table
student = {
    "name": "John",
    "age": 20,
    "grade": "A",
    "city": "Chennai"
}

print(student)
print(student["name"])       # John
print(student.get("age"))    # 20

student["age"] = 21          # Update value
student["country"] = "India" # Add new key-value

print(student.keys())      # ['name', 'age', 'grade', 'city', 'country']
print(student.values())    # ['John', 21, 'A', 'Chennai', 'India']
print(student.items())     # [('name', 'John'), ...]

del student["city"]        # Delete a key
student.pop("grade")       # Remove and return value
student.clear()            # Remove all items

Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

try:
    x = "10"
    y = "ABC"

    result = int(x) / int(y)
except ValueError:
    print("Invalid input, can not convert to int")
finally:
    print("Clean up resources in finally")

File Handling

Read Mode

  • throws error when file not found
file = open("Quotes.txt", "r")      # r - Read
all_string = file.read()
one_line   = file.readline()
all_lines  = file.readlines()
file.close()

Write Mode

  • Create file when not present
  • Caution overwrites when file already exists
file = open("Quotes.txt", "w")      # w - Write
file.write("Hello from python")
file.writelines(["First Line\n", "Second Line\n"])
file.close()

Append Mode

  • Create file when not present
  • Appends to existing file.
file = open("Quotes.txt", "a")      # a - append
file.write("Hello from python")
file.writelines(["First Line\n", "Second Line\n"])
file.close()

Common Built-in Functions

len(), sum(), min(), max(), sorted(), type(str), dir(list)