Comprehensive Guide to Python Fundamentals
Python Character Set
- Definition: A set of valid characters that the Python interpreter can recognize. Characters represent letters, digits, or symbols.
- Encoding Standard: Python supports the UNICODE encoding standard.
- Categories of Characters:
- Letters: A−Z and a−z.
- Digits: 0−9.
- Special Symbols: space, +, −, ∗, /, (, ), ∼, ‘, !, @, #, \, %, \text{\^}, &, [, {, ], }, ;, :, „, ”, ,, <, ., >, /, ?
- White Spaces: Blank space, Enter, and Tab.
- Other Characters: Python can process all ASCII and UNICODE characters as part of data or literals.
Tokens (Lexical Units)
- Definition: The smallest individual unit in a program is known as a token, lexical unit, or lexical element.
- Types of Tokens:
- Keywords: Reserved words with special meanings.
- Identifiers: Names given to different parts of the program (variables, objects, classes, etc.).
- Literals: Data items with a fixed value.
- Operators: Symbols that perform specific operations when applied to variables.
- Punctuators: Symbols used to organize program structure and sentences.
Keywords and Identifiers
- Keywords:
- These are reserved words for the Python interpreter.
- Every keyword is assigned a specific task and can only be used for that purpose.
- Identifiers:
- Names given to variables, objects, classes, and functions.
- Rules for Forming Identifiers:
- Can be an arbitrarily long sequence of letters and digits.
- The first character must be a letter or an underscore (_).
- Upper and lower case characters are distinct (case-sensitive).
- Digits 0−9 are allowed except as the first character.
- Must not be a keyword.
- No special characters allowed except underscore (_).
- Spaces are not allowed.
- Valid Identifier Examples:
GradePay, File_12_2018, JAMES007, GRADEPAY, _ismarried, _to_update.
Literals / Values
- General Definition: Literals are data items that have a fixed value.
- Types of Literals:
- String Literals: Characters enclosed in double (") or single (′) quotes (e.g.,
"Python", "123456", '@'). Single and multiple characters in quotes are treated the same. - Numeric Literals: Includes integers, floating-point numbers, and complex numbers.
- Boolean Literals: Represented by
True or False. - Special Literals:
None indicates the absence of a value (similar to NULL in other languages). - Literal Collections: Groups of data items.
String Types and Non-Graphic Characters
- Non-Graphic (Escape) Characters: Special characters that cannot be typed directly from the keyboard (like backspace or enter). They start with a backslash (\).
- Escape Character List:
- : Backslash
- \': Single quotes
- \": Double quotes
- \text{\a}: ASCII bell
- \text{\b}: Back Space
- \text{\n}: New line
- \text{\r}: Carriage return
- \text{\t}: Horizontal tab
- \text{\v}: Vertical tab
- \text{\uxxxx}: 16-bit Hexadecimal value
- \text{\Uxxxx}: 32-bit Hexadecimal value
- \text{\ooo}: Octal value
- Single Line Strings: Created with single or double quotes; must terminate on one line. Failure to close on the same line results in an error:
EOL while scanning string literal. - Multiline Strings: Used to store text across multiple lines.
- Method A: Add a backslash (\) at the end of a normal single/double quoted string to continue on the next line.
- Method B: Use triple quotation marks (
""" or ''').
- Size of String:
- Determined using the
len() function. - Escape sequences count as one character (e.g.,
len('\ab') is 2; len('\\') is 1). - For triple-quoted strings, the EOL (end of line) character is counted. (Example:
len("""Civil lines\nKanpur""") is 18). - For strings using backslashes for continuation, EOL is not counted. (Example:
len("ab\ \n bc\ \n cd") is 6).
Numeric Literals and Complex Numbers
- Integer Literals: Contain at least one digit and no decimal point. Can be positive or negative.
- Decimal: Standard numbers (e.g., 1234,−50).
- Octal: Starts with 0o (zero followed by 'o'). E.g., 0o10 represents decimal 8.
- Hexadecimal: Starts with 0x (zero followed by 'x'). E.g., 0xF represents decimal 15.
- Floating Point Literals: Also known as Real Literals.
- Fractional Form: Signed or unsigned with a decimal point (e.g., 12.0,−15.86,10.).
- Exponent Form: Consists of Mantissa and Exponent. E.g., 10.5 can be 0.105×102, written as 0.105E02 (where 0.105 is the mantissa and 02 is the exponent).
- Complex Numbers: Made of two floating-point values (real and imaginary). The imaginary part uses j (instead of i). For a variable x, access parts via
x.real and x.imag (e.g., 1+0j has real 1.0 and imag 0.0). - Cautions: Numeric values separated by commas (e.g., 100,50,600) are treated by Python as a tuple (a collection/sequence of values).
Type Conversion and Typing
- Determining Type: Use the
type() function (e.g., type(10.5) returns <class 'float'>). - Implicit Type Conversion: Done automatically by the compiler. E.g., assigning a float value to an integer variable makes the variable a float type.
- Explicit Type Conversion (Type Casting): Done by the programmer using functions like
int(), float(), str(), and bool(). - Dynamic Typing: A variable pointing to a value of one type can be reassigned to point to a value of a different type (e.g., from
int to str). - Caution with Dynamic Typing: Incorrect operations on types (like dividing a string by 2) will raise errors.
Operators
- Unary Operators (Require one operand):
- +: Unary plus
- −: Unary minus
- ∼: Bitwise complement
not: Logical negation
- Binary Operators (Require two operands):
- Arithmetic: + (Addition), −, ∗ (Multiplication), / (Division), % (Remainder/Modulus), ∗∗ (Exponent), // (Floor division).
- Bitwise: Work on binary values of numbers.
& (Bitwise AND), ^ (Bitwise XOR), | (Bitwise OR). - Shift Operators:
<< (Shift left), >> (Shift right). - Identity:
is (Is the identity same?), is not (Is the identity not same?). - Relational:
<, >, <=, >=, == (Equal to), != (Not equal to). - Logical:
and, or. - Assignment:
=, /=, +=, -=, *=, **=, //=. - Membership:
in (Whether variable in sequence), not in.
- Input Function: Use
variable = input(<message>).- Crucial Note:
input() always returns a value of String type. Arithmetic operations cannot be performed directly on raw input. - To get numeric input, wrap the input in a conversion function:
int(input("Enter marks ")).
- Input Errors:
- Entering a float string (like
"100.5") while converting to int causes a ValueError. - Entering text (like
"Eighteen") for numeric conversion causes a ValueError. - Entering incompatible float formats (like
"12.5.6" or "100 percent") results in a ValueError.
- Output Function: Use
print().- Syntax:
print(message_to_print[, sep="string", end="string"]). - sep Parameter: The separator between values (default is a space
' '). - end Parameter: The string appended after the last value (default is newline
\n). print() automatically converts numeric values and evaluated expressions to strings before displaying them.
Python Program Barebones
- Expressions: Legal combinations of symbols representing a value (e.g., 20, A+10).
- Statements: Programming instructions that perform actions (e.g.,
print("Welcome"), a = 100). - Comments: Additional information ignored by the interpreter. Start with the hash symbol (#).
- Full line: Entire line starts with #.
- Inline: Code followed by # and comment text.
- Multiline: Using # on each new line or using triple quotes (
"""...""").
- Functions: Named blocks of code defined with the
def keyword, designed for reuse. - Blocks and Indentation: A group of statements is a block (like those in functions or loops). Indentation (extra space before a statement, usually 4 spaces) defines the next indent level.
- Variables: Named temporary memory locations.
- Unlike C++, where a variable's memory address remains fixed when the value changes, Python variables refer to new memory addresses each time a new value is assigned (referential model).
- Variables are not created in memory until a value is assigned (
print(x) fails if x was never assigned a value).
- Lvalues and Rvalues:
- Lvalues: Expressions on the Left Hand Side of an assignment; refer to memory locations/objects to which you can assign values.
- Rvalues: Expressions on the Right Hand Side; refer to the value being assigned.
- Rule: Literals or expressions cannot be on the LHS (e.g.,
100 = x or a+b = c is invalid).
Multiple Assignments
- Same Value to Multiple Variables:
a = b = c = 50. - Multiple Values to Multiple Variables:
a, b, c = 11, 22, 33. - Evaluation Logic: Python first evaluates the Entire Right Hand Side (RHS) and then performs the mapping to the Left Hand Side (LHS).
- Example:
x, y = 10, 20; z, y, x = x + 1, z + 10, y - 10. If z=30, the output would evaluate x+1 (11), z+10 (40), and y−10 (10). Final Assignment: z=11, y=40, x=10. - Example of reassignment:
y, y = 10, 20 results in y being 20.
Questions & Discussion
- Difference between keywords and identifiers: Keywords are reserved; identifiers are user-defined names. Keywords cannot be used as identifiers.
- String Size Practice Cases:
'\a': Size 1"\a": Size 1"Reena\'s": Size 7'\"': Size 1"It\'s": Size 4
- Valid/Invalid String Syntax:
"Welcome to India": Correct.'He announced "Start the match" very loudly': Correct (single quotes host double quotes)."Sayonara': Incorrect (mixed quotes).'Revise Python Chapter 1': Correct."Bonjour: Incorrect (missing closing quote)."Honesty is the 'best' policy": Correct.
- Correcting Error Example:
num = input("enter any number") → Result is string.double_num = num * 2 → String repetition (e.g., "100100").Print("Double of",num,"is",double_num) → Syntax error (Print vs print).- Fix:
num = int(input("enter any number")).