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 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.
Prints a message to the screen.
print("Hello, World!")
Performs basic arithmetic operations.
# Addition
result = 2 + 3
Defines the type of values.
num = 10 # Integer
text = "Python" # String
Opens, reads, writes, and closes files.
with open('file.txt', 'r') as file:
content = file.read()
Defines reusable blocks of code.
def greet(name):
return f"Hello, {name}!"
Manages and manipulates text data.
s = "Python"
print(s.upper())
Implements conditional logic.
if x > 0:
print("Positive")
else:
print("Non-positive")
Repeats a block of code multiple times.
for i in range(5):
print(i)
Stores an ordered collection of items.
fruits = ["apple", "banana", "cherry"]
Stores values that can be reused and manipulated.
age = 25
Formats strings using expressions inside curly braces.
name = "Alice"
print(f"Hello, {name}")
Adds a value to a variable and assigns the result to that variable.
count = 0
count += 1
Text data enclosed in single or double quotes.
s = "Hello"
Ordered and mutable sequence of elements.
lst = [1, 2, 3]
Key-value pairs enclosed in curly braces.
d = {"one": 1, "two": 2}
Represents True or False values.
is_active = True
Unordered collection of unique elements.
s = {1, 2, 3}
Ordered and immutable sequence of elements.
t = (1, 2, 3)
Numeric data types like int, float, and complex.
num = 10 # Integer
float_num = 10.5 # Float
Converts a variable from one type to another.
x = int(3.8) # 3
Access characters using indexes.
s = "Python"
print(s[0]) # 'P'
Gets the length of a string.
length = len("Python")
Checks if a substring exists within a string.
if "Py" in "Python":
print("Found!")
Iterates through characters of a string.
for char in "Python":
print(char)
Combines two or more strings.
full = "Hello" + " " + "World"
Extracts part of a string.
substr = "Python"[2:5] # 'tho'
Repeats a string multiple times.
repeat = "Hi! " * 3 # 'Hi! Hi! Hi! '
Formats strings using {} placeholders.
s = "Hello, {}. Welcome to {}.".format(name, place)
Takes user input as a string.
user_input = input("Enter something: ")
Joins elements of an iterable into a single string.
join_str = ", ".join(["apple", "banana", "cherry"])
Checks if a string ends with a specific suffix.
ends = "python.org".endswith(".org") # True
Creates a list with specified elements.
fruits = ["apple", "banana", "cherry"]
Extracts parts of a list.
sublist = fruits[1:3] # ['banana', 'cherry']
Omits starting or ending index for slicing.
sublist_from_start = fruits[:2] # ['apple', 'banana']
sublist_to_end = fruits[1:] # ['banana', 'cherry']
Extracts elements with step size.
stride_slicing = fruits[::2] # ['apple', 'cherry']
Counts occurrences of an element in a list.
count = fruits.count("apple")
Repeats elements in a list.
repeat_list = [0] * 5 # [0, 0, 0, 0, 0]
Sorts and reverses a list.
fruits.sort() # ['apple', 'banana', 'cherry']
fruits.reverse() # ['cherry', 'banana', 'apple']
Accesses elements by index.
first_fruit = fruits[0] # 'apple'
Combines two or more lists.
combined = fruits + ["kiwi", "mango"]
Repeats a block of code for a fixed number of times.
for i in range(3):
print(i)
Exits the loop prematurely.
for i in range(5):
if i == 3:
break
print(i)
Iterates over multiple iterables in parallel.
names = ["Alice", "Bob"]
scores = [85, 92]
for name, score in zip(names, scores):
print(name, score)
Continues until a condition is met.
count = 0
while count < 5:
print(count)
count += 1
Generates a sequence of numbers.
for i in range(1, 10, 2):
print(i)
Skips the current iteration and proceeds to the next.
for i in range(5):
if i == 3:
continue
print(i)
Uses range and len to loop with an index.
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
Executes else block if no break occurs.
for i in range(5):
if i == 6:
break
else:
print("Completed")
Defines a function with a specific task.
def greet():
print("Hello, World!")
Passes arguments by name.
def introduce(name, age):
print(f"Name: {name}, Age: {age}")
introduce(age=30, name="Alice")
Uses lambda for short, unnamed functions.
square = lambda x: x ** 2
print(square(5))
Returns a value from a function.
def add(a, b):
return a + b
Returns multiple values from a function.
def get_name_age():
return "Alice", 25
name, age = get_name_age()
Uses default values for parameters.
def greet(name="Guest"):
print(f"Hello, {name}!")
Passes arguments in the order of parameters.
def add(a, b):
print(a + b)
add(3, 5)
Imports a module to use its functions and attributes.
import math
print(math.sqrt(16))
Uses an alias for a module.
import numpy as np
Imports all functions and attributes from a module.
from math import *
Uses specific functions and attributes from a module.
from math import pow, pi
print(pow(2, 3))
print(pi)
Defines a blueprint for objects.
class Dog:
def __init__(self, name):
self.name = name
Variables shared among all instances.
class Dog:
species = "Canine"
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())
Redefines methods in a subclass.
class Animal:
def make_sound(self):
print("Generic sound")
class Dog(Animal):
def make_sound(self):
print("Bark")
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
Creates custom exception classes.
class CustomError(Exception):
pass
Provides a string representation of an object.
class Dog:
def __repr__(self):
return f"Dog({self.name})"
Special methods to initialize new objects.
class Dog:
def __init__(self, name):
self.name = name
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.
specialization
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
course
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
course
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
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.