Python Cheatsheet

Variables & Data Types

Assigning Variables

Variables store data values. Python is dynamically typed.

name = "Alice"  # String
age = 30      # Integer
height = 5.8  # Float
is_student = True # Boolean
my_list = [1, "apple", 3.14] # List
my_tuple = (10, 20, "banana") # Tuple
my_dict = {"key": "value", "id": 123} # Dictionary
my_set = {1, 2, 3, 3} # Set (duplicates removed)

Common Data Types

Type Description Example
str Sequence of characters (text) "Hello World"
int Whole numbers 42, -100
float Numbers with a decimal point 3.14159, -0.001
bool Logical values True, False
list Ordered, mutable sequence [1, 'a', True]
tuple Ordered, immutable sequence (1, 'a', True)
dict Unordered collection of key-value pairs {'name': 'Bob', 'age': 25}
set Unordered collection of unique items {1, 2, 'c'}

Basic Operations

Arithmetic Operators

a = 10
b = 3
print(a + b)  # Addition: 13
print(a - b)  # Subtraction: 7
print(a * b)  # Multiplication: 30
print(a / b)  # Division: 3.333...
print(a // b) # Floor Division: 3
print(a % b)  # Modulus: 1
print(a ** b) # Exponentiation: 1000

String Operations

s1 = "Hello"
s2 = "World"
greeting = s1 + " " + s2 + "!" # Concatenation: "Hello World!"
print(greeting)
print(s1 * 3) # Repetition: "HelloHelloHello"
print(len(greeting)) # Length: 12
print(greeting[0]) # Indexing: "H"
print(greeting[6:11]) # Slicing: "World"

String Operations

String Methods

Python provides a variety of built-in methods to manipulate strings.

text = "  Hello, World!  "

        # Removing whitespace
        print(text.strip())  # "Hello, World!"

        # Changing case
        print(text.lower())  # "  hello, world!  "
        print(text.upper())  # "  HELLO, WORLD!  "

        # Replacing substrings
        print(text.replace("World", "Python"))  # "  Hello, Python!  "

        # Splitting and joining
        words = text.split(",")  # ["  Hello", " World!  "]
        print(" ".join(words))   # "  Hello  World!  "

Checking String Content

You can check for specific content in strings using these methods:

text = "Hello123"

        # Checking content
        print(text.isalpha())  # False (contains numbers)
        print(text.isdigit())  # False (contains letters)
        print(text.isalnum())  # True (letters and numbers only)
        print(text.startswith("Hello"))  # True
        print(text.endswith("123"))      # True

String Formatting

Python offers multiple ways to format strings:

# Using f-strings
        name = "Alice"
        age = 25
        print(f"My name is {name} and I am {age} years old.")

        # Using format()
        print("My name is {} and I am {} years old.".format(name, age))

        # Using % formatting
        print("My name is %s and I am %d years old." % (name, age))

User Input

Using input()

The input() function allows you to take input from the user as a string.

name = input("What is your name? ")
        print(f"Hello, {name}!")

Converting Input

You can convert the input to other data types using functions like int(), float(), etc.

age = int(input("How old are you? "))
        print(f"You are {age} years old.")

Handling Multiple Inputs

You can take multiple inputs in one line using split().

data = input("Enter your name and age separated by a space: ").split()
        name, age = data[0], int(data[1])
        print(f"Name: {name}, Age: {age}")

Loops

For Loops

A for loop is used to iterate over a sequence (like a list, tuple, or string).

# Iterating over a list
        fruits = ["apple", "banana", "cherry"]
        for fruit in fruits:
            print(fruit)

        # Iterating over a range
        for i in range(5):
            print(i)  # Prints 0 to 4

While Loops

A while loop continues as long as a condition is true.

# Using a while loop
        count = 0
        while count < 5:
            print(count)
            count += 1  # Increment count

Breaking Out of Loops

Use break to exit a loop prematurely.

for i in range(10):
            if i == 5:
                break
            print(i)  # Stops when i is 5

Skipping Iterations

Use continue to skip the current iteration and move to the next.

for i in range(10):
            if i % 2 == 0:
                continue
            print(i)  # Prints only odd numbers

Turtle Module

Introduction

The turtle module is used to create graphics and drawings by controlling a virtual "turtle" on the screen.

Basic Example

import turtle

        # Create a screen and a turtle
        screen = turtle.Screen()
        t = turtle.Turtle()

        # Draw a square
        for _ in range(4):
            t.forward(100)  # Move forward by 100 units
            t.right(90)     # Turn right by 90 degrees

        # Close the window on click
        screen.mainloop()

Customizing the Turtle

import turtle

        t = turtle.Turtle()

        # Change the turtle's appearance
        t.shape("turtle")  # Other options: "arrow", "circle", "square", etc.
        t.color("blue")    # Set the turtle's color
        t.pensize(3)       # Set the pen thickness

        # Draw a triangle
        for _ in range(3):
            t.forward(100)
            t.left(120)

        turtle.done()

Drawing with Loops

import turtle

        t = turtle.Turtle()

        # Draw a circle made of small lines
        for _ in range(36):
            t.forward(10)
            t.right(10)

        turtle.done()

Math Module

Introduction

The math module provides access to mathematical functions and constants.

Common Functions

import math

        # Constants
        print(math.pi)  # 3.14159...
        print(math.e)   # 2.71828...

        # Trigonometric functions
        print(math.sin(math.pi / 2))  # 1.0
        print(math.cos(0))           # 1.0

        # Exponential and logarithmic functions
        print(math.exp(2))           # e^2
        print(math.log(10))          # Natural log
        print(math.log10(100))       # Log base 10

        # Rounding and absolute value
        print(math.ceil(4.2))        # 5
        print(math.floor(4.8))       # 4
        print(math.fabs(-5))         # 5.0

Dictionaries

Introduction

Dictionaries are collections of key-value pairs. Keys must be unique and immutable.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

Accessing Values

print(my_dict["name"])  # Access value by key: "Alice"
        print(my_dict.get("age"))  # Access value using get(): 25

Adding and Updating

my_dict["country"] = "USA"  # Add new key-value pair
        my_dict["age"] = 26         # Update existing value

Removing Items

my_dict.pop("city")  # Remove key and return its value
        del my_dict["age"]         # Remove key-value pair

Iterating Over a Dictionary

for key, value in my_dict.items():
            print(f"{key}: {value}")

Common Methods

keys = my_dict.keys()      # Get all keys
        values = my_dict.values()  # Get all values
        items = my_dict.items()    # Get all key-value pairs