Skip to content
Laviyx Learn

Try

Python Basics Cheat Sheet

Variables, types, operators, strings, conditions, loops, and functions at a glance.

Updated

Variables and types#

Python
name = "Asha"        # str
age = 21             # int
height = 1.62        # float
is_member = True     # bool
nickname = None      # no value

type(age)            # <class 'int'>
int("42"), float("3.5"), str(10), bool(0)

Operators#

KindOperators
Arithmetic+ - * / (float) // (floor) % (remainder) ** (power)
Comparison== != > < >= <=
Logicaland or not
Membershipin, not in
Identityis, is not (use for None)
Assignment= += -= *= /=

Strings#

Python
s = "Python"
len(s)                # 6
s[0], s[-1]           # 'P', 'n'
s[1:4]                # 'yth'
s.upper(), s.lower()
s.replace("Py", "Jy")
"a,b,c".split(",")    # ['a', 'b', 'c']
", ".join(["a", "b"]) # 'a, b'
f"{name} is {age}"    # f-string
f"{3.14159:.2f}"      # '3.14'

Input and output#

Python
answer = input("Your name: ")   # always returns a str
age = int(input("Your age: "))
print("Hello", name, sep=" ", end="\n")

Conditions#

Python
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"

status = "adult" if age >= 18 else "minor"

Loops#

Python
for item in items:            # each item
    ...

for i in range(5):            # 0, 1, 2, 3, 4
    ...

for i, item in enumerate(items, start=1):
    ...

while count < 10:
    count += 1

break      # leave the loop
continue   # skip to the next iteration

Lists#

Python
nums = [3, 1, 2]
nums.append(4)       # add to end
nums.insert(0, 9)    # add at index
nums.remove(1)       # remove a value
nums.pop()           # remove + return last
nums.sort()          # in place, returns None
sorted(nums)         # new sorted list
len(nums), sum(nums), min(nums), max(nums)
squares = [n * n for n in nums]

Functions#

Python
def greet(name, greeting="Hello"):
    """Return a greeting."""
    return f"{greeting}, {name}!"

greet("Ravi")                    # 'Hello, Ravi!'
greet(greeting="Hi", name="Ravi")

Common errors#

ErrorUsual cause
SyntaxErrormissing colon, quote, or bracket
IndentationErrorinconsistent or unexpected indentation
NameErrorvariable used before it is defined, or a typo
TypeErrormixing types, e.g. "Age: " + 21
IndexErrorlist index past the end
KeyErrordictionary key that does not exist
ValueErrorright type, wrong value, e.g. int("abc")

Want the full explanations? Go to the Learn Python course →