Programming with Python - MSBTE Exam Revision Notes
1. Python Basics
- Easy to Learn, Open Source, Cross-platform, Portable, Interpreted.
- Interactive mode supports direct command execution.
- Indentation: Defines code blocks (use consistent spaces).
- Comments:
* Single-line: starts with #
* Multi-line: enclosed in triple quotes (''' or """)
2. Data Types
- int, float, complex, str, bool, list, tuple, set, dict.
- Example:
* int: a = 5
* float: b = 3.14
* str: s = "Hello"
* list: l = [1, 2, "three"]
* tuple: t = (1, 2)
* dict: d = {'name': 'Alice', 'age': 25}
3. Operators
- Arithmetic: +, -, *, /, %, //, **
- Relational: ==, !=, <, >, <=, >=
- Logical: and, or, not
- Assignment: =, +=, -=, *=, /=
- Membership: 'in', 'not in'
- Identity: 'is', 'is not'
- Bitwise: &, |, ^, ~, <<, >>
4. Control Structures
- if, if-else, if-elif-else:
* if x > 10: print("Large")
* elif x == 10: print("Equal")
* else: print("Small")
- Loops:
* for i in range(5): print(i)
* while x > 0: x -= 1
- break: exits loop, continue: skips to next iteration
5. Functions
- Defined using def:
* def greet(name): print("Hi", name)
- Lambda:
* add = lambda x, y: x + y
- Built-in: len(), max(), min(), sum(), abs(), round()
Programming with Python - MSBTE Exam Revision Notes
6. Lists
- Mutable, dynamic-sized sequences.
- Methods: append(), extend(), insert(), remove(), pop(), sort(), reverse()
- Indexing & Slicing: l[0], l[-1], l[1:4]
7. Tuples
- Immutable sequences.
- Faster and more secure than lists.
- Defined using parentheses: t = (1, 2, 3)
8. Dictionary
- Key-value pairs: d = {'a': 1, 'b': 2}
- Access: d['a'], d.get('b')
- Methods: keys(), values(), items(), pop(), update()
9. Object-Oriented Concepts
- class, object, constructor (__init__), self
- Example:
class Student:
def __init__(self, name): self.name = name
def show(self): print(self.name)
- Concepts: Inheritance, Encapsulation, Polymorphism, Abstraction
- Data hiding: use _ or __ for private members
10. File Handling
- Modes: 'r', 'w', 'a', 'r+', 'w+', 'a+'
- Read: read(), readline(), readlines()
- Write: write(), writelines()
- Always close file using close()
11. Modules & Packages
- Module: Python file with functions/classes
- Importing: import math, from math import sqrt
- Package: directory with __init__.py
- Example: pkg.mod1.m1()
12. Exception Handling
- try-except-finally
- Example:
try:
x=1/0
Programming with Python - MSBTE Exam Revision Notes
except ZeroDivisionError:
print("Error")
finally:
print("Done")