Quick answer: For placement revision, Python basics come down to eight areas: data types and operators, strings, lists, tuples, sets and dictionaries, conditions and loops, functions, comprehensions, classes, and exceptions. Learn which types can change, what each common method returns, and the classic output traps. This cheat sheet puts all of them on one page.
This Python basics cheat sheet is for the days before a campus test or interview. It gives you the rule, a tiny example and the result, with no long theory. It works best if you have already studied the topics once.
If something here is new, learn it slowly in our Python basics tutorial and then come back. All examples use Python 3.
Python basics cheat sheet: types and operators
| Type | Example | Can it change? | Ordered? |
|---|---|---|---|
int |
42 |
No | Not applicable |
float |
3.5 |
No | Not applicable |
bool |
True |
No | Not applicable |
str |
"python" |
No | Yes |
list |
[1, 2, 2] |
Yes | Yes |
tuple |
(1, 2) |
No | Yes |
set |
{1, 2} |
Yes | No |
dict |
{"a": 1} |
Yes | Keeps insertion order |
NoneType |
None |
No | Not applicable |
"Mutable" means it can change. "Immutable" means it cannot.
| Expression | Result | Why |
|---|---|---|
7 / 2 |
3.5 |
/ always gives a float here |
7 // 2 |
3 |
Floor division |
-7 // 2 |
-4 |
Floor goes down, not towards zero |
7 % 2 |
1 |
Remainder |
2 ** 3 |
8 |
Power |
10 > 5 > 2 |
True |
Chained comparison |
"" or "guest" |
'guest' |
Empty string counts as false |
5 and 0 |
0 |
and returns the first false value |
Values that count as false: False, None, 0, 0.0, "", [], (), {} and set().
Interview note:
==compares values.ischecks if two names point to the same object. UseisforNone, as inif x is None.
Strings
For s = "Python":
| Code | Result |
|---|---|
s[0] |
'P' |
s[-1] |
'n' |
s[1:4] |
'yth' (stops before index 4) |
s[::-1] |
'nohtyP' |
len(s) |
6 |
s.upper() |
'PYTHON' |
s.find("z") |
-1 (not found) |
s.replace("P", "J") |
'Jython' |
"a,b".split(",") |
['a', 'b'] |
"-".join(["a", "b"]) |
'a-b' |
" hi ".strip() |
'hi' |
String methods return a new string. They never change the old one.
name = "Asha"
marks = 86.456
print(f"{name} scored {marks:.1f}")
# Asha scored 86.5
Lists, tuples, sets and dictionaries
| List task | Code | Note |
|---|---|---|
| Add at end | a.append(x) |
Adds one item |
| Add many | a.extend([x, y]) |
Adds each item |
| Insert | a.insert(0, x) |
At an index |
| Remove by value | a.remove(x) |
First match only |
| Remove by index | a.pop(i) |
Returns the item |
| Sort in place | a.sort() |
Returns None |
| Sorted copy | sorted(a) |
Returns a new list |
| Copy | a.copy() or a[:] |
Shallow copy |
| Dictionary task | Code |
|---|---|
| Read safely | d.get("key", 0) |
| Add or update | d["key"] = 5 |
| Delete | del d["key"] |
| Loop over pairs | for k, v in d.items(): |
| Check a key | "key" in d |
| Set task | Code | For a={1,2}, b={2,3} |
|---|---|---|
| Union | a | b |
{1, 2, 3} |
| Intersection | a & b |
{2} |
| Difference | a - b |
{1} |
Common mistake: Writing
x = {}to make an empty set. That makes an empty dictionary. Useset(). Also,(5)is only the number 5. A one-item tuple needs a comma:(5,).
Conditions, loops and comprehensions
for i in range(1, 6):
if i == 2:
continue # skip 2
if i == 5:
break # stop the loop
print(i, end=" ")
# 1 3 4
| Code | Gives |
|---|---|
list(range(4)) |
[0, 1, 2, 3] |
list(range(2, 8, 2)) |
[2, 4, 6] |
list(range(3, 0, -1)) |
[3, 2, 1] |
[n * n for n in range(4)] |
[0, 1, 4, 9] |
[n for n in range(6) if n % 2 == 0] |
[0, 2, 4] |
{w: len(w) for w in ["hi", "sun"]} |
{'hi': 2, 'sun': 3} |
list(enumerate(["a", "b"])) |
[(0, 'a'), (1, 'b')] |
list(zip([1, 2], ["x", "y"])) |
[(1, 'x'), (2, 'y')] |
A loop's else block runs only if the loop did not stop with break.
Functions
def total(a, b=10, *args, **kwargs):
return a + b + sum(args)
print(total(5)) # 15
print(total(5, 1)) # 6
print(total(1, 2, 3, 4)) # 10
| Term | Meaning |
|---|---|
| Parameter | The name in the function definition |
| Argument | The value you pass in |
| Default | Used when no value is passed |
*args |
Extra positional values, as a tuple |
**kwargs |
Extra named values, as a dictionary |
lambda x: x * 2 |
A small one-line function |
No return |
The function returns None |
The default list trap: a default value is made only once, when the function is defined.
def add(item, box=[]):
box.append(item)
return box
print(add(1)) # [1]
print(add(2)) # [1, 2]
The same list is used again in the second call. The fix is box=None, then create a new list inside if box is None.
Classes, errors and files
class Student:
college = "ABC" # shared by all objects
def __init__(self, name):
self.name = name # belongs to one object
class Topper(Student):
def greet(self):
return f"{self.name} from {self.college}"
print(Topper("Ravi").greet()) # Ravi from ABC
| OOP idea | One-line meaning |
|---|---|
| Class and object | The plan, and a thing made from it |
| Encapsulation | Keep data and methods together, limit direct access |
| Inheritance | A child class reuses a parent class |
| Polymorphism | Same method name, different behaviour |
| Abstraction | Show what it does, hide how |
try:
n = int("abc")
except ValueError:
print("Not a number")
else:
print("OK")
finally:
print("Done")
# Not a number
# Done
| Error | Usual cause |
|---|---|
NameError |
Name not defined |
TypeError |
Wrong type, as in "5" + 2 |
ValueError |
Right type, bad value, as in int("x") |
IndexError |
List index too large |
KeyError |
Dictionary key missing |
IndentationError |
Wrong spaces at line start |
Read a file safely with with open("data.txt") as f:. The file closes by itself when the block ends.
Output traps to test yourself
Cover the right column and guess.
| Code | Output | Reason |
|---|---|---|
print("5" * 3) |
555 |
String is repeated |
print(bool("False")) |
True |
Any non-empty string is true |
print([1, 2] + [3]) |
[1, 2, 3] |
Lists are joined |
print(True + True) |
2 |
True acts as 1 |
print(0.1 + 0.2 == 0.3) |
False |
Floats are not exact |
print(len({1, 1, 2})) |
2 |
A set drops repeats |
print([3, 1].sort()) |
None |
sort changes the list itself |
One more favourite:
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
b = a does not copy the list. Both names point to one list.
Pro tip: In an output question, say your reason aloud before your answer. A clear reason often earns credit even if you slip on the final value.
Python basics quick revision plan
Use these Python basics notes over three days:
- Day 1: types, operators and strings. Write ten tiny programs.
- Day 2: collections, loops and functions. Solve the Python basics practice problems.
- Day 3: classes, errors and output traps. Then answer ten questions aloud.
If you want a Python basics PDF for offline study, print this page from your browser and choose "Save as PDF". Analyst candidates can also try Python interview questions for analysts.
After basics comes project work. Our Python full stack course guide shows how Python connects to Django, SQL and React. In the Python Full Stack with AI course, you practise these ideas across six projects.
Frequently asked questions
Is there a Python basics PDF I can download here?
There is no separate PDF of this page. You can use the print option in your browser and save the page as a PDF. The tables are short enough to read on a phone too.
What Python topics are asked most in fresher interviews?
Expect list vs tuple, mutable vs immutable types, == vs is, dictionary methods, slicing, comprehensions, functions with default values, OOP basics and exception handling. You may also get small output questions.
How many days do I need to revise Python basics?
If you have already learned them, three to five days is usually enough for a full revision with small programs. If the topics are new, take a tutorial first and give yourself a few weeks.
What is the difference between a list and a tuple?
A list can be changed after you create it, and a tuple cannot. Use a list for data that grows or changes, and a tuple for a fixed group of values. A tuple can be a dictionary key if all its items are hashable.
How should I use this cheat sheet?
Cover the result column, guess each answer, and then check. Type the snippets yourself instead of only reading them. Mark every wrong guess and return to it the next day.
Ready to use Python in real projects? Book a free demo class and see how CodeBegun teaches Python in batches of up to 27, in Madhapur or live online.
