- Published on
Python Cheat Sheet
Table of Contents
credit to https://quickref.me/python credit to https://learnxinyminutes.com/docs/python/
================================
Basic Syntax
- Comments:
# This is a comment
- Indentation: Use 4 spaces (not tabs) for each level of indentation.
- Variables:
- Naming: Start with a letter or underscore, case-sensitive (e.g.,
my_variable = 5
). - Types: Dynamically typed (inferred from the value).
- Naming: Start with a letter or underscore, case-sensitive (e.g.,
Data Types
- Numbers:
int
(integer),float
(floating-point),complex
- Strings:
'single quotes'
or"double quotes"
- Lists:
[1, 2, 'apple']
(ordered, mutable) - Tuples:
(1, 2, 'banana')
(ordered, immutable) - Dictionaries:
{'key': 'value'}
(unordered, mutable) - Sets:
{1, 2, 3}
(unordered, unique elements) - Booleans:
True
,False
Operators
- Arithmetic:
+
,-
,*
,/
,//
(floor division),%
(modulo),**
(exponentiation) - Comparison:
==
,!=
,<
,>
,<=
,>=
- Logical:
and
,or
,not
- Assignment:
=
,+=
,-=
,*=
, etc. - Membership:
in
,not in
- Identity:
is
,is not
Control Flow
Conditional Statements:
if condition: # code block elif another_condition: # code block else: # code block
Loops:
for item in iterable: # code block while condition: # code block
Functions
def function_name(parameters):
# function body
return value # optional
Modules
- Import standard library modules:
import math
,import random
, etc. - Import external modules:
pip install module_name
Classes
class MyClass:
def __init__(self, parameters):
# constructor
self.attribute = value
def method_name(self):
# method body
Error Handling
try:
# code that might raise an error
except ExceptionType:
# code to handle the error
finally:
# code that always executes
File I/O
with open('filename.txt', 'r') as file:
data = file.read() # 'w' for writing, 'a' for appending
- Automate the Boring Stuff with Python
- The Official Docs
- Hitchhiker’s Guide to Python
- Python Course
- First Steps With Python
- A curated list of awesome Python frameworks, libraries and software
- Official Style Guide for Python
- Python 3 Computer Science Circles
- Dive Into Python 3
- Python Tutorial for Intermediates
- Build a Desktop App with Python
Resources
- Python Cheatsheet: https://www.pythoncheatsheet.org/
- Python Cheat Sheet for Beginners: https://www.datacamp.com/cheat-sheet/getting-started-with-python-cheat-sheet
- Beginner's Python Cheat Sheets: https://www.reddit.com/r/learnpython/comments/11eg5af/beginners_python_cheat_sheets_updated/