Python Basics Cheat Sheet
Variables, types, operators, strings, conditions, loops, and functions at a glance.
Updated
Variables and types#
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#
Strings#
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#
answer = input("Your name: ") # always returns a str
age = int(input("Your age: "))
print("Hello", name, sep=" ", end="\n")Conditions#
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
status = "adult" if age >= 18 else "minor"Loops#
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 iterationLists#
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#
def greet(name, greeting="Hello"):
"""Return a greeting."""
return f"{greeting}, {name}!"
greet("Ravi") # 'Hello, Ravi!'
greet(greeting="Hi", name="Ravi")Common errors#
Want the full explanations? Go to the Learn Python course →