Your Ultimate Python 3 Cheat Sheet for Quick Reference

Are you new to Python programming or just need a handy reference guide? Look no further! In this blog post, we’ve compiled a comprehensive Python 3 cheat sheet that covers the essential concepts, syntax, and techniques to help you navigate the world of Python programming. Whether you’re a beginner or an experienced developer, this cheat sheet will serve as a quick and informative reference.

Python Basics

Comments

Let’s start with comments, single line comment as shown below:

# This is a single-line comment

Multiline comment as shown below :

'''
This is a
multi-line
comment
'''

Print

print(“Hello, World!”)

Variables

variable_name = value

Example :

age = 25
name = "Tom"

Here age and name are variables. Python variables are dynamically typed, so they can hold any type of data.

Data Types

Python 3 has following data types:

  • int: integers
  • float: floating-point numbers
  • str: strings
  • bool: boolean values (True/False)

  • list: ordered collection of elements
  • tuple: ordered, immutable collection of elements
  • dict: key-value pairs
  • set: unordered collection of unique elements

Control Flow

Conditional Statements

if condition:
    # code
elif another_condition:
    # code
else:
    # code

Loops

Python 3 supports the following loops.

For loop

for item in iterable:
    # code

While Loop

while condition:
    if some_condition:
        break
    elif another_condition:
        continue

Learn more about Python loop syntax

Functions

Defining Functions

def function_name(parameters):
    # code
    return result

Lambda Functions

Lambda functions are anonymous functions created using the lambda keyword.

lambda arguments: expression

Example :

lambda x, y: x + y

Scope

  • Variables defined within a function are local to that function.
  • Variables defined outside functions are global.

Data Structures

Lists

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

Tuples

days= ("Sunday", "Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday")

Dictionaries

my_dict = {
    'key1': 'value1',
    'key2': 'value2'
}

Example :

person = {
'name': 'Tom',
'age': 30
}

Sets

my_set = {item1, item2, item3}

Example :

my_set = {1, 2, 3} 

File Handling

Opening Files

file = open('filename.txt', 'mode')

Modes :

  • 'r': Read
  • 'w': Write (creates a new file or truncates an existing one)
  • 'a': Append
  • 'b': Binary mode
  • 'x': Exclusive creation (fails if file already exists)

Reading from a File

content = file.read()

Writing to a File

file.write("Hello, File!")

Exception Handling

Try-Except Blocks

try:
    # code
except SomeException:
    # code
else:
    # code (runs if no exception)
finally:
    # code (always runs)

Raising Exceptions

raise SomeException("An error occurred")

Modules

Importing Modules

import module_name
from module_name import some_function

Creating Modules

  • Create a .py file and define functions and variables.
  • Use import to use the module in other scripts.

Object-Oriented Programming

Classes and Objects

class MyClass:
    def __init__(self, param):
        self.attribute = param
    def some_method(self):
        # code

Inheritance

class ChildClass(ParentClass):
    # code

Useful Built-in Functions

  • len(iterable): Returns the number of items in an iterable.
  • range(start, stop, step): Generates a sequence of numbers.
  • type(object): Returns the type of an object.
  • str(object): Converts an object to a string.

Virtual Environment

Creating a Virtual Environment

python3 -m venv env_name

Activating a Virtual Environment

  • Windows: env_name\Scripts\activate
  • Linux/Mac: source env_name/bin/activate

Useful Libraries (Install with pip)

  • NumPy: Numerical computing library.
  • Pandas: Data manipulation and analysis library.
  • Matplotlib: Data visualization library.
  • Requests: HTTP library for making API requests.
  • Beautiful Soup: HTML parsing library.
  • SQLAlchemy: SQL toolkit and Object-Relational Mapping (ORM) library.

Remember, this cheat sheet is designed to provide a quick overview of Python 3 concepts and syntax. For more detailed explanations and examples, be sure to refer to the official Python documentation and other learning resources. Happy coding!