Python Fundamentals Study Notes
Python Character Set
- Definition: A set of valid characters that the Python interpreter can recognize. A character represents letters, digits, or any symbol.
- Encoding Standard: Python supports the UNICODE encoding standard.
- Composition of Character Set:
- Letters: A−Z and a−z.
- Digits: 0−9.
- Special Symbols: space, +, −, ∗, /, (, ), ∼, ``` , !, @, #, \, %, ^, &, [, ], {, }, ;, :, ′, ", <, ,, >, ., /, ?.
- White Spaces: Blank space, Enter, and Tab.
- Other Characters: Python can process all ASCII and UNICODE characters as part of data or literals.
Tokens
- Definition: The smallest individual unit in a program. They are also known as lexical units or lexical elements.
- Types of Tokens:
- Keywords
- Identifiers (Names)
- Literals
- Operators
- Punctuators
Keywords
- Definition: Reserved words that have special meaning for the Python interpreter. Every keyword is assigned a specific task and can only be used for that specific purpose.
Identifiers
- Definition: Names given to different parts of a program, such as variables, objects, classes, and functions.
- Naming Rules:
- An identifier is an arbitrarily long sequence of letters and digits.
- The first character must be a letter or an underscore (_).
- Upper and lower case characters are treated as different (case-sensitive).
- The digits 0−9 are allowed except as the first character.
- It must not be a keyword.
- No special characters are allowed except for the underscore (_).
- Spaces are not allowed.
- Examples of Valid Identifiers:
- GradePay
- File_12_2018
- JAMES007
- GRADEPAY
- _ismarried
- _to_update
Literals / Values
- Definition: Data items that have a fixed value.
- Types of Literals:
- String Literals: A collection of characters enclosed in double or single quotes. Examples include "Python", "Mogambo", '123456', 'Hello How are you', '', '4', and "@@". Multi-character and single-character strings are treated the same.\n * **Numeric Literals**: Includes integers, floating-point numbers, and complex numbers.\n * **Boolean Literals**: Represented by either `True` or `False`.\n * **Special Literals**: Python has one special literal, `None`, which indicates the absence of a value (similar to NULL in other languages).\n * **Literal Collections**: Such as tuples, which are collections of sequences of values.\n\n# Non-Graphic (Escape) Characters\n\n* **Definition**: Special characters that cannot be typed directly from the keyboard (like backspace, tabs, enter). They are represented by escape sequences beginning with a backslash (\).\n* **List of Escape Sequences**:\n * \\ : Backslash\n * \' : Single quotes\n * \" : Double quotes\n * \a : ASCII bell\n * \b : Back Space\n * \n : New line\n * \r : Carriage return\n * \t : Horizontal tab\n * \uxxxx : Hexadecimal value (16-bit)\n * \Uxxxx : Hexadecimal value (32-bit)\n * \v : Vertical tab\n * \ooo : Octal value\n\n# String Types and Multiline Handling\n\n* **Single Line Strings**: Created using single or double quotes. They must terminate on the same line. Failing to close the quote on the same line results in an "EOL while scanning string literal" error.\n* **Multiline Strings**: Used to store text across multiple lines.\n * **Method A**: Adding a backslash (\) at the end of a single/double-quoted string. Example:\n * `Name="1/6 Mall Road \ `\n * `Kanpur"` results in `'1/6 Mall RoadKanpur'`.\n * **Method B**: Using triple quotation marks (`"""` or `'''`). Example:\n * `Address="""1/7 Preet Vihar`\n * `New Delhi`\n * `India"""` results in `'1/7 Preet Vihar\nNew Delhi\nIndia'`.\n\n# Size of Strings\n\n* **Calculation Logic**: Python determines the size as the count of characters. Escape sequences count as exactly one character.\n* **The `len()` Function**: Use `len()` to check the size.\n* **Examples**:\n * `len('abc')` is 3.\n * `len('\\')` (backslash escape) is 1.\n * `len('\\ab')` is 2 (where `\\a` is the bell escape sequence and `b` is a letter).\n * `len("Meera\'s Toy")` is 11.\n * `len("Vicky\'s")` is 7.\n* **Multiline Size Rules**:\n * In triple-quoted strings, the EOL (End of Line) character is counted. For instance, a multiline string "Civil lines [newline] Kanpur" results in a length of 18.\n * In single/double quotes with a backslash to continue the line, the EOL is **not** counted. Example: `len("ab\bc\cd")` is 6.\n\n# Numeric Literals Detail\n\n* **Integer Literals**: Contain at least one digit and no decimal point. Can be positive or negative.\n * **Decimal**: Standard numbers like `1234`, `-50`, `+100`.\n * **Octal**: Starts with `0o` (zero followed by 'o'). e.g., `0o10` is decimal 8.\n * **Hexadecimal**: Starts with `0x` (zero followed by 'x'). e.g., `0xF` is decimal 15.\n* **Floating Point Literals (Real Literals)**: Numbers with fractional parts.\n * **Fractional Form**: Signed or unsigned with a decimal point (e.g., `12.0`, `-15.86`, `0.5`, `10.` represents `10.0`).\n * **Exponent Form**: Consists of a "Mantissa" and an "Exponent". Example: 10.5canberepresentedas0.105 \times 10^2, written as `0.105E02`. Here `0.105` is the mantissa and `02` is the exponent.\n* **Complex Numbers**: Made of two floating-point values (real and imaginary). Represented as `a + bj`. In Python, `j` is used for the imaginary part.\n * Example: `x = 1+0j` results in `x.real` being `1.0` and `x.imag` being `0.0`.\n\n# Type Checking and Conversion\n\n* **The `type()` Function**: Used to determine the class/data type of a literal or variable.\n * `type(100)` -> ``\n * `type(10.5)` -> ``\n * `type("hello")` -> ``\n * Values with commas are treated as a **tuple** (e.g., `a = 100, 50, 600` is a tuple).\n* **Conversion Types**:\n 1. **Implicit Type Conversion**: Done automatically by the compiler. E.g., if `x` is an int and `y` is a float, setting `x = y` converts `x` to a float.\n 2. **Explicit Type Conversion (Type Casting)**: Done by the programmer using functions:\n * `int()`: Converts to integer (e.g., `int(50.25)` results in `50`).\n * `float()`: Converts to float (e.g., `float(25)` results in `25.0`).\n * `str()`: Converts to string.\n * `bool()`: Converts to Boolean.\n\n# Simple Input and Output\n\n* **Input Function**: `variable = input()`. Note that `input()` always returns a **String** type.\n* **Arithmetic Warning**: Because input defaults to string, you cannot perform math on it immediately. For example, `salary = input("Enter salary ")` followed by `salary * 20 / 100` will raise a `TypeError` because you cannot divide a string by an integer.\n* **Handling Numeric Input**: Wrap the input in a conversion function, e.g., `num1 = int(input("Enter Number "))`.\n* **Common Input Errors**:\n 1. Entering a float string (like "100.5") into `int()` results in a `ValueError`.\n 2. Entering words (like "Eighteen") into `int()` results in a `ValueError`.\n 3. Entering multiple decimal points or non-numeric words into `float()` results in a `ValueError`.\n* **Output Function**: `print(message, [sep="string", end="string"])`.\n * **Evaluation**: `print()` evaluates expressions before converting the result to a string for display.\n * **Separator (`sep`)**: Defaults to a single space. It can be changed (e.g., `sep="##"`).\n * **End Parameter (`end`)**: Defaults to `\n` (new line). It can be changed to stay on the same line (e.g., `end=" "`).\n\n# Operators\n\n## Unary Operators\n* Require one operand to operate.\n * `+` : Unary plus\n * `-` : Unary minus\n * `~` : Bitwise complement\n * `not` : Logical negation\n\n## Binary Operators\n* Require two operands to operate.\n* **Arithmetic Operators**:\n * `+` : Addition\n * `-` : Subtraction\n * `*` : Multiplication\n * `/` : Division\n * `%` : Remainder (Modulus)\n * `**` : Exponent (e.g., `2**4` is 16)\n * `//` : Floor division (e.g., `20 // 7` is 2)\n* **Bitwise Operators** (Work on binary representations like `101` for decimal 5$$):
& : Bitwise AND^ : Bitwise XOR| : Bitwise OR<< : Shift left>> : Shift right
- Identity Operators:
is : Is the identity the same?is not : Is the identity not the same?
- Relational Operators:
- Logical Operators:
- Assignment Operators:
=, /=, +=, -=, *=, **=, //=.
- Membership Operators:
in : Is variable in sequence?not in : Is variable not in sequence?
Punctuators
- Definition: Symbols used to organize sentence structure and indicate the rhythm and emphasis of expressions.
- List:
', ", #, $, @, [], {}, =, :, ;, (), ,, ..
Barebones of a Python Program
- Expressions: Combinations of symbols (operators/operands) that represent a value (e.g.,
A+10). - Statements: Programming instructions that perform an action (e.g.,
print("Welcome"), a=100). - Comments: Additional information ignored by the interpreter. Starts with
#.- Full line:
# This is a comment. - Inline:
area = l*b # calculating area. - Multiline: Multiple lines starting with
# or enclosed in triple quotes (""").
- Functions: Named blocks of reusable code created with the
def keyword. - Blocks and Indentation: A group of statements (like in a function or loop) is a block. Indentation (usually 4 spaces) marks the level of the block.
Variables and Assignment
- Definition: Named temporary locations for storing values. Every variable has an Identity, Type, and Value.
- Variable Storage Logic: Unlike C++, where a variable refers to a fixed memory address, Python variables refer to the memory location of the object they currently point to. When a value changes, the memory address the variable refers to usually changes (Identity changes).
- Lvalues and Rvalues:
- Lvalue: Expression on the left side of assignment; refers to a memory location/object (must be a variable).
- Rvalue: Expression on the right side of assignment; refers to the value being assigned.
100 = x is invalid.
- Multiple Assignments:
- Same value to multiple variables:
a = b = c = 50. - Multiple values to multiple variables:
a, b, c = 11, 22, 33. Python evaluates the entire RHS first, then assigns to the LHS.
Dynamic Typing
- Definition: A variable pointing to a value of one type can be reassigned to point to a value of a different type (e.g.,
x = 100 then x = "KVians"). - Caution: Operations must be compatible with the current type. For example,
x = 'Exam' then y = x / 2 will cause a crash.
Questions & Discussion
- Difference between Keywords and Identifiers: Keywords are reserved by the language; identifiers are names created by the user for variables/functions.
- Determining size of
"XY\ [newline] YZ": If created with triple quotes, the newline is counted. If created with a backslash at the end of the line in single/double quotes, it is not. - Identify Type of Literals:
41.678: Float12345: IntegerTrue: Boolean'True': String"False": String0xCAFE: Hexadecimal Integer0o456: Octal Integer
- Correction Example: If a program does
num = input("enter number") and double_num = num * 2, entering 100 will produce "100100" (string repetition) instead of 200. The fix is num = int(input("enter number")). - Assignment Logic Exercise:
x, y = 6, 8 x, y = y, x + 2 -> x becomes 8, y becomes 6 + 2 = 8.print(x, y) results in 8 8.