Python Cheat Sheet

Published:5 min read

Python is a powerful, easy-to-learn programming language that has gained popularity due to its simplicity and versatility. This comprehensive guide will walk you through the fundamentals of Python, from installing it to using advanced features like classes, functions, and file handling.

What is Python?

Python is a high-level, general-purpose programming language that emphasizes code readability and simplicity. Created by Guido van Rossum in the late 1980s, Python is widely used for web development, data science, automation, and more. Its syntax is easy to learn, making it a great choice for beginners and professionals alike.

What Can Python Do?

Python can be used for a variety of tasks, such as:

  • Web development: Using frameworks like Django or Flask.
  • Data analysis and machine learning: Using libraries like pandas and scikit-learn.
  • Automation: Writing scripts to automate tasks.
  • Game development: Using libraries like Pygame.
  • Desktop applications: Building graphical interfaces with libraries like Tkinter.

Why Python?

Python stands out because:

  • Easy to read: Python's syntax is straightforward and looks similar to English.
  • Versatile: Python can be used across many domains, from web development to machine learning.
  • Large community: Python has a huge user base, offering plenty of tutorials, documentation, and libraries.

Python Syntax

Python syntax is simpler and more readable compared to languages like C++ or Java. It uses indentation instead of braces for defining code blocks, making the code clean and easy to follow.

Python Install

To get started with Python, you can download it from the official website python.org. Follow the installation instructions for your operating system (Windows, macOS, or Linux).

Python Version

After installation, you can check the installed Python version by running:

python
1 lines
|
4/ 500 tokens
1
python --version
Code Tools
Learn Python tutorial

The Python Command Line

You can run Python code directly in the command line or shell by typing python in your terminal or command prompt. This will open an interactive session where you can type Python commands and see immediate results.

Python Syntax

Python syntax is designed to be clean and easy to understand. For example, here’s a simple Python code to print "Hello, World!":

python
1 lines
|
6/ 500 tokens
1
print("Hello, World!")
Code Tools

Python Indentation

Python uses indentation to define blocks of code, rather than curly braces {} like other languages. Indentation must be consistent.

python
2 lines
|
12/ 500 tokens
1
2
if 5 > 2:
    print("Five is greater than two")
Code Tools

Python Comments

You can add comments in Python using the # symbol. Comments are ignored by the interpreter and are used to explain code:

python
2 lines
|
18/ 500 tokens
1
2
# This is a comment
print("Hello, World!")  # This will print a message
Code Tools

Python Variables

Variables in Python are used to store data values. You don’t need to declare the type of a variable; it is inferred from the value assigned to it.

Creating Variables

To create a variable, just assign a value to it:

python
2 lines
|
5/ 500 tokens
1
2
x = 5
y = "Hello"
Code Tools

Python Casting

You can explicitly convert (cast) variables from one type to another:

python
1 lines
|
10/ 500 tokens
1
x = int(5.5)  # Casts float to integer
Code Tools

Get the Type

You can check the type of a variable using the type() function:

python
2 lines
|
12/ 500 tokens
1
2
x = 5
print(type(x))  # Output: <class 'int'>
Code Tools

Single or Double Quotes?

Python allows both single (') and double (") quotes to define strings:

python
2 lines
|
6/ 500 tokens
1
2
x = 'Hello'
y = "World"
Code Tools

Case-Sensitive

Python is case-sensitive, which means myVar and myvar are considered different variables.

Variable Names

Variable names must start with a letter or an underscore, and can contain letters, digits, and underscores.

python
1 lines
|
3/ 500 tokens
1
my_var = 5
Code Tools

Multi-Word Variable Names

Camel Case

Each word after the first starts with a capital letter:

python
1 lines
|
8/ 500 tokens
1
myVariableName = "Camel Case"
Code Tools

Pascal Case

Each word starts with a capital letter:

python
1 lines
|
8/ 500 tokens
1
MyVariableName = "Pascal Case"
Code Tools

Snake Case

Words are separated by underscores:

python
1 lines
|
8/ 500 tokens
1
my_variable_name = "Snake Case"
Code Tools

Python Variables - Assign Multiple Values

You can assign multiple values to multiple variables in one line:

python
1 lines
|
5/ 500 tokens
1
x, y, z = 1, 2, 3
Code Tools

You can print variables by using the print() function:

python
2 lines
|
9/ 500 tokens
1
2
x = 5
print("The value of x is", x)
Code Tools

Global Variables

A global variable is declared outside of any function and can be accessed inside functions as well.

python
6 lines
|
20/ 500 tokens
1
2
3
4
5
6
x = "Global"

def my_function():
    print(x)

my_function()  # Output: Global
Code Tools

Python Data Types

Python has several built-in data types like integers, floats, strings, and more.

Built-in Data Types

Common Python data types include:

  • int for integers
  • float for floating-point numbers
  • str for strings
  • list for lists
  • dict for dictionaries

Getting the Data Type

Use type() to find the data type of any variable:

python
2 lines
|
12/ 500 tokens
1
2
x = 10
print(type(x))  # Output: <class 'int'>
Code Tools

Setting the Data Type

You can explicitly set data types using casting:

python
1 lines
|
11/ 500 tokens
1
x = str(10)  # Converts integer to string
Code Tools

Python Numbers

Python supports three types of numbers: integers (int), floating-point numbers (float), and complex numbers (complex).

Python Casting

Casting allows you to change the type of a variable:

python
1 lines
|
11/ 500 tokens
1
x = int("10")  # Converts string to integer
Code Tools

Python Strings

Strings in Python are sequences of characters enclosed in single or double quotes:

python
1 lines
|
3/ 500 tokens
1
x = "Hello"
Code Tools

Python - Slicing Strings

You can slice strings to extract parts of them:

python
2 lines
|
10/ 500 tokens
1
2
x = "Hello"
print(x[1:4])  # Output: ell
Code Tools

Python - Modify Strings

Strings can be modified using various methods:

python
2 lines
|
12/ 500 tokens
1
2
x = "hello"
print(x.upper())  # Output: HELLO
Code Tools

Python - String Concatenation

You can concatenate strings using the + operator:

python
3 lines
|
17/ 500 tokens
1
2
3
x = "Hello"
y = "World"
print(x + " " + y)  # Output: Hello World
Code Tools

Python - Format Strings

You can format strings using the format() method:

python
3 lines
|
22/ 500 tokens
1
2
3
age = 30
txt = "I am {} years old"
print(txt.format(age))  # Output: I am 30 years old
Code Tools

Python - Escape Characters

Escape characters like \n (new line) and \\ (backslash) are used to include special characters in strings:

python
2 lines
|
8/ 500 tokens
1
2
txt = "Hello\nWorld"
print(txt)
Code Tools

Python - String Methods

Python offers various string methods, such as strip(), replace(), and split():

python
2 lines
|
14/ 500 tokens
1
2
txt = " Hello "
print(txt.strip())  # Output: "Hello"
Code Tools

Python Booleans

Booleans represent one of two values: True or False. They are often used in conditional statements.

python
1 lines
|
2/ 500 tokens
1
x = True
Code Tools

Python Operators

Operators in Python are used to perform operations on variables and values, such as arithmetic (+, -, *, /), comparison (==, >, <), and logical (and, or, not) operators.

Python Lists

Lists are used to store multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.

python
1 lines
|
5/ 500 tokens
1
my_list = [1, 2, 3]
Code Tools

Python - Access List Items

You can access list items using their index:

python
1 lines
|
8/ 500 tokens
1
print(my_list[0])  # Output: 1
Code Tools

Python - Change List Items

Lists are mutable, meaning their items can be changed:

python
1 lines
|
4/ 500 tokens
1
my_list[1] = 10
Code Tools

Python - Add List Items

You can add items to a list using append() or insert():

python
1 lines
|
5/ 500 tokens
1
my_list.append(4)
Code Tools

Python - Remove List Items

You can remove items from a list using remove() or pop():

python
1 lines
|
5/ 500 tokens
1
my_list.remove(10)
Code Tools

Python - Loop Lists

You can loop through a list using a for loop:

python
2 lines
|
9/ 500 tokens
1
2
for item in my_list:
    print(item)
Code Tools

Python - List Comprehension

List comprehension is a concise way to create lists:

python
1 lines
|
9/ 500 tokens
1
squares = [x**2 for x in range(10)]
Code Tools

Python - Sort Lists

You can sort a list using sort():

python
1 lines
|
4/ 500 tokens
1
my_list.sort()
Code Tools

Python - Copy Lists

Lists can be copied using the copy() method or slicing:

python
1 lines
|
7/ 500 tokens
1
new_list = my_list.copy()
Code Tools

Python - Join Lists

You can join lists using the + operator:

python
3 lines
|
13/ 500 tokens
1
2
3
list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2
Code Tools

Python - List Methods

Python lists have many built-in methods like append(), extend(), index(), and count().

Python Tuples

Tuples are similar to lists but are immutable (unchangeable). They are defined by placing elements inside parentheses ():

python
1 lines
|
5/ 500 tokens
1
my_tuple = (1, 2, 3)
Code Tools

Python - Access Tuple Items

You can access tuple items by their index:

python
1 lines
|
5/ 500 tokens
1
print(my_tuple[0])
Code Tools

Python - Update Tuples

Tuples are immutable, but you can update them by converting them into a list and then back to a tuple.

python
3 lines
|
17/ 500 tokens
1
2
3
my_tuple = list(my_tuple)
my_tuple[0] = 4
my_tuple = tuple(my_tuple)
Code Tools

Python - Unpack Tuples

You can unpack a tuple into variables:

python
1 lines
|
5/ 500 tokens
1
x, y, z = my_tuple
Code Tools

Python - Loop Tuples

You can loop through tuples using a for loop:

python
2 lines
|
10/ 500 tokens
1
2
for item in my_tuple:
    print(item)
Code Tools

Python - Join Tuples

You can concatenate two tuples using the + operator:

python
3 lines
|
14/ 500 tokens
1
2
3
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
Code Tools

Python - Tuple Methods

Tuples only have two built-in methods: count() and index().

Python Sets

Sets are unordered collections of unique elements. They are defined using curly braces {}:

python
1 lines
|
5/ 500 tokens
1
my_set = {1, 2, 3}
Code Tools

Python - Access Set Items

You cannot access set items by index because sets are unordered. Instead, you can loop through the set:

python
2 lines
|
9/ 500 tokens
1
2
for item in my_set:
    print(item)
Code Tools

Python - Add Set Items

You can add items to a set using add():

python
1 lines
|
4/ 500 tokens
1
my_set.add(4)
Code Tools

Python - Remove Set Items

Items can be removed using remove() or discard():

python
1 lines
|
4/ 500 tokens
1
my_set.remove(2)
Code Tools

Python - Loop Sets

You can loop through sets using a for loop:

python
2 lines
|
9/ 500 tokens
1
2
for item in my_set:
    print(item)
Code Tools

Python Dictionaries

Dictionaries store data in key-value pairs and are defined using curly braces {}:

python
1 lines
|
10/ 500 tokens
1
my_dict = {"name": "John", "age": 30}
Code Tools

Python - Access Dictionary Items

You can access dictionary items by referring to their key:

python
1 lines
|
6/ 500 tokens
1
print(my_dict["name"])
Code Tools

Python - Change Dictionary Items

Dictionary values can be updated by referencing their key:

python
1 lines
|
5/ 500 tokens
1
my_dict["age"] = 31
Code Tools

Python - Add Dictionary Items

You can add new key-value pairs to a dictionary:

python
1 lines
|
8/ 500 tokens
1
my_dict["address"] = "New York"
Code Tools

Python - Remove Dictionary Items

Remove an item from a dictionary using pop() or del:

python
1 lines
|
5/ 500 tokens
1
my_dict.pop("age")
Code Tools

Python - Loop Dictionaries

You can loop through dictionary keys, values, or both:

python
2 lines
|
14/ 500 tokens
1
2
for key, value in my_dict.items():
    print(key, value)
Code Tools

Python - Copy Dictionaries

Dictionaries can be copied using the copy() method:

python
1 lines
|
7/ 500 tokens
1
new_dict = my_dict.copy()
Code Tools

Python - Nested Dictionaries

You can nest dictionaries inside dictionaries:

python
4 lines
|
25/ 500 tokens
1
2
3
4
my_family = {
    "child1": {"name": "John", "age": 10},
    "child2": {"name": "Jane", "age": 8}
}
Code Tools

Python If...Else

Python uses if, elif, and else for conditional statements:

python
4 lines
|
15/ 500 tokens
1
2
3
4
if x > 10:
    print("Greater")
else:
    print("Smaller")
Code Tools

Python While Loops

while loops execute a block of code as long as a condition is true:

python
4 lines
|
11/ 500 tokens
1
2
3
4
i = 1
while i < 5:
    print(i)
    i += 1
Code Tools

Python For Loops

for loops iterate over a sequence (like a list or a range):

python
2 lines
|
8/ 500 tokens
1
2
for i in range(5):
    print(i)
Code Tools

Python Functions

Functions are defined using the def keyword:

python
2 lines
|
14/ 500 tokens
1
2
def my_function():
    print("Hello from a function!")
Code Tools

Python Lambda

A lambda function is a small anonymous function:

python
2 lines
|
8/ 500 tokens
1
2
x = lambda a: a + 10
print(x(5))
Code Tools

Python Arrays

Arrays in Python can be created using the array module or with lists for simpler cases:

python
2 lines
|
14/ 500 tokens
1
2
import array as arr
my_array = arr.array('i', [1, 2, 3])
Code Tools

Python Classes/Objects

Classes are used to create objects. A class is like a blueprint for objects:

python
3 lines
|
18/ 500 tokens
1
2
3
class MyClass:
    def __init__(self, name):
        self.name = name
Code Tools

Python Inheritance

Inheritance allows one class to inherit methods and properties from another:

python
6 lines
|
25/ 500 tokens
1
2
3
4
5
6
class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    pass
Code Tools

Python Iterators

An iterator is an object that contains a countable number of values. Use iter() to create an iterator:

python
2 lines
|
12/ 500 tokens
1
2
my_iter = iter([1, 2, 3])
print(next(my_iter))
Code Tools

Python Polymorphism

Polymorphism allows functions to operate on different object types, like classes sharing the same method name:

python
7 lines
|
27/ 500 tokens
1
2
3
4
5
6
7
class Cat:
    def speak(self):
        return "Meow"

class Dog:
    def speak(self):
        return "Bark"
Code Tools

Python Scope

Variables have a scope that defines where they can be accessed. Python has local, global, and nonlocal scopes.

Python Modules

Modules allow you to break down large programs into smaller, manageable files. You can import them using import:

python
1 lines
|
3/ 500 tokens
1
import math
Code Tools

Python Dates

Python's datetime module allows you to work with dates and times:

python
2 lines
|
12/ 500 tokens
1
2
import datetime
print(datetime.datetime.now())
Code Tools

Python Math

The math module offers various mathematical functions:

python
2 lines
|
8/ 500 tokens
1
2
import math
print(math.sqrt(16))
Code Tools

Python JSON

Python provides methods for working with JSON data using the json module:

python
2 lines
|
14/ 500 tokens
1
2
import json
x = json.dumps({"name": "John", "age": 30})
Code Tools

Python RegEx

The re module in Python allows you to work with regular expressions:

python
4 lines
|
26/ 500 tokens
1
2
3
4
import re
pattern = r"\bword\b"
text = "This is a word in a sentence."
match = re.search(pattern, text)
Code Tools

Python PIP

PIP is a package manager for installing and managing Python libraries. You can install packages using pip install <package-name>.

Python Try...Except

try...except is used for error handling in Python:

python
4 lines
|
20/ 500 tokens
1
2
3
4
try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
Code Tools

Python User Input

You can get user input using the input() function:

python
2 lines
|
15/ 500 tokens
1
2
name = input("Enter your name: ")
print("Hello, " + name)
Code Tools

Python String Formatting

Python allows string formatting to include variables in strings:

python
4 lines
|
24/ 500 tokens
1
2
3
4
name = "John"
age = 30
txt = "My name is {} and I am {} years old"
print(txt.format(name, age))
Code Tools

Python File Handling

Python allows you to work with files. You can open, read, write, and delete files.

Python File Handling

You can open files using the open() function:

python
1 lines
|
8/ 500 tokens
1
file = open("filename.txt", "r")
Code Tools

Python Read Files

Read files using read() or readline():

python
2 lines
|
13/ 500 tokens
1
2
file = open("filename.txt", "r")
print(file.read())
Code Tools

Python Write/Create Files

Use write() or append() to write to a file:

python
2 lines
|
15/ 500 tokens
1
2
file = open("filename.txt", "w")
file.write("Hello, World!")
Code Tools

Python Delete Files

You can delete a file using the os.remove() method from the os module:

python
2 lines
|
9/ 500 tokens
1
2
import os
os.remove("filename.txt")
Code Tools

Frequently Asked Questions

Yes, Python is a beginner-friendly language with extensive online tutorials, documentation, and resources that make it easy to learn on your own. Many developers have successfully taught themselves Python through online courses, books, and practice.

You can learn the basics of Python in 7 days if you dedicate time daily. While you may not master it, you'll understand the fundamentals like syntax, variables, loops, and basic functions to start building simple programs.

The best Python tutorial depends on your learning style. Some popular options include the official Python documentation, interactive platforms like Codecademy, or video tutorials on YouTube or Coursera. Choose one that balances theory and practical coding exercises.

To learn basic Python, start with online tutorials or beginner courses, practice simple exercises like loops and functions, and build small projects. Interactive coding platforms like LeetCode and Hackerrank are great for practicing basic concepts.

Yes, Python is considered one of the easiest programming languages to learn due to its simple, readable syntax and large community support. It's beginner-friendly and widely used across various domains like web development, data science, and automation.

While you can grasp Python's basic syntax and structure in 3 days, mastering it and learning how to apply it effectively in projects or jobs will take more time and practice. Focus on learning basic concepts like variables, loops, and functions.

In 4 hours, you can learn some very basic Python concepts like printing output, working with variables, and using simple loops. However, becoming proficient in Python requires more in-depth practice over time.

Python alone can be enough to get a job, especially in fields like web development, data science, or automation. However, job requirements often include knowledge of related tools, libraries (like Django, NumPy, or pandas), and practical experience in solving real-world problems with Python.

Still have questions?Contact our support team

Related Articles

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.