Python Basics
CBSE Class 11 - Computer Science & Information Practices
Python Basics
Python is a high-level, interpreted programming language known for its simplicity and readability. This guide covers the fundamental concepts of Python programming.
Character Set
Python uses the following characters to form valid tokens:
1. Letters
- Uppercase: A-Z
- Lowercase: a-z
2. Digits
- 0-9
3. Special Characters
4. White Spaces
Space, tab, newline, and carriage return
Literals
Literals are notations representing a fixed value in the source code.
Example:
Types of Literals:
1. String Literal
2. Numeric Literal
3. Boolean Literal
4. Special Literal
Operators
1. Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 10 - 3 = 7 |
| * | Multiplication | 4 * 5 = 20 |
| / | Division (Float) | 10 / 3 = 3.333... |
| // | Floor Division | 10 // 3 = 3 |
| ** | Exponentiation | 2 ** 3 = 8 |
| % | Modulus (Remainder) | 10 % 3 = 1 |
2. Assignment Operators
| Operator | Description | Example |
|---|---|---|
| = | Assignment | x = 5 |
| += | Add and Assign | x += 3 (x = x + 3) |
| -= | Subtract and Assign | x -= 2 (x = x - 2) |
| *= | Multiply and Assign | x *= 4 (x = x * 4) |
| /= | Divide and Assign | x /= 2 (x = x / 2) |
| %= | Modulus and Assign | x %= 3 (x = x % 3) |
3. Comparison Operators
| Operator | Description | Example |
|---|---|---|
| < | Less than | 5 < 10 → True |
| > | Greater than | 10 > 5 → True |
| <= | Less than or equal | 5 <= 5 → True |
| >= | Greater than or equal | 10 >= 5 → True |
| == | Equal to | 5 == 5 → True |
| != | Not equal to | 5 != 3 → True |
4. Logical Operators
| Operator | Description | Example |
|---|---|---|
| and | Logical AND | True and False → False |
| or | Logical OR | True or False → True |
| not | Logical NOT | not True → False |
5. Identity Operators
Identity operators compare the memory locations of two objects.
| Operator | Description | Example |
|---|---|---|
| is | Returns True if both variables point to same object | x is y |
| is not | Returns True if both variables point to different objects | x is not y |
Example:
6. Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
| Operator | Description | Example (x=5, y=3) |
|---|---|---|
| & | Bitwise AND | 5 & 3 = 1 |
| | | Bitwise OR | 5 | 3 = 7 |
| ^ | Bitwise XOR | 5 ^ 3 = 6 |
| ~ | Bitwise NOT | ~5 = -6 |
| << | Left Shift | 5 << 1 = 10 |
| >> | Right Shift | 5 >> 1 = 2 |
7. Membership Operators
Membership operators test if a value is a member of a sequence (string, list, tuple, etc.).
| Operator | Description | Example |
|---|---|---|
| in | Returns True if value is found in sequence | 'a' in 'apple' → True |
| not in | Returns True if value is not found in sequence | 'z' not in 'apple' → True |
Example:
Punctuators
Punctuators are special symbols used to organize code structure in Python.
Common Punctuators:
Usage:
[ ]- Lists, indexing( )- Tuples, function calls{ }- Dictionaries, sets:- Indentation, slicing
Keywords
Keywords are reserved words in Python that have special meanings and cannot be used as variable names, function names, or any other identifiers.
- Keywords are case-sensitive
- They cannot be used as identifiers
Python Keywords (35 keywords):
Identifiers
Identifiers are names used to identify variables, functions, classes, modules, and other objects in Python.
Rules for Identifiers:
- ✓Must begin with an uppercase letter (A-Z), lowercase letter (a-z), or underscore (_)
- ✓Can contain letters, digits (0-9), and underscores
- ✓Only special character accepted is underscore (_)
- ✓Can be of any length
- ✗Cannot be a keyword
- ✗Cannot start with a digit
- ✗Cannot contain spaces or other special characters
✅ Valid Identifiers:
❌ Invalid Identifiers:
Features of Python
1. High-Level Language
Easy to read and write, closer to human language than machine code
2. Interpreted Language
Code is executed line by line, no compilation needed
3. Easy to Understand
Simple syntax, readable code
4. Case-Sensitive
Python distinguishes between uppercase and lowercase
5. Predefined Libraries
Rich standard library with many built-in modules
6. Platform Independent
Runs on Windows, Mac, Linux, etc.
Applications of Python:
- Machine Learning - Data science, AI
- Web Development - Django, Flask
- Data Analysis - Pandas, NumPy
- Automation - Scripting, automation
- Game Development - Pygame
Execution Modes in Python
1. Interactive Mode
Code is executed immediately after typing each line. Also known as Python Shell or REPL (Read-Eval-Print Loop).
Advantages: Quick testing, immediate feedback
2. Script Mode
Code is written in a file (with .py extension) and executed as a complete program.
Advantages: Save and reuse code, better for larger programs
Datatypes in Python
1. Numeric/Number
- int - Integer (e.g., 5, -10, 100)
- float - Floating point (e.g., 3.14, -2.5)
- complex - Complex numbers (e.g., 3+4j)
2. Boolean
- True or False
- Used for logical operations
3. Sequence
- list - Ordered, mutable [1, 2, 3]
- tuple - Ordered, immutable (1, 2, 3)
- String - Text "Hello"
4. None
Represents absence of value
Mutable vs Immutable:
Mutable (Changes Allowed):
- list - Can modify elements
- dict - Can add/remove keys
- set - Can add/remove elements
Immutable (Cannot Change):
- int, float - Numbers
- tuple - Cannot modify
- String - Cannot modify
Type Conversion
1. Implicit Type Conversion
Python automatically converts one data type to another when needed (usually to a "larger" type).
Example:
2. Explicit Type Conversion
Manually converting one data type to another using built-in functions.
| Function | Description | Example |
|---|---|---|
| int() | Convert to integer | int(5.9) → 5 |
| float() | Convert to float | float(10) → 10.0 |
| str() | Convert to string | str(100) → "100" |
| bool() | Convert to boolean | bool(0) → False |
Example:
Errors in Python
1. Syntax Error
Occurs when the code violates the rules of the Python programming language. Syntax means the rules of the language.
Example:
Correction:
2. Logical Error
The program runs without crashing but produces incorrect output due to flawed logic.
Example:
3. Runtime Error (Exception)
Errors that occur during program execution, such as division by zero, file not found, etc.
Example:
PEP 8 - Python Style Guide
PEP 8 is the official style guide for Python code. Following PEP 8 makes your code more readable and maintainable.
1. Indentation
Use 4 spaces per indentation level (no tabs).
2. Maximum Line Length
Keep lines ≤ 79 characters. Use line continuation with \ or parentheses.
3. Naming Conventions
| Type | Convention | Example |
|---|---|---|
| Variables | snake_case | user_name |
| Constants | UPPERCASE | MAX_LIMIT |
| Functions | snake_case | get_data() |
| Classes | PascalCase | DataProcessor |
4. Comments
Use # for single-line comments. Write comments before the code, not inline.
Comments
Comments are remarks or notes in the code that are ignored by the Python interpreter. They help document and explain code.
1. Single Line Comments
Use
#for single-line comments2. Multi-Line Comments
Use triple quotes
'''or"""Uses of Comments: