Python Cheat Sheet

This cheat sheet is a valuable resource for anyone who wants to learn Python. It is a quick and easy way to learn about the most common Python syntax, functions, and concepts, and it can help you to develop efficient and powerful applications.

Python is a high-level programming language known for its simplicity and readability. It offers various features and libraries that make it suitable for multiple purposes, including web development, data analysis, machine learning, and more. By referring to a Python cheat sheet, you can quickly grasp the language's fundamental syntax, functions, and concepts. This will enable you to write clean and concise code, automate tasks, handle data, and build robust applications. Python's versatility and user-friendly nature make it an excellent choice for beginners and experienced developers.

Python Cheat Sheet

This cheat sheet is a valuable resource for anyone who wants to learn Python. It is a quick and easy way to learn about the most common Python syntax, functions, and concepts, and it can help you to develop efficient and powerful applications.

Python is a high-level programming language known for its simplicity and readability. It offers various features and libraries that make it suitable for multiple purposes, including web development, data analysis, machine learning, and more. By referring to a Python cheat sheet, you can quickly grasp the language's fundamental syntax, functions, and concepts. This will enable you to write clean and concise code, automate tasks, handle data, and build robust applications. Python's versatility and user-friendly nature make it an excellent choice for beginners and experienced developers.

Python quick reference cheat sheet

1. Variables and Data Types:

  • variable_name = value: Declare and assign a value to a variable.

  • int, float, str, bool: Data types for integers, floating-point numbers, strings, and booleans.

  • type(variable): Check the data type of a variable.

Example:

x = 5

name = "John"

is_true = True

 

print(type(x))    # Output: <class 'int'>

print(type(name)) # Output: <class 'str'>

print(type(is_true)) # Output: <class 'bool'>

2. Basic Input and Output:

  • print("text"): Display text or variable values.

  • input("prompt"): Accept user input.

Example:

name = input("Enter your name: ")

print("Hello, " + name + "!")

 

# Output:

# Enter your name: John

# Hello, John!

3. Operators:

  • Arithmetic Operators: +, -, *, /, //, %, **.

  • Assignment Operators: =, +=, -=, *=, /=, //=, %=, **=.

  • Comparison Operators: ==, !=, >, <, >=, <=.

  • Logical Operators: and, or, not.

Example:

x = 5 + 3

y = x * 2

z = y > 10 and x < 5

 

print(x) # Output: 8

print(y) # Output: 16

print(z) # Output: False

4. Conditional Statements:

  • if statement: Execute a block of code if a condition is true.

  • elif statement: Execute a block of code if the previous condition(s) are false and this condition is true.

  • else statement: Execute a block of code if all previous conditions are false.

  • ==, !=, >, <, >=, <=: Comparison operators used in conditions.

Example:

age = 18

 if age >= 18:

    print("You are an adult.")

elif age >= 13:

    print("You are a teenager.")

else:

    print("You are a child.")

# Output: You are an adult.

5. Loops:

  • for loop: Execute a block of code a specific number of times.

  • while loop: Execute a block of code as long as a condition is true.

  • range(start, stop, step): Generate a sequence of numbers.

  • break: Exit the loop prematurely.

  • continue: Skip the current iteration and move to the next one.

Example:

# for loop

for i in range(1, 6):

    print(i)

# Output: 1 2 3 4 5

 

# while loop

count = 0

while count < 5:

    print(count)

    count += 1

# Output: 0 1 2 3 4

6. Lists:

  • my_list = [item1, item2, item3]: Create a list.

  • len(my_list): Get the length of a list.

    • index = my_list.index(item): Find the index of an item in a list.

    • my_list.append(item): Add an item to the end of a list.

    • my_list.insert(index, item): Insert an item at a specific index in a list.

    • my_list.pop(): Remove and return the last item from a list.

    • my_list.remove(item): Remove the first occurrence of an item from a list.

Example:

numbers = [1, 2, 3, 4, 5]

 

print(len(numbers))  # Output: 5

print(numbers.index(3))  # Output: 2

 

numbers.append(6)

print(numbers)  # Output: [1, 2, 3, 4, 5, 6]

 

numbers.insert(2, 10)

print(numbers)  # Output: [1, 2, 10, 3, 4, 5, 6]

 

last_item = numbers.pop()

print(last_item)  # Output: 6

print(numbers)  # Output: [1, 2, 10, 3, 4, 5]

 

numbers.remove(3)

