| Concept | Syntax | Example |
|---|---|---|
| Comments | # comment | # This is a comment |
| Print Statement | print(value) | print("Hello World") |
| Input Statement | input(prompt) | name = input("Enter name: ") | Multi-line Comment | """ comment """ | """This is a multi-line comment""" |
| Type | Example | Description |
|---|---|---|
| int | x = 10 | Integer number |
| float | y = 3.14 | Floating point number |
| str | name = "Python" | String of characters |
| bool | flag = True | Boolean value (True/False) |
| list | items = [1, 2, 3] | Ordered, mutable collection |
| tuple | point = (1, 2) | Ordered, immutable collection |
| dict | person = {"name": "John"} | Key-value pairs |
| set | unique = {1, 2, 3} | Unordered unique items |
| Category | Operator | Example | Description |
|---|---|---|---|
| Arithmetic | + - * / // % ** | 5 + 3 = 8 | Addition, Subtraction, Multiplication, Division, Floor Division, Modulus, Exponentiation |
| Comparison | == != < > <= >= | 5 == 5 is True | Equality, Inequality, Less/Greater than, etc. |
| Logical | and or not | True and False is False | Logical AND, OR, NOT |
| Assignment | = += -= *= /= //= %= **= &= |= ^= >>= <<= | x += 5 | Assignment operators |
| Membership | in not in | 3 in [1,2,3] is True | Check if value is in sequence |
| Identity | is is not | x is y | Check if objects are identical |
| Structure | Syntax | Example |
|---|---|---|
| If Statement | if condition: statement | if x > 0: print("Positive") |
| If-Elif-Else | if c1: s1 elif c2: s2 else: s3 | if x > 0: print("Pos") elif x == 0: print("Zero") else: print("Neg") |
| For Loop | for item in iterable: statement | for i in range(5): print(i) |
| While Loop | while condition: statement | while x > 0: x -= 1 |
| Break | break | for i in range(10): if i == 5: break |
| Continue | continue | for i in range(5): if i == 2: continue print(i) |
| Concept | Syntax | Example |
|---|---|---|
| Function Definition | def name(params): body | def greet(name): return f"Hello {name}" |
| Function Call | name(arguments) | result = greet("John") |
| Default Parameters | def func(p=value): | def greet(name="World"): |
| Keyword Arguments | func(param=value) | func(name="John", age=25) |
| Variable Arguments | *args, **kwargs | def func(*args, **kwargs): |
| Lambda Function | lambda params: expression | square = lambda x: x**2 |
| Operation | Syntax | Example |
|---|---|---|
| Create List | list = [items] | nums = [1, 2, 3] |
| Access Element | list[index] | first = nums[0] |
| Add Element | list.append(item) | nums.append(4) |
| Insert Element | list.insert(index, item) | nums.insert(1, 10) |
| Remove Element | list.remove(item) | nums.remove(2) |
| Pop Element | list.pop(index) | last = nums.pop() |
| List Slicing | list[start:end:step] | subset = nums[1:4] |
| List Comprehension | [expr for item in list] | squares = [x**2 for x in range(5)] |
| Operation | Syntax | Example |
|---|---|---|
| Create Dict | dict = {key: value} | person = {"name": "John", "age": 25} |
| Access Value | dict[key] | name = person["name"] |
| Add/Update | dict[key] = value | person["city"] = "NYC" |
| Get Value | dict.get(key) | age = person.get("age", 0) |
| Keys | dict.keys() | keys = person.keys() |
| Values | dict.values() | values = person.values() |
| Items | dict.items() | items = person.items() |
| Delete Key | del dict[key] | del person["age"] |
| Operation | Syntax | Example |
|---|---|---|
| Length | len(string) | length = len("hello") |
| Concatenation | str1 + str2 | result = "Hello" + " " + "World" |
| Repetition | string * n | stars = "*" * 5 |
| Indexing | string[index] | first = "hello"[0] |
| Slicing | string[start:end] | part = "hello"[1:4] |
| Upper Case | string.upper() | caps = "hello".upper() |
| Lower Case | string.lower() | lower = "HELLO".lower() |
| Replace | string.replace(old, new) | new = "hello".replace("l", "x") |
| Split | string.split(separator) | parts = "a,b,c".split(",") |
| Join | separator.join(list) | result = "-".join(["a", "b", "c"]) |
| Operation | Syntax | Example |
|---|---|---|
| Open File | open(filename, mode) | f = open("file.txt", "r") |
| Read File | file.read() | content = f.read() |
| Read Lines | file.readlines() | lines = f.readlines() |
| Write File | file.write(text) | f.write("Hello World") |
| Close File | file.close() | f.close() |
| Context Manager | with open(...) as f: | with open("file.txt", "r") as f: content = f.read() |
| Structure | Syntax | Example |
|---|---|---|
| Try-Except | try: statements except Error: handler | try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") |
| Try-Except-Else | try: ... except ...: ... else: ... | try: x = int(input()) except ValueError: print("Invalid") else: print("Valid") |
| Try-Except-Finally | try: ... except ...: ... finally: ... | try: f = open("file.txt") ... finally: f.close() |
| Concept | Syntax | Example |
|---|---|---|
| Class Definition | class Name: def __init__(self): | class Person: def __init__(self, name): self.name = name |
| Object Creation | obj = ClassName() | p = Person("John") |
| Method Definition | def method(self): | def greet(self): return f"Hello {self.name}" |
| Inheritance | class Child(Parent): | class Student(Person): def __init__(self, name, grade): super().__init__(name) self.grade = grade |
| Function | Usage | Example |
|---|---|---|
| len() | Get length of object | len([1,2,3]) returns 3 |
| type() | Get type of object | type(42) returns <class 'int'> |
| str() | Convert to string | str(42) returns "42" |
| int() | Convert to integer | int("42") returns 42 |
| float() | Convert to float | float("3.14") returns 3.14 |
| list() | Convert to list | list("abc") returns ['a', 'b', 'c'] |
| range() | Create range object | range(5) creates 0,1,2,3,4 |
| enumerate() | Get index and value | for i, v in enumerate(list) |
| zip() | Combine iterables | zip([1,2], ['a','b']) |
| map() | Apply function to items | map(func, [1,2,3]) |
| filter() | Filter items with function | filter(func, [1,2,3]) |
| sum() | Sum of numbers | sum([1,2,3]) returns 6 |
| max() | Maximum value | max([1,2,3]) returns 3 |
| min() | Minimum value | min([1,2,3]) returns 1 |