Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 4: Getting Started with Python

Python is a high-level, interpreted, and general-purpose programming language. Created by Guido van Rossum, it is renowned for its readability and simplicity.

4.1 Familiarization with Basics

Python is easy to learn and supports both procedural and object-oriented programming paradigms.

Execution Modes

  1. Interactive Mode: Commands are typed directly into the Python prompt (>>>) and executed immediately. Good for testing small snippets.
  2. Script Mode: Python code is saved in a file with a .py extension and executed as a whole. Good for writing complete programs.

Simple Program:

print("Hello World!")

4.2 Tokens and Variables

A Token is the smallest individual unit in a Python program.

  • Keywords: Reserved words with special meaning (e.g., if, for, def).
  • Identifiers: Names given to variables, functions, etc. Must start with a letter or underscore, and cannot be a keyword.
  • Literals: Data items that have a fixed value (e.g., 42, "Hello").
  • Operators: Symbols that perform operations on operands (e.g., +, -).
  • Punctuators: Symbols used to organize sentence structures in programming (e.g., ,, :, ()).

Variables, l-value, and r-value

A variable is a named memory location used to store data.

age = 16  # 'age' is the l-value, 16 is the r-value
  • l-value: An expression that can appear on the left side of an assignment (e.g., a variable name).
  • r-value: An expression that provides a value to be assigned (e.g., a literal or calculation).

Comments: Used to explain code. Python uses # for single-line comments.

4.3 Data Types

Data types define the type of data a variable can hold.

  • Number: int (integers), float (decimals), complex (real + imaginary).
  • Boolean: bool (True or False).
  • Sequence: str (String), list (mutable sequence), tuple (immutable sequence).
  • Mapping: dict (Dictionary - key/value pairs).
  • None: Represents the absence of a value.

Mutable vs Immutable:

  • Mutable: Values can be changed in place (e.g., list, dict).
  • Immutable: Values cannot be changed once created (e.g., int, float, str, tuple).

4.4 Operators

  • Arithmetic: +, -, *, /, // (floor division), % (modulus), ** (exponentiation).
  • Relational: <, >, <=, >=, ==, !=.
  • Logical: and, or, not.
  • Assignment: =, +=, -=, etc.
  • Identity: is, is not (checks memory location).
  • Membership: in, not in (checks if an item exists in a sequence).

4.5 Expressions, Type Conversion, and I/O

  • Expressions: A combination of operators and operands. Precedence rules (BODMAS/PEMDAS) apply.
  • Type Conversion:
    • Implicit: Python automatically converts types (e.g., int + float = float).
    • Explicit (Type Casting): Programmer forces conversion using functions like int(), float().
  • Input/Output:
    • input() function reads input from the user as a string.
    • print() function displays output to the console.

4.6 Errors

  1. Syntax Errors: Grammatical rules of Python are violated (e.g., missing a colon). The program won’t run.
  2. Logical Errors: The program runs but produces the wrong output due to flawed logic (e.g., using + instead of -).
  3. Run-time Errors: The program crashes during execution due to illegal operations (e.g., dividing by zero).

Competency Based Questions

Q1. Predict the Output What will be the output of the following Python code snippet?

x = 10
y = 3
print(x // y)
print(x % y)

Q2. Case-Based Scenario Rahul wrote the following code to calculate the area of a rectangle:

length = input("Enter length: ")
breadth = input("Enter breadth: ")
area = length * breadth
print("Area is", area)

When he runs the code and inputs 5 and 4, the program crashes with an error.

  1. Identify the type of error (Syntax, Logical, or Run-time).
  2. Explain why the error occurred and correct the code.

Q3. Assertion-Reasoning

  • Assertion (A): Strings and Tuples are immutable data types in Python.
  • Reason (R): Elements of an immutable data type cannot be altered or modified in-place after they are created. Choose the correct option: a) Both A and R are true and R is the correct explanation of A. b) Both A and R are true but R is NOT the correct explanation of A. c) A is true but R is false. d) A is false but R is true.

Q4. Application-Oriented Write a Python expression to check if a variable char is a vowel (i.e., ‘a’, ‘e’, ‘i’, ‘o’, ‘u’). Use the membership operator.


Answers to Competency Based Questions

A1. Output:

3
1

Explanation: // is floor division (\(10 \div 3 = 3\) remainder 1). % is the modulus operator, which returns the remainder (\(1\)).

A2.

  1. It is a Run-time error (specifically a TypeError).
  2. Explanation: The input() function always returns data as a string. You cannot multiply two strings together ("5" * "4" is invalid). Rahul needs to use explicit type conversion. Corrected Code:
length = int(input("Enter length: "))
breadth = int(input("Enter breadth: "))
area = length * breadth
print("Area is", area)

A3. a) Both A and R are true and R is the correct explanation of A. By definition, immutable objects cannot be modified after creation.

A4.

char in 'aeiouAEIOU'

(Alternatively, checking against a list: char.lower() in ['a', 'e', 'i', 'o', 'u'])