print(numbers)  # Output: [1, 2, 10, 4, 5]

7. Strings:

  • my_string = "text": Create a string.

  • len(my_string): Get the length of a string.

  • my_string.upper(): Convert a string to uppercase.

  • my_string.lower(): Convert a string to lowercase.

  • my_string.strip(): Remove leading and trailing whitespace.

  • my_string.split(separator): Split a string into a list of substrings.

  • my_string.replace(old, new): Replace occurrences of a substring in a string.

Example:

message = "Hello, World!"

 

print(len(message))  # Output: 13

print(message.upper())  # Output: HELLO, WORLD!

print(message.lower())  # Output: hello, world!

 

name = "   John   "

print(name.strip())  # Output: John

 

sentence = "I love Python programming"

words = sentence.split(" ")

print(words)  # Output: ['I', 'love', 'Python', 'programming']

 

replaced = sentence.replace("Python", "JavaScript")

print(replaced)  # Output: I love JavaScript programming

8. Functions:

  • def function_name(parameters): Declare a function.

  • return value: Return a value from a function.

  • function_name(arguments): Call a function with arguments.

Example:

def greet(name):

    return "Hello, " + name + "!"

 

message = greet("John")

print(message)  # Output: Hello, John!

9. File Handling:

  • open(filename, mode): Open a file.

  • file.read(): Read the contents of a file.

  • file.write(text): Write text to a file.

  • file.close(): Close a file.

Example:

# Open a file in read mode

file = open("data.txt", "r")

contents = file.read()

print(contents)

file.close()

 

# Open a file in write mode

file = open("output.txt",

10. Modules for File Operations:

  • os: Module for interacting with the operating system.

    • os.getcwd(): Get the current working directory.

    • os.listdir(path): Get a list of files and directories in a given path.

    • os.path.join(path, filename): Join a path and a filename to create a file path.

  • shutil: Module for high-level file operations.

    • shutil.copy(source, destination): Copy a file from source to destination.

    • shutil.move(source, destination): Move or rename a file.

Example:

import os

import shutil

 

current_dir = os.getcwd()

print(current_dir)  # Output: Current working directory

 

files = os.listdir(current_dir)

print(files)  # Output: List of files and directories in the current directory

 

file_path = os.path.join(current_dir, "file.txt")

print(file_path)  # Output: Full file path

 

shutil.copy("source.txt", "destination.txt")  # Copy file from source to destination

shutil.move("old.txt", "new.txt")  # Move or rename a file

11. Virtual Environments:

  • python -m venv env_name: Create a virtual environment.

  • source env_name/bin/activate (Linux/Mac) or .\env_name\Scripts\activate (Windows): Activate a virtual environment.

  • deactivate: Deactivate the current virtual environment.

Example:

python -m venv myenv  # Create a virtual environment

source myenv/bin/activate  # Activate the virtual environment

# Your Python environment is now isolated within the virtual environment

deactivate  # Deactivate the virtual environment

12. Working with Dates and Times:

  • datetime: Module for working with dates and times.

    • datetime.now(): Get the current date and time.

    • datetime.date(): Get the current date.

    • datetime.time(): Get the current time.

Example:

from datetime import datetime

 

current_datetime = datetime.now()

print(current_datetime)  # Output: Current date and time

 

current_date = datetime.date()

print(current_date)  # Output: Current date

 

current_time = datetime.time()

print(current_time)  # Output: Current time

Learn more Python skills on Coursera.

Python CoursesOpens in a new tab | Data Science CoursesOpens in a new tab | Machine Learning CoursesOpens in a new tab | Web Scraping CoursesOpens in a new tab | Programming Fundamentals CoursesOpens in a new tab | Data Analysis CoursesOpens in a new tab | Web Development CoursesOpens in a new tab | Deep Learning CoursesOpens in a new tab | Artificial Intelligence CoursesOpens in a new tab

CommunityJoin a community of over 100 million learners from around the world
CertificateLearn from more than 200 leading universities and industry educators.
Confidence70% of all learners who have stated a career goal and completed a course report outcomes such as gaining confidence, improving work performance, or selecting a new career path.
All courses include:
  • 100% online
  • Flexible schedule
  • Mobile learning
  • Videos and readings from professors at world-renowned universities and industry leaders
  • Practice quizzes

Can’t decide what is right for you?

Try the full learning experience for most courses free for 7 days.

Register to learn with Coursera’s community of 87 million learners around the world