Python Basics Cheat Sheet

Python Programming Basics Cheat Sheet

Download PDF: Python Programming Basics Cheat Sheet.pdf

Basic Structure of a Python Program

# Basic structure
def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

Variables and Data Types

Variables
# Integer
number = 10

# Float
pi = 3.14

# String
name = "Alice"

# Boolean
is_valid = True
Data Types
# Integer
a = 10

# Float
b = 20.5

# String
c = "Hello, World!"

# Boolean
d = True

Control Flow

If Statements
if condition:
    # code block
elif another_condition:
    # another code block
else:
    # another code block
Loops
For Loop
for i in range(5):
    print(i)
While Loop
i = 0
while i < 5:
    print(i)
    i += 1

String Operations

# Concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2

# Formatting
name = "Alice"
age = 25
formatted_str = f"My name is {name} and I am {age} years old."

# Methods
uppercase_str = "hello".upper()
lowercase_str = "WORLD".lower()

File Operations

Reading from a File
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)
Writing to a File
with open('file.txt', 'w') as file:
    file.write("Hello, file!")

Comments

Single-Line Comments
# This is a single-line comment
x = 5  # This is an inline comment
Multi-Line Comments
"""
This is a multi-line comment
spanning multiple lines.
"""
y = 10

Basic Operators

Arithmetic Operators
+  # Addition
-  # Subtraction
*  # Multiplication
/  # Division
%  # Modulus
**  # Exponentiation
//  # Floor Division
Comparison Operators
==  # Equal to
!=  # Not equal to
>  # Greater than
<  # Less than
>=  # Greater than or equal to
<=  # Less than or equal to
Logical Operators
and  # Logical AND
or  # Logical OR
not  # Logical NOT

Functions

Defining a Function
def function_name(parameters):
    # code block
    return value
Calling a Function
result = function_name(arguments)

Data Structures

Lists
# Define a list
my_list = [1, 2, 3, 4, 5]

# Access elements
print(my_list[0])  # First element

# Add elements
my_list.append(6)

# Remove elements
my_list.remove(3)

# Slicing
print(my_list[1:3])
Tuples
# Define a tuple
my_tuple = (1, 2, 3)

# Access elements
print(my_tuple[0])
Dictionaries
# Define a dictionary
my_dict = {"name": "Alice", "age": 25}

# Access elements
print(my_dict["name"])

# Add elements
my_dict["email"] = "alice@example.com"

# Remove elements
del my_dict["age"]
Sets
# Define a set
my_set = {1, 2, 3, 4, 5}

# Add elements
my_set.add(6)

# Remove elements
my_set.remove(3)

Exception Handling

try:
    # code block that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # code block to handle the exception
    print("Cannot divide by zero!")
finally:
    # code block that will always execute
    print("This will always execute.")

Common Libraries

Importing Libraries
import math  # Import the entire module
print(math.sqrt(16))

from math import sqrt  # Import specific function
print(sqrt(16))

import numpy as np  # Import with alias
array = np.array([1, 2, 3])