Variables and types
name = "Asha" # str
age = 25 # int
price = 99.5 # float
active = True # bool
nothing = None
print(type(age)) # <class 'int'>
Strings
s = "Hello, World"
s.lower() # 'hello, world'
s.split(", ") # ['Hello', 'World']
s.replace("World", "Python")
f"{name} is {age}" # f-string
s[0:5] # 'Hello'
len(s)
Lists, tuples, sets and dictionaries
nums = [3, 1, 2]
nums.append(4)
nums.sort() # in place
sorted(nums, reverse=True) # a new list
point = (10, 20) # tuple: cannot change
unique = {1, 2, 2, 3} # set: {1, 2, 3}
user = {"name": "Asha", "age": 25}
user["city"] = "Pune"
user.get("phone", "none") # safe lookup
Loops and conditions
for n in [1, 2, 3]:
print(n)
for i in range(5): # 0 to 4
print(i)
while age < 30:
age += 1
if age > 18 and active:
print("adult")
elif age == 18:
print("just 18")
else:
print("minor")
squares = [n * n for n in range(5)] # list comprehension
Functions
def add(a, b=0):
return a + b
add(2, 3) # 5
add(2) # 2
Files and JSON
with open("data.txt", "r", encoding="utf-8") as f:
text = f.read()
import json
data = json.loads('{"a": 1}')
print(json.dumps(data, indent=2))
Common mistakes
- Indentation matters. Use four spaces, and do not mix tabs and spaces.
= assigns and == compares.
- Lists are changed in place, so copy with
list(items) when you need a separate one.
- Do not name a variable
list, str or dict, since that hides the built-in.