Skip to content

python-beginner-help/python-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

Python Beginner Help

Python Cheatsheet 🐍

A one-page quick reference for Python basics. Each section links to a full beginner tutorial on pythonbeginner.help.

Bookmark this page. When you need the why behind a snippet, follow the Learn more → link.

Contents

Variables & Types

name = "Ada"        # str
age = 36            # int
height = 1.7        # float
is_admin = True     # bool
nothing = None      # NoneType

type(age)           # <class 'int'>
int("42")           # 42   (string -> int)
str(42)             # "42"

Learn more → Variables · Data Types

Strings

s = "hello world"
len(s)              # 11
s.upper()           # "HELLO WORLD"
s.title()           # "Hello World"
s.replace("o","0")  # "hell0 w0rld"
s.split()           # ["hello", "world"]
"world" in s        # True
s[0]                # "h"      (indexing)
s[0:5]              # "hello"  (slicing)
f"{name} is {age}"  # f-string formatting

Learn more → Strings · Check for a substring

Numbers & Math

7 + 2   # 9      7 - 2   # 5
7 * 2   # 14     7 / 2   # 3.5  (float)
7 // 2  # 3      (floor division)
7 % 2   # 1      (remainder)
2 ** 8  # 256    (power)
abs(-5) # 5      round(3.14159, 2)  # 3.14

Learn more → Numbers · abs()

Lists

nums = [3, 1, 2]
nums.append(4)      # [3, 1, 2, 4]
nums.insert(0, 9)   # [9, 3, 1, 2, 4]
nums.pop()          # removes & returns last
nums.sort()         # sorts in place (returns None!)
sorted(nums)        # returns a new sorted list
len(nums)           # length
nums[0], nums[-1]   # first, last
nums[1:3]           # slice
[x * 2 for x in nums]   # list comprehension

Learn more → Lists · Add an item

Tuples & Sets

point = (3, 4)      # tuple: immutable
x, y = point        # unpacking

unique = {1, 2, 2, 3}   # set -> {1, 2, 3}
unique.add(4)
2 in unique             # True

Learn more → Tuples · Sets · Which to use

Dictionaries

user = {"name": "Ada", "age": 36}
user["name"]            # "Ada"
user.get("email")       # None (no crash)
user.get("email", "-")  # default value
user["email"] = "a@b.c" # add / update
"age" in user           # True
for k, v in user.items():
    print(k, v)

Learn more → Dictionaries · dict.get() · Check if a key exists

Conditionals

if age >= 18:
    print("adult")
elif age >= 13:
    print("teen")
else:
    print("child")

label = "even" if n % 2 == 0 else "odd"   # ternary

Learn more → if / elif / else

Loops

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

for item in ["a", "b"]:
    print(item)

for i, item in enumerate(["a", "b"]):
    print(i, item)          # 0 a / 1 b

n = 3
while n > 0:
    print(n)
    n -= 1

# break / continue control the loop

Learn more → for loops · while loops · enumerate()

Functions

def greet(name, greeting="Hi"):
    return f"{greeting}, {name}!"

greet("Ada")              # "Hi, Ada!"
greet("Ada", "Hello")     # "Hello, Ada!"
greet(name="Ada")         # keyword argument

square = lambda x: x * x  # lambda (anonymous)

Learn more → Functions · Default & keyword args

Files

with open("data.txt") as f:       # read
    text = f.read()

with open("out.txt", "w") as f:   # write (overwrite)
    f.write("hello")

with open("log.txt", "a") as f:   # append
    f.write("line\n")

Learn more → File handling · Append to a file · Check if a file exists

Errors

try:
    value = int(user_input)
except ValueError:
    print("Not a number")
else:
    print("Got", value)
finally:
    print("Done")

Learn more → try / except · Common errors & fixes


📚 Full tutorials: pythonbeginner.help · 🏋️ Practice: python-beginner-exercises

Released under CC0 1.0 by pythonbeginner.help.

About

A beginner-friendly one-page Python syntax cheatsheet. Powered by pythonbeginner.help

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors