Basics
| Command or syntax | What it does |
|---|---|
print("Hello") | Show output |
name = input("Name: ") | Read input as text |
x = 10 | Create a variable |
type(x) | Find the data type |
int("5"), float("2.5"), str(7) | Convert between types |
# comment | A comment line |
Data types and operators
| Command or syntax | What it does |
|---|---|
int, float, str, bool | Basic data types |
+ - * / // % ** | Arithmetic: divide, floor divide, remainder, power |
== != < > <= >= | Comparison |
and or not | Logical operators |
Strings
| Command or syntax | What it does |
|---|---|
s.upper(), s.lower() | Change case |
s.strip() | Remove spaces at both ends |
s.replace("a","b") | Replace text |
s.split(",") | Split into a list |
s[0], s[-1], s[1:4] | Index and slice |
len(s) | Length |
f"Hello {name}" | Insert variables in text |
Lists, tuples, sets, dictionaries
| Command or syntax | What it does |
|---|---|
a = [1,2,3] | List (changeable) |
a.append(4), a.remove(2), a.sort() | Common list methods |
t = (1,2,3) | Tuple (fixed) |
s = {1,2,3} | Set (no duplicates) |
d = {"name":"Anu"} | Dictionary |
d["name"], d.get("age") | Read a dictionary value |
d.keys(), d.values(), d.items() | Keys, values and pairs |
Decisions and loops
| Command or syntax | What it does |
|---|---|
if x > 0: ... elif x == 0: ... else: ... | Decision making |
for i in range(5): ... | Loop a fixed number of times |
while x < 5: ... | Loop while a condition is true |
break, continue | Leave a loop, skip to the next round |
[i*i for i in range(5)] | List comprehension |
Functions, files and errors
| Command or syntax | What it does |
|---|---|
def add(a, b): return a + b | Define a function |
lambda x: x*2 | A short anonymous function |
import math | Use a module |
open("a.txt","r") | Open a file for reading |
with open("a.txt") as f: f.read() | Read a file safely |
try: ... except Exception: ... | Handle errors |
class Student: ... | Define a class |
