Python Cheat Sheet: Basic Syntax and Commands for Beginners

Python cheat sheet for beginners: variables, data types, strings, lists, dictionaries, loops, functions, files and error handling.

This one-page Python cheat sheet lists the syntax you use most. Copy the examples into Python and change them to learn by doing.

On this page (6 sections)
  1. Basics
  2. Data types and operators
  3. Strings
  4. Lists, tuples, sets, dictionaries
  5. Decisions and loops
  6. Functions, files and errors

Basics

Command or syntaxWhat it does
print("Hello")Show output
name = input("Name: ")Read input as text
x = 10Create a variable
type(x)Find the data type
int("5"), float("2.5"), str(7)Convert between types
# commentA comment line

Data types and operators

Command or syntaxWhat it does
int, float, str, boolBasic data types
+ - * / // % **Arithmetic: divide, floor divide, remainder, power
== != < > <= >=Comparison
and or notLogical operators

Strings

Command or syntaxWhat it does
s.upper(), s.lower()Change case
s.strip()Remove spaces at both ends
s.replace("a","b")Replace text
s.split(",")Split into a list
s[0], s[-1], s[1:4]Index and slice
len(s)Length
f"Hello {name}"Insert variables in text

Lists, tuples, sets, dictionaries

Command or syntaxWhat it does
a = [1,2,3]List (changeable)
a.append(4), a.remove(2), a.sort()Common list methods
t = (1,2,3)Tuple (fixed)
s = {1,2,3}Set (no duplicates)
d = {"name":"Anu"}Dictionary
d["name"], d.get("age")Read a dictionary value
d.keys(), d.values(), d.items()Keys, values and pairs

Decisions and loops

Command or syntaxWhat it does
if x > 0: ... elif x == 0: ... else: ...Decision making
for i in range(5): ...Loop a fixed number of times
while x < 5: ...Loop while a condition is true
break, continueLeave a loop, skip to the next round
[i*i for i in range(5)]List comprehension

Functions, files and errors

Command or syntaxWhat it does
def add(a, b): return a + bDefine a function
lambda x: x*2A short anonymous function
import mathUse a module
open("a.txt","r")Open a file for reading
with open("a.txt") as f: f.read()Read a file safely
try: ... except Exception: ...Handle errors
class Student: ...Define a class

Frequently asked questions

Is Python good for beginners?

Yes. Python has simple, readable syntax, so beginners can start writing useful programs quickly.

How do I take input in Python?

Use the input() function, for example name = input("Name: ").

What is the difference between a list and a tuple?

A list can be changed after it is created. A tuple cannot.

Test yourself

All Python tests

Learn step by step

Learn it in a course

More quick guides

WhatsApp us