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: AZA-Z and aza-z.
    • Digits: 090-9.
    • Special Symbols: space, ++, -, *, //, ((, )), \sim, `, !!, @@, #\#, \, %\%, \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:
      1. Can be an arbitrarily long sequence of letters and digits.
      2. The first character must be a letter or an underscore (_\_).
      3. Upper and lower case characters are distinct (case-sensitive).
      4. Digits 090-9 are allowed except as the first character.
      5. Must not be a keyword.
      6. No special characters allowed except underscore (_\_).
      7. 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:
    1. String Literals: Characters enclosed in double ("") or single (') quotes (e.g., "Python", "123456", '@'). Single and multiple characters in quotes are treated the same.
    2. Numeric Literals: Includes integers, floating-point numbers, and complex numbers.
    3. Boolean Literals: Represented by True or False.
    4. Special Literals: None indicates the absence of a value (similar to NULL in other languages).
    5. 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 22; len('\\') is 11).
    • For triple-quoted strings, the EOL (end of line) character is counted. (Example: len("""Civil lines\nKanpur""") is 1818).
    • For strings using backslashes for continuation, EOL is not counted. (Example: len("ab\ \n bc\ \n cd") is 66).

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,501234, -50).
    • Octal: Starts with 0o0o (zero followed by 'o'). E.g., 0o100o10 represents decimal 88.
    • Hexadecimal: Starts with 0x0x (zero followed by 'x'). E.g., 0xF0xF represents decimal 1515.
  • Floating Point Literals: Also known as Real Literals.
    • Fractional Form: Signed or unsigned with a decimal point (e.g., 12.0,15.86,10.12.0, -15.86, 10.).
    • Exponent Form: Consists of Mantissa and Exponent. E.g., 10.510.5 can be 0.105×1020.105 \times 10^{2}, written as 0.105E020.105E02 (where 0.1050.105 is the mantissa and 0202 is the exponent).
  • Complex Numbers: Made of two floating-point values (real and imaginary). The imaginary part uses jj (instead of ii). For a variable xx, access parts via x.real and x.imag (e.g., 1+0j1+0j has real 1.01.0 and imag 0.00.0).
  • Cautions: Numeric values separated by commas (e.g., 100,50,600100, 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 22) will raise errors.

Operators

  • Unary Operators (Require one operand):
    • ++: Unary plus
    • -: Unary minus
    • \sim: 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.

Simple Input and Output

  • 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:
    1. Entering a float string (like "100.5") while converting to int causes a ValueError.
    2. Entering text (like "Eighteen") for numeric conversion causes a ValueError.
    3. 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., 2020, A+10A+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 (#\#).
    1. Full line: Entire line starts with #\#.
    2. Inline: Code followed by #\# and comment text.
    3. 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+1x+1 (1111), z+10z+10 (4040), and y10y-10 (1010). Final Assignment: z=11, y=40, x=10.
    • Example of reassignment: y, y = 10, 20 results in y being 2020.

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 11
    • "\a": Size 11
    • "Reena\'s": Size 77
    • '\"': Size 11
    • "It\'s": Size 44
  • Valid/Invalid String Syntax:
    1. "Welcome to India": Correct.
    2. 'He announced "Start the match" very loudly': Correct (single quotes host double quotes).
    3. "Sayonara': Incorrect (mixed quotes).
    4. 'Revise Python Chapter 1': Correct.
    5. "Bonjour: Incorrect (missing closing quote).
    6. "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")).