Python Basics Cheat Sheet & Quick Reference

Written by Coursera • Updated on

Master essential Python commands and data types. This guide covers everything from basic operations and data handling to loops, functions, modules, and classes, helping you quickly navigate common Python programming tasks.

Python Cheat Sheet

Python is a versatile and powerful programming language that is easy to learn and widely used in various fields such as web development, data science, automation, and more. Its simplicity and readability make it an ideal choice for beginners and experienced developers. This cheat sheet provides a quick reference for the most common Python commands and types to help you get started and navigate the essentials of Python programming.

Python Basics Cheat Sheet PDF

Click to download

Getting Started with Basics

Hello world:

Prints a message to the screen.

print("Hello, World!")

Arithmetic:

Performs basic arithmetic operations.

# Addition
result = 2 + 3

Data types:

Defines the type of values.

num = 10   # Integer
text = "Python"   # String

File handling:

Opens, reads, writes, and closes files.

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

Functions:

Defines reusable blocks of code.

def greet(name):
    return f"Hello, {name}!"

Strings:

Manages and manipulates text data.

s = "Python"
print(s.upper())

If else:

Implements conditional logic.

if x > 0:
    print("Positive")
else:
    print("Non-positive")

Loops:

Repeats a block of code multiple times.

for i in range(5):
    print(i)

Lists:

Stores an ordered collection of items.

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

Variables:

Stores values that can be reused and manipulated.

age = 25

f-Strings:

Formats strings using expressions inside curly braces.

name = "Alice"
print(f"Hello, {name}")

Plus-equals:

Adds a value to a variable and assigns the result to that variable.

count = 0
count += 1

Python Built-in Data Types

Strings:

Text data enclosed in single or double quotes.

s = "Hello"

Lists:

Ordered and mutable sequence of elements.

lst = [1, 2, 3]

Dictionary:

Key-value pairs enclosed in curly braces.

d = {"one": 1, "two": 2}

Booleans:

Represents True or False values.

is_active = True

Set:

Unordered collection of unique elements.

s = {1, 2, 3}

Tuple:

Ordered and immutable sequence of elements.

t = (1, 2, 3)

Numbers:

Numeric data types like int, float, and complex.

num = 10   # Integer
float_num = 10.5   # Float

Casting:

Converts a variable from one type to another.

x = int(3.8)   # 3

Python Strings

Array-like:

Access characters using indexes.

s = "Python"
print(s[0])   # 'P'

String length:

Gets the length of a string.

length = len("Python")

Check string:

Checks if a substring exists within a string.

if "Py" in "Python":
    print("Found!")

Looping:

Iterates through characters of a string.

for char in "Python":
    print(char)

Concatenates:

Combines two or more strings.

full = "Hello" + " " + "World"

Slicing string:

Extracts part of a string.

substr = "Python"[2:5]   # 'tho'

Multiple copies:

Repeats a string multiple times.

repeat = "Hi! " * 3   # 'Hi! Hi! Hi! '

Formatting:

Formats strings using {} placeholders.

s = "Hello, {}. Welcome to {}.".format(name, place)

Input:

Takes user input as a string.

user_input = input("Enter something: ")

Join:

Joins elements of an iterable into a single string.

join_str = ", ".join(["apple", "banana", "cherry"])

Endswith:

Checks if a string ends with a specific suffix.

ends = "python.org".endswith(".org")   # True

Python Lists Commands

Generate:

Creates a list with specified elements.

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

List slicing:

Extracts parts of a list.

sublist = fruits[1:3]   # ['banana', 'cherry']

Omitting index:

Omits starting or ending index for slicing.

sublist_from_start = fruits[:2]   # ['apple', 'banana']
sublist_to_end = fruits[1:]   # ['banana', 'cherry']

With a stride:

Extracts elements with step size.

stride_slicing = fruits[::2]   # ['apple', 'cherry']

Count:

Counts occurrences of an element in a list.

count = fruits.count("apple")

Repeating:

Repeats elements in a list.

repeat_list = [0] * 5   # [0, 0, 0, 0, 0]

Sort & reverse:

Sorts and reverses a list.

fruits.sort()   # ['apple', 'banana', 'cherry']
fruits.reverse()   # ['cherry', 'banana', 'apple']

Access:

Accesses elements by index.

first_fruit = fruits[0]   # 'apple'

Concatenating:

Combines two or more lists.

combined = fruits + ["kiwi", "mango"]

Python Loops

Basic:

Repeats a block of code for a fixed number of times.

for i in range(3):
    print(i)

Break:

Exits the loop prematurely.

for i in range(5):
    if i == 3:
        break
    print(i)

With zip():

Iterates over multiple iterables in parallel.

names = ["Alice", "Bob"]
scores = [85, 92]
for name, score in zip(names, scores):
    print(name, score)

While:

Continues until a condition is met.

count = 0
while count < 5:
    print(count)
    count += 1

Range:

Generates a sequence of numbers.

for i in range(1, 10, 2):
    print(i)

Continue:

Skips the current iteration and proceeds to the next.

for i in range(5):
    if i == 3:
        continue
    print(i)

With index:

Uses range and len to loop with an index.

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(fruits[i])

for/else:

Executes else block if no break occurs.

for i in range(5):
    if i == 6:
        break
else:
    print("Completed")

Python Functions

Basic:

Defines a function with a specific task.

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

Keyword arguments:

Passes arguments by name.

def introduce(name, age):
    print(f"Name: {name}, Age: {age}")
introduce(age=30, name="Alice")

Anonymous functions:

Uses lambda for short, unnamed functions.

square = lambda x: x ** 2
print(square(5))

Return:

Returns a value from a function.

def add(a, b):
    return a + b

Returning multiples:

Returns multiple values from a function.

def get_name_age():
    return "Alice", 25
name, age = get_name_age()

Default value:

Uses default values for parameters.

def greet(name="Guest"):
    print(f"Hello, {name}!")

Positional arguments:

Passes arguments in the order of parameters.

def add(a, b):
    print(a + b)
add(3, 5)

Python Modules

Import modules:

Imports a module to use its functions and attributes.

import math
print(math.sqrt(16))

Shorten module:

Uses an alias for a module.

import numpy as np

From a module import all:

Imports all functions and attributes from a module.

from math import *

Functions and attributes:

Uses specific functions and attributes from a module.

from math import pow, pi
print(pow(2, 3))
print(pi)

Python Classes

Defining:

Defines a blueprint for objects.

class Dog:
    def __init__(self, name):
        self.name = name

Class variables:

Variables shared among all instances.

class Dog:
    species = "Canine"

Polymorphism:

Uses a single interface for different types.

class Cat:
    def sound(self):
        return "Meow"
class Dog:
    def sound(self):
        return "Bark"
for pet in (Cat(), Dog()):
    print(pet.sound())

Overriding:

Redefines methods in a subclass.

class Animal:
    def make_sound(self):
        print("Generic sound")
class Dog(Animal):
    def make_sound(self):
        print("Bark")

Inheritance:

Derives a new class from an existing class.

class Animal:
    def __init__(self, name):
        self.name = name
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

User-defined exceptions:

Creates custom exception classes.

class CustomError(Exception):
    pass

repr() method:

Provides a string representation of an object.

class Dog:
    def __repr__(self):
        return f"Dog({self.name})"

Constructors:

Special methods to initialize new objects.

class Dog:
    def __init__(self, name):
        self.name = name

Method:

Defines functions within a class.

class Dog:
    def bark(self):
        print("Woof!")

This cheat sheet covers essential Python commands and concepts to help you quickly reference and master the basics of Python programming. Whether you are a beginner or looking to refresh your knowledge, Coursera offers online courses in Python to help support your career.

Further Python Resources:

Popular Python Courses:

Placeholder

specialization

Python for Everybody

Learn to Program and Analyze Data with Python. Develop programs to gather, clean, analyze, and visualize data.

4.8

(214,160 ratings)

1,728,862 already enrolled

Beginner level

Average time: 2 month(s)

Learn at your own pace

Skills you'll build:

Json, Xml, Python Programming, Database (DBMS), Python Syntax And Semantics, Basic Programming Language, Computer Programming, Sqlite, SQL, Data Structure, Tuple, Data Analysis, Data Visualization, Web Scraping

Placeholder

course

Python for Data Science, AI & Development

Kickstart your learning of Python with this beginner-friendly self-paced course taught by an expert. Python is one of the most popular languages in the ...

4.6

(39,229 ratings)

1,058,774 already enrolled

Beginner level

Average time: 25 hour(s)

Learn at your own pace

Skills you'll build:

Data Science, Data Analysis, Python Programming, Numpy, Pandas

Placeholder

course

Crash Course on Python

This course is designed to teach you the foundations in order to write simple programs in Python using the most common structures. No previous exposure to ...

4.8

(38,575 ratings)

1,177,730 already enrolled

Beginner level

Average time: 20 hour(s)

Learn at your own pace

Skills you'll build:

Python Programming, Basic Python Syntax, Basic Python Data Structures, Object-Oriented Programming (OOP), Fundamental Programming Concepts

Updated on
Written by:

Coursera

Writer

Coursera is the global online learning platform that offers anyone, anywhere access to online course...

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Build job-ready development skills including Java and SQL.

Unlock a year of unlimited access to learning for $199.