Computer Science: Class 11 — Chapter 5: Getting Started with Python

5.1 Introduction to Python

Python is a high-level, interpreted programming language. Before diving into Python, it is essential to understand the fundamental concepts of programming languages and how they bridge the gap between human logic and machine execution.

Core Programming Concepts
  • Program : An ordered set of instructions executed by a computer to carry out a specific task.
  • Programming Language : The formal language used to specify instructions to a computer.
  • Machine Language : Low-level language consisting of 0s and 1s that computers understand natively.
  • High-Level Language : Human-readable languages (e.g., Python, C++, Java) that are easier to manage but require translation.
  • Source Code : The program written in a high-level language.
  • Interpreter : Translates and executes source code line-by-line. Python uses an interpreter.
  • Compiler : Translates the entire source code at once into object code before execution.
5.1.1 Features of Python
  • High-Level & Free/Open Source : Accessible to everyone and easy to distribute.
  • Interpreted Language : Executed line-by-line by the Python interpreter.
  • Easy to Understand : Features a clearly defined syntax and simple structure.
  • Case-Sensitive : For example, NUMBER and number are treated as different identifiers.
  • Portable & Platform Independent : Can run on various operating systems (Windows, macOS, Linux).
  • Rich Standard Library : Offers a vast collection of predefined functions.
  • Indentation-Based : Uses indentation instead of curly braces to define code blocks.
5.1.2 Working with Python & Execution Modes

To write and run Python programs, we use a Python interpreter (also called the Python shell ), indicated by the prompt >>> .

  1. Interactive Mode : Allows execution of individual statements instantaneously. Ideal for testing single lines of code. Statements cannot be saved.
        
          >>> 1 + 2
          3
          >>> "Hello " + "World"
          'HelloWorld'
        
      
  2. Script Mode : Allows writing multiple instructions in a file, saving it with a .py extension, and executing it as a whole.
      
        # Save as prog5-1.py
        print("Save Earth")
        print("Preserve Future")
      
    
5.2 Python Keywords & 5.3 Identifiers
5.2 Python Keywords

Keywords are reserved words with specific meanings for the interpreter. They must be written exactly as defined (case-sensitive).

Keyword Keyword Keyword Keyword Keyword
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
5.3 Identifiers

Identifiers are user-defined names used to identify variables, functions, or other entities in a program.

  • Naming Rules:
    • Must begin with an uppercase/lowercase letter or an underscore ( _ ).
    • Cannot start with a digit.
    • Can contain letters, digits, and underscores ( a-z, A-Z, 0-9, _ ).
    • Cannot be a keyword.
    • Cannot contain special symbols like !, @, #, $, %, etc.
5.4 Variables & 5.5 Comments
5.4 Variables

A variable is a named reference to an object stored in memory. In Python, variable declaration is implicit (created automatically upon first assignment).

  
    gender = 'M'
    message = "Keep Smiling"
    price = 987.9
  
5.5 Comments

Comments are non-executable notes added to source code to improve readability. In Python, comments begin with a hash sign ( # ).

  
    # This is a single-line comment
    amount = 3400  # Inline comment
  
5.6 Everything is an Object & 5.7 Data Types

Python treats every value or data item as an object. Each object is assigned a unique identity (ID) representing its memory address, which can be retrieved using the id() function.

5.7 Data Types Classification

Data types identify the type of values a variable can hold and the operations that can be performed on them.

Core Computer Science Concept Technical Definition / Operational State Structural Parameters & Specifications Computational Function & System Purpose
Numbers Stores numerical values. Classified into int , float , and complex . Includes bool as a subtype of integer. Performs mathematical computations.
Sequence An ordered collection of items indexed by integers. Includes String (immutable), List (mutable), and Tuple (immutable). Manages ordered datasets.
Sets An unordered collection of unique items. Enclosed in curly brackets { } . Mutable but cannot contain duplicate elements. Performs mathematical set operations and eliminates duplicates.
None A special data type representing the absence of a value. Has only one value: None . Supports no special operations. Acts as a placeholder or default return value.
Mapping An unordered collection of key-value pairs. Represented by Dictionary (enclosed in { } with key:value syntax). Provides fast, key-based lookups.
Mutable vs Immutable Data Types
  • Mutable Types: Values can be changed in-place after creation. Examples: List , Set , Dictionary .
  • Immutable Types: Values cannot be changed in-place. Any modification creates a new object in memory. Examples: int , float , complex , bool , string , tuple .
5.8 Operators & 5.9 Expressions
5.8 Operators in Python
  • Arithmetic Operators: + (Addition/Concatenation), - (Subtraction), * (Multiplication/Replication), / (Division), % (Modulus), // (Floor Division), ** (Exponentiation).
  • Relational Operators: == , != , > , < , >= , <= . Evaluate to True or False .
  • Assignment Operators: = , += , -= , *= , /= , %= , //= , **= .
  • Logical Operators: and , or , not .
  • Identity Operators: is , is not (checks if two variables point to the same memory location).
  • Membership Operators: in , not in (checks if a value exists within a sequence).
5.9.1 Precedence of Operators

When an expression contains multiple operators, precedence determines the evaluation order (from highest to lowest):

  1. ** (Exponentiation)
  2. ~, +, - (Complement, unary plus, unary minus)
  3. *, /, %, // (Multiply, divide, modulo, floor division)
  4. +, - (Addition, subtraction)
  5. <=, <, >, >=, ==, != (Relational/Comparison)
  6. =, %=, /=, //=, -=, +=, *=, **= (Assignment)
  7. is, is not (Identity)
  8. in, not in (Membership)
  9. not , and , or (Logical)
5.11 Input, Output & 5.12 Type Conversion

Technical Profile: Built-in I/O Functions

  • input([prompt]): Prompts the user for input. Always returns the input as a string .
  • print(value, ..., sep=' ', end=' '): Outputs data to the screen. sep defines the separator between values, and end defines the character appended at the end of the output.
5.12 Type Conversion
  • Explicit Conversion (Type Casting): Forced by the programmer using functions like int() , float() , str() , chr() , and ord() .
      
        # Explicitly converting string input to integer
        age = int(input("Enter your age: "))
      
    
  • Implicit Conversion (Coercion): Handled automatically by the Python interpreter to avoid data loss (type promotion).
      
        num1 = 10      # int
        num2 = 20.0    # float
        sum1 = num1 + num2  # Result is 30.0 (float)
      
    
5.13 Debugging & Error Types

Debugging is the process of identifying and removing bugs (errors) from a program.

Categories of Errors
  • Syntax Errors: Violations of the grammatical rules of the programming language. The interpreter will not execute the program if syntax errors exist.
  • Logical Errors: Occur when the program runs without crashing but produces incorrect results due to flawed logic (e.g., writing 10 + 12/2 instead of (10 + 12)/2 ).
  • Runtime Errors: Occur during execution when an invalid operation is attempted (e.g., division by zero, or trying to convert an invalid string to an integer).

Case Study: Student Management Information System (SMIS)


Socio-Technical Analysis & Core Systemic Impact: Implementing an automated SMIS requires robust input validation and explicit type casting to prevent runtime crashes. For instance, capturing numeric fields like "Roll No" or "Phone Number" requires converting raw string inputs from input() into integers using int() , while ensuring proper exception handling is in place to catch non-numeric inputs that trigger runtime ValueError exceptions. Proper documentation and consistent naming conventions (e.g., first_num or firstNum ) are critical for collaborative software maintenance.