Class 11 Computer and Communicatio Notes Chapter 5 (Chapter 5) – CCT Part-II Book

CCT Part-II
Alright class, let's get straight into Chapter 5, "Getting Started with Python". This is a foundational chapter, crucial not just for your Class 11 understanding but also often tested in various government exams that include basic computer literacy or programming concepts. Pay close attention to the definitions, rules, and basic syntax.


Chapter 5: Getting Started with Python - Detailed Notes

1. Introduction to Python

  • What is Python?
    • A high-level, interpreted, general-purpose programming language.
    • High-Level: Closer to human language, abstracts away low-level computer details (memory management, hardware interaction).
    • Interpreted: Code is executed line by line by an interpreter, unlike compiled languages (like C++ or Java) where the entire code is first translated to machine code. This makes debugging easier but can sometimes be slower.
    • General-Purpose: Can be used for a wide variety of applications – web development, data science, scripting, automation, AI, scientific computing, etc.
    • Dynamically Typed: You don't need to declare the data type of a variable explicitly; the interpreter infers it at runtime.
    • Features: Simple syntax (emphasizes readability), large standard library, open-source, platform-independent (cross-platform), object-oriented capabilities.
  • Origin: Created by Guido van Rossum, first released in 1991.

2. Working in Python

  • Modes of Execution:
    • Interactive Mode (REPL - Read-Eval-Print Loop):
      • You type commands directly into the Python interpreter (like IDLE Shell or the python command in the terminal) and get immediate results.
      • Indicated by the prompt >>>.
      • Useful for testing small code snippets, exploring features, and quick calculations.
      • Commands are not saved permanently.
    • Script Mode:
      • You write your Python code in a file (usually with a .py extension).
      • The entire file (script) is then executed by the Python interpreter.
      • Suitable for writing longer programs.
      • Code is saved and can be reused or modified.
  • IDLE (Integrated Development and Learning Environment):
    • The default IDE provided with Python installation.
    • Includes:
      • Python Shell: For interactive mode execution.
      • Editor: For writing, saving, and editing Python scripts (.py files).
    • To run a script from the IDLE editor: Go to Run -> Run Module (or press F5).

3. Python Fundamentals

  • Keywords:
    • Reserved words with predefined meanings in Python.
    • Cannot be used as variable names or other identifiers.
    • Examples: if, else, elif, for, while, def, class, import, from, try, except, finally, return, yield, True, False, None, and, or, not, is, in, lambda, global, nonlocal, etc. (You can see the full list by typing import keyword; print(keyword.kwlist) in the interpreter).
    • Keywords are case-sensitive (True is a keyword, true is not).
  • Identifiers:
    • Names given to entities like variables, functions, classes, modules, etc.
    • Rules for Naming Identifiers:
      1. Must start with a letter (a-z, A-Z) or an underscore (_).
      2. Can be followed by letters, numbers (0-9), or underscores.
      3. Cannot be a Python keyword.
      4. Cannot contain spaces or special symbols like !, @, #, $, %, etc. (except _).
      5. Are case-sensitive (myVar, myvar, MyVar are different identifiers).
    • Conventions (Good Practice):
      • Use descriptive names (e.g., student_name instead of sn).
      • Use underscores for multi-word variable/function names (snake_case: total_marks).
      • Use CamelCase for class names (MyClass).
  • Variables:
    • Named memory locations used to store data values.
    • Created when you first assign a value to them using the assignment operator (=).
    • Example: age = 25, name = "Alice", pi = 3.14
    • Dynamic Typing: The type of the variable is determined by the value assigned to it and can change if reassigned.
      • x = 10 (x is int)
      • x = "Hello" (Now x is str)
  • Comments:
    • Used to explain code, making it more understandable. Ignored by the interpreter.
    • Single-line comments: Start with #. Everything after # on that line is ignored.
      # This is a single-line comment
      count = 10 # Initial count value
      
    • Multi-line comments: Often use triple quotes ("""Docstring""" or '''Docstring'''). Technically, these are multi-line strings, but commonly used for comments or documentation strings (docstrings).
      """
      This is a multi-line comment
      spanning across several lines.
      Used often for function/module documentation.
      """
      '''Also works with single quotes'''
      
  • Indentation:
    • Crucial in Python. Used to define blocks of code (e.g., code inside loops, functions, if statements).
    • Unlike other languages that use braces {} or keywords, Python uses whitespace (spaces or tabs).
    • Standard Convention: Use 4 spaces per indentation level.
    • Inconsistent indentation will cause an IndentationError.
    if age >= 18:
        print("Eligible to vote") # Indented block
        print("Please register")   # Part of the same block
    else:
        print("Not eligible yet") # Another indented block
    print("End of check") # Not indented, outside the if/else blocks
    
  • Statements:
    • An instruction that the Python interpreter can execute.
    • Can be simple (single logical line) or compound (like if, for, while which contain other statements).
    • Multiple simple statements can be on the same line separated by a semicolon (;), though this is generally discouraged for readability. a = 5; b = 6; print(a+b)

4. Data Types

  • Python has several built-in data types:
    • Numeric Types:
      • int: Integers (whole numbers, positive or negative, e.g., 10, -5, 0).
      • float: Floating-point numbers (numbers with a decimal point, e.g., 3.14, -0.5, 2.7e2 which is 270.0).
      • complex: Complex numbers (e.g., 3+4j, 2-1j).
    • Boolean Type:
      • bool: Represents truth values. Only two possible values: True and False (note capitalization).
    • Sequence Types (Ordered collections):
      • str: String (immutable sequence of characters). Enclosed in single ('...'), double ("..."), or triple quotes ("""...""" or '''...'''). Triple quotes allow multi-line strings.
      • list: List (mutable sequence of items, can hold different data types). Enclosed in square brackets [...]. Example: my_list = [1, "hello", 3.14, True]
      • tuple: Tuple (immutable sequence of items). Enclosed in parentheses (...). Example: my_tuple = (1, "hello", 3.14)
    • Mapping Type (Unordered collection):
      • dict: Dictionary (mutable collection of key-value pairs). Enclosed in curly braces {...}. Keys must be unique and immutable (e.g., strings, numbers, tuples). Example: my_dict = {"name": "Bob", "age": 30}
    • Set Types (Unordered collection):
      • set: Set (mutable collection of unique, unordered items). Enclosed in curly braces {...}. Duplicates are automatically removed. Example: my_set = {1, 2, 3, 2, "a"} results in {1, 2, 3, 'a'}.
    • None Type:
      • None: Represents the absence of a value. It has its own type, NoneType. Often used to indicate that a variable doesn't have a value yet.
  • Mutable vs. Immutable:
    • Mutable: Objects whose value/content can be changed after creation (e.g., list, dict, set).
    • Immutable: Objects whose value cannot be changed after creation (e.g., int, float, bool, str, tuple). If you perform an operation that seems to modify an immutable object, it actually creates a new object.
  • Type Conversion (Casting):
    • Converting a value from one data type to another using built-in functions.
    • int(x): Converts x to an integer.
    • float(x): Converts x to a float.
    • str(x): Converts x to a string.
    • list(x): Converts sequence x to a list.
    • tuple(x): Converts sequence x to a tuple.
    • set(x): Converts sequence x to a set.
    • dict(...): Creates a dictionary.
    • bool(x): Converts x to a boolean (False for 0, None, empty sequences/mappings; True otherwise).
    • Example: num_str = "123"; num_int = int(num_str)

5. Operators

  • Symbols that perform operations on values (operands).
    • Arithmetic: + (add), - (subtract), * (multiply), / (float division), // (integer/floor division), % (modulo/remainder), ** (exponentiation).
    • Relational/Comparison: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to). Return True or False.
    • Assignment: = (assign), +=, -=, *=, /=, //=, %=, **= (compound assignment operators, e.g., x += 5 is shorthand for x = x + 5).
    • Logical: and (logical AND), or (logical OR), not (logical NOT). Operate on boolean values.
    • Membership: in (True if value is found in sequence), not in (True if value is not found in sequence).
    • Identity: is (True if both operands refer to the same object in memory), is not (True if they refer to different objects).
  • Operator Precedence: The order in which operations are performed (e.g., ** before *//, which are before +/-). Use parentheses () to control the order explicitly.

6. Input and Output

  • Output: print() function
    • Displays values/variables to the console.
    • Can take multiple arguments, separated by commas. By default, they are printed with a space in between.
    • sep argument: Specifies the separator between arguments (default is space ' '). print(a, b, sep='--')
    • end argument: Specifies what to print at the end (default is newline '\n'). print("Hello", end=' ')
  • Input: input() function
    • Reads a line of text from the user via the console.
    • Optionally takes a string argument as a prompt to display to the user.
    • Important: Always returns the user's input as a string (str).
    • You often need to convert the input to the desired type (e.g., int, float) using type conversion functions.
    name = input("Enter your name: ")
    age_str = input("Enter your age: ")
    age_int = int(age_str) # Convert string input to integer
    print("Hello,", name)
    print("You will be", age_int + 1, "next year.")
    

7. Debugging

  • Errors (Bugs): Problems in code that prevent it from running correctly.
    • Syntax Errors: Errors in the structure/grammar of the code (e.g., misspelled keyword, missing colon, incorrect indentation). Detected by the interpreter before execution begins.
    • Runtime Errors: Errors that occur during the execution of the program (e.g., trying to divide by zero, trying to convert a non-numeric string to int, accessing a non-existent variable). Cause the program to crash.
    • Logical Errors: Errors where the code runs without crashing but produces incorrect results because the logic implemented is flawed. Hardest to find.
  • Debugging: The process of finding and fixing errors. Simple techniques include using print() statements to check variable values at different points, reading error messages carefully, and testing code incrementally.

Multiple Choice Questions (MCQs)

  1. Which of the following correctly describes Python?
    a) Compiled, Statically Typed
    b) Interpreted, Statically Typed
    c) Compiled, Dynamically Typed
    d) Interpreted, Dynamically Typed

  2. Which symbol is used for single-line comments in Python?
    a) //
    b) /* ... */
    c) #
    d) """ ... """

  3. What is the output of print(10 // 3)?
    a) 3.333
    b) 3.0
    c) 3
    d) 1

  4. Which of the following is NOT a valid identifier name in Python?
    a) _myVar
    b) my_var_1
    c) MyVar
    d) 2myVar

  5. What data type does the input() function return by default?
    a) int
    b) float
    c) str
    d) bool

  6. Which data type in Python is immutable?
    a) list
    b) dict
    c) set
    d) tuple

  7. What defines blocks of code in Python (e.g., inside an if statement)?
    a) Curly braces {}
    b) Parentheses ()
    c) Indentation
    d) Keywords begin and end

  8. What is the output of print(type(False))?
    a) <class 'int'>
    b) <class 'str'>
    c) <class 'bool'>
    d) <class 'NoneType'>

  9. Which operator is used to check if two variables refer to the exact same object in memory?
    a) ==
    b) =
    c) is
    d) in

  10. What will be the value of result after executing the following code?

    x = 5
    y = "10"
    result = x + int(y)
    

    a) "510"
    b) 15
    c) 510
    d) TypeError


Answer Key for MCQs:

  1. d) Interpreted, Dynamically Typed
  2. c) #
  3. c) 3 (Integer division discards the remainder)
  4. d) 2myVar (Identifiers cannot start with a number)
  5. c) str
  6. d) tuple (Lists, dicts, and sets are mutable)
  7. c) Indentation
  8. c) <class 'bool'>
  9. c) is
  10. b) 15 (The string "10" is converted to an integer 10 before addition)

Study these notes thoroughly. Focus on understanding the concepts like data types, mutability, operators, and the significance of indentation. These basics are essential building blocks for more complex programming. Good luck with your preparation!

Read more