Top Banner Ad

BCC302 — Unit 1: Introduction to Python

Table of Contents (27 sections)

BCC302 · Python Programming · Unit 1

Introduction to Python

Unit Scope & Exam Weightage: This unit builds the base of Python programming: variables and dynamic typing, arithmetic/comparison/logical/membership/identity operators, indentation-based blocks, and numeric, string and boolean data types with type conversion. The supplied 2023-24 to 2025-26 question set contains 17 recorded clusters; 7-mark questions repeatedly ask for operator tables, data-type explanations and short programs (even/odd, calculator, set difference, regex digits).


Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Python basic Operators 7 (2023-24 ×3, 2024-25 ×3, 2025-26 ×2) 2m ×3 + 7m ×5 Survival Mode
2 Python Data Types 6 (2023-24 ×3, 2024-25, 2025-26 ×3) 2m ×2 + 7m ×4 High-Yield
3 Python variables 3 (2023-24, 2024-25, 2025-26) 2m + 7m ×2 Core Concept
4 Understanding python blocks 2 (2024-25, 2025-26) 2m + 7m Syntax Rule
5 Declaring and using Numeric data types: int, float etc Integrated in #1–#2 — Worked Examples

2-Hour Last-Night Survival Checklist:

  1. Operators (Priority 1): Memorise six groups with one example each: arithmetic (/ vs //), comparison, logical (and/or/not), assignment (+=), membership (in), identity (is).
  2. Floor division (frequent 2-marker): 7/2 = 3.5, 7//2 = 3, 7%2 = 1; for negatives remember Python floors toward −∞: -7//3 = -3, -7%3 = 2.
  3. Data types (Priority 2): Write int, float, complex, bool, str, list, tuple, dict, set with type() outputs; know chr(65) → 'A' and ord('A') → 65.
  4. Blocks (Priority 4): State the four rules — colon, consistent indentation, no braces, block ends when indentation decreases.
  5. Programs: Keep four 8-line programs ready: even/odd, calculator, set difference, regex digit extraction.

1. Python Variables and Dynamic Typing

Variable (2 Marks): A named reference to a value stored in memory. In Python, no type declaration is needed — the interpreter infers the type from the value assigned, and the same name can later refer to a value of another type.

roll_no = 21          # int
name = "Asha"         # str
percentage = 88.5     # float
passed = True         # bool
print(roll_no, type(roll_no))   # 21 <class 'int'>
roll_no = "BCA"       # legal: name now refers to a str
print(roll_no, type(roll_no))   # BCA <class 'str'>

1.1 Rules for Identifiers

  1. May contain letters, digits and underscore; cannot start with a digit.
  2. Case-sensitive: marks and Marks are different variables.
  3. Cannot use reserved words (if, for, class, None, True, etc.).
  4. Convention: snake_case for variables, UPPER_CASE for constants.
  5. Multiple assignment: a = b = 0; unpacking: x, y = 10, 20; swap: x, y = y, x.

1.2 References, Not Boxes

x = 10 creates an integer object with value 10 and binds the name x to it. y = x binds y to the same object; id(x) == id(y). Rebinding y = 20 creates a new object; x is unchanged. Integers and strings are immutable, so operations produce new objects.

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart LR
    X["name x"] --> OBJ["int object 10<br/>id = 1407..."]
    Y["name y after y = x"] --> OBJ
    Y2["y = 20 → new object"] --> OBJ2["int object 20"]

After-Topic PYQs:

  • 2024-25, 2025-26 (Sec A, 2 Marks): "What are variables in Python?"
  • 2025-26 (Sec C, 7 Marks): "Write a Python program using variables and operators to calculate the sum of two numbers."
  • 2023-24 (Sec C, 7 Marks): "Explain the concept of dynamic typing in Python with an example."

2. Python Basic Operators

Operator: A symbol that applies an operation to operands. Python groups operators as arithmetic, relational/comparison, logical, assignment, bitwise, membership and identity.

2.1 Arithmetic Operators (a = 7, b = 3)

Operator Name Expression Result
+ Addition a + b 10
- Subtraction a - b 4
* Multiplication a * b 21
/ True division (always float) a / b 2.333...
// Floor division a // b 2
% Modulus (remainder) a % b 1
** Exponentiation a ** b 343

Floor division trap (asked in 2024-25): a // b gives the quotient floored to the nearest integer toward negative infinity, while a % b has the sign of the divisor. Check: -7 // 3 == -3 and -7 % 3 == 2, because (-3) * 3 + 2 = -7. In contrast, 7 // -3 == -3 and 7 % -3 == -2.

2.2 Comparison, Logical, Assignment and Bitwise

Group Operators Example (a=7, b=3) Result
Comparison == != > < >= <= a > b, a == b True, False
Logical and, or, not a > 0 and b > 0 True
Assignment = += -= *= /= //= %= **= a += b → a = 10 updated value
Bitwise & | ^ ~ << >> 7 & 3 (0111 & 0011) 3 (0011)
Membership in, not in 'a' in "cat" True
Identity is, is not a is b See Section 2.3

Short-circuiting: A and B does not evaluate B if A is false; A or B does not evaluate B if A is true. This is used in guards such as if denom != 0 and x/denom > 1:.

2.3 == vs is (Asked Twice)

  • == compares values (calls __eq__).
  • is compares object identity (id() equality).
a = 3
b = 3
print(a == b)   # True — same value
print(a is b)   # True here: CPython interns small integers (-5..256)
x = 1000
y = 1000
print(x == y)   # True
print(x is y)   # implementation-dependent; do NOT rely on it
s = None
print(s is None)  # correct way to test for None

Examiner conclusion: use == for value comparison and is only for singletons (None, True, False) or when identity is explicitly required.

2.4 Precedence (Highest → Lowest)

Level Operators
1 () parentheses
2 ** (right-associative)
3 unary +, -, ~, not
4 * / // %
5 + -
6 << >>
7 &
8 ^
9 |
10 comparisons == != < > <= >=
11 and
12 or

Example: 2 + 3 * 4 ** 2 == 50 → 4**2=16, 3*16=48, 2+48=50. Use parentheses to remove ambiguity.

After-Topic PYQs:

  • 2024-25, 2025-26 (Sec C, 7 Marks): "Explain different types of basic operators in Python with examples."
  • 2023-24 (Sec A, 2 Marks): "Give difference between ==== and is operator."
  • 2024-25 (Sec A, 2 Marks): "Explain floor division with an example."
  • 2023-24 (Sec A, 2 Marks): "Differentiate between / and // operator with an example"
  • 2024-25 (Sec C, 7 Marks): "Define Membership and Identity Operators. Given: a = 3, b = 3. Distinguish between: (a is b) and (a == b)."
  • 2024-25 (Sec C, 7 Marks): "Design a basic calculator in Python that supports addition, subtraction, multiplication, division."

3. Understanding Python Blocks and Indentation

Block: A group of statements that belong together, introduced by a compound statement ending in a colon (:) and delimited by consistent indentation. Python has no braces or endif/endfor keywords.

marks = 75
if marks >= 40:              # colon starts the block
    print("Pass")            # 4 spaces inside the block
    print("Eligible for next sem")
else:                        # dedent ends the previous block
    print("Fail")
print("Program continues")   # outside both blocks

Four rules to write in answers:

  1. A colon after if / else / for / while / def / class begins a block.
  2. Every statement in the block must be indented by the same number of spaces (PEP 8: four).
  3. Mixing tabs and spaces causes TabError; inconsistent indentation causes IndentationError.
  4. The block ends when indentation returns to the previous level; blank lines do not end it.

After-Topic PYQs:

  • 2025-26 (Sec A, 2 Marks): "What is a block in Python?"
  • 2024-25 (Sec C, 7 Marks): "Write short notes on the following with examples:\na) Operator Precedence\nb) Python Indentation\nc) Type Conversion"

4. Python Data Types and Type Casting

4.1 Built-in Data Types

Category Types Example Mutable?
Numeric int, float, complex 7, 3.14, 2+3j No
Boolean bool True, False (subclass of int) No
Text str "Python" No
Sequence list, tuple, range [1,2], (1,2) list yes; tuple no
Mapping dict {"roll":21} Yes
Set set, frozenset {1,2} set yes; frozenset no
None NoneType None —

4.2 Numeric Types (int, float etc.)

  • int: arbitrary-precision integer; supports binary 0b1010, octal 0o12, hex 0xA, underscores 1_000.
  • float: IEEE-754 double approximation; decimal literals 3.14, scientific 1.5e3.
  • complex: a + bj; .real and .imag attributes.
  • bool: True == 1 and False == 0 in arithmetic, but printing gives True/False.
>>> type(7), type(7.0), type(2+3j), type(True)
(<class 'int'>, <class 'float'>, <class 'complex'>, <class 'bool'>)
>>> 5 / 2, 5 // 2, 5 % 2
(2.5, 2, 1)

4.3 Type Conversion (Casting)

s = "25"
n = int(s)          # "25" → 25
f = float(n)        # 25 → 25.0
back = str(f)       # 25.0 → "25.0"
ch = chr(65)        # 'A'  (ASCII value → character)
code = ord('A')     # 65  (character → ASCII value)
print(f"{n} {f} {back} {ch} {code}")
  • Implicit conversion: 7 + 2.5 → 9.5 (int promoted to float).
  • Explicit conversion: int(3.9) → 3 (truncates toward zero), float("3.5") → 3.5; invalid strings raise ValueError.

After-Topic PYQs:

  • 2024-25, 2025-26 (Sec C, 7 Marks): "What are Python data types? Explain numeric, string, and boolean data types."
  • 2024-25 (Sec A, 2 Marks): "Write a Python program to demonstrate type casting between int, float, and string."
  • 2023-24 (Sec A, 2 Marks): "How we print the character of a given ASCII value in Python?"

5. Sets and Regular Expressions (Data-Type Extensions)

5.1 Sets

A set is an unordered collection of unique, hashable values enclosed in braces; it removes duplicates and supports mathematical operations.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)   # union      {1,2,3,4,5,6}
print(A & B)   # intersection {3,4}
print(A - B)   # difference   {1,2}
print(A ^ B)   # symmetric difference {1,2,5,6}
print(A.issubset({1,2,3,4,5}))  # True

Program — difference between two sets:

a = set(input("Set A values: ").split())
b = set(input("Set B values: ").split())
print("A - B:", a - b)
print("B - A:", b - a)
print("Symmetric difference:", a ^ b)

5.2 Regular Expressions with re

Regular expression: A pattern describing a set of strings. Python's re module compiles the pattern and provides search(), match(), findall() and sub().

Pattern Meaning
\d any digit 0-9
\w word character (letter, digit, underscore)
\s whitespace
. any character except newline
+ / * / ? one-or-more / zero-or-more / optional
[abc] one of a, b, c
import re
text = "BCA302 has 5 units and 70 marks"
print(re.findall(r'\d+', text))   # ['302', '5', '70']
print(re.sub(r'\d+', '#', text))  # BCA# has # units and # marks

After-Topic PYQs:

  • 2025-26 (Sec C, 7 Marks): "Explain sets and their operations. Write a program to find difference between two sets."
  • 2025-26 (Sec C, 7 Marks): "Describe regular expressions using re module. Write a program to find all digits in a string."

Solved Exam-Ready Questions

Solved Q1 (2024-25, 2025-26 Sec C — 7 Marks | Survival Mode)

Q: Explain different types of basic operators in Python with examples.

Solution: Present the seven groups with one evaluated example each:

  1. Arithmetic: + - * / // % ** with 7,3 → 10, 4, 21, 2.333..., 2, 1, 343. Emphasise / returns float and // floors.
  2. Relational/comparison: == != > < >= <= return bool; 7 > 3 → True.
  3. Logical: and, or, not; True and False → False; short-circuit behaviour saves work.
  4. Assignment: =, +=, -=, *=, /=, //=, %=, **=; x += 1 means x = x + 1.
  5. Bitwise: & | ^ ~ << >>; 7 & 3 = 3, 1 << 3 = 8.
  6. Membership: in, not in; 'a' in "cat" → True.
  7. Identity: is, is not; compares id(), use for None. Close with a precedence note: ** before * / // % before + -, parentheses override all.

Solved Q2 (2024-25, 2025-26 Sec C — 7 Marks)

Q: What are Python data types? Explain numeric, string, and boolean data types.

Solution:

  • Meaning: A data type classifies a value and determines the operations and memory representation available; Python infers it at runtime (dynamic typing).
  • Numeric: int (arbitrary precision, 0b/0o/0x literals), float (decimal/scientific, 5/2 = 2.5), complex (2+3j, .real/.imag). Show type(7) → <class 'int'>.
  • String: immutable sequence of Unicode characters; indexing s[0], slicing s[1:4], concatenation +, repetition *, methods upper(), split(), strip(); "A" * 3 → "AAA".
  • Boolean: bool with True/False; True == 1, False == 0; results of comparisons and logical operations; used in if conditions.
  • Other containers: list, tuple, dict, set (name them briefly).
  • Conversion: int("25"), float(7), str(3.5), chr(65) → 'A', ord('A') → 65.

Solved Q3 (2025-26 Sec C — 7 Marks)

Q: Explain Python basic operators and data types. Write a program to check if a number is even or odd using if-else.

Solution:

  • Theory: Summarise the operator groups from Solved Q1 and the data types from Solved Q2; state that % gives the remainder and comparison operators produce bool values used by if.
  • Logic: read input as int, compute n % 2; remainder 0 means even, otherwise odd.
  • Program:
n = int(input("Enter an integer: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
  • Trace: input 27 → 27 % 2 = 1 → condition false → prints 27 is odd.
  • Note: input() returns a string, so int() conversion is mandatory; without it, comparing with 0 raises a TypeError.

Solved Q4 (2024-25 Sec C — 7 Marks)

Q: Design a basic calculator in Python that supports addition, subtraction, multiplication, division.

Solution:

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("1 Add\n2 Subtract\n3 Multiply\n4 Divide")
choice = int(input("Enter choice (1-4): "))

if choice == 1:
    print("Result:", a + b)
elif choice == 2:
    print("Result:", a - b)
elif choice == 3:
    print("Result:", a * b)
elif choice == 4:
    if b != 0:                 # guard against division by zero
        print("Result:", a / b)
    else:
        print("Cannot divide by zero")
else:
    print("Invalid choice")

Explanation: float() allows decimal inputs; elif selects exactly one operation; the nested if b != 0 prevents ZeroDivisionError. Sample run: a=8, b=2, choice=4 → Result: 4.0.


Solved Q5 (2024-25 Sec C — 7 Marks)

Q: Define Membership and Identity Operators. Given: a = 3, b = 3. Distinguish between: (a is b) and (a == b).

Solution:

  • Definitions: Membership operators in / not in test whether a value exists in a sequence or collection. Identity operators is / is not test whether two names refer to the same object (id(a) == id(b)).
  • Given: a = 3; b = 3.
  • Value comparison: a == b → True, because both objects hold the integer value 3.
  • Identity comparison: a is b → True in CPython, because small integers from −5 to 256 are interned and reused.
  • Important caution: for x = 1000; y = 1000, x == y is True but x is y may be False; identity is an implementation detail, so never use is for numeric/string value tests.
  • Correct use: if name is None: for singletons; '3' in "BCA302" for membership.

Solved Q6 (2025-26 Sec C — 7 Marks)

Q: Explain sets and their operations. Write a program to find difference between two sets.

Solution:

  • Set: unordered collection of unique hashable values; duplicates are automatically removed; written {1, 2} or set(list).
  • Operations with A={1,2,3,4}, B={3,4,5,6}: union A|B={1,2,3,4,5,6}; intersection A&B={3,4}; difference A-B={1,2}; symmetric difference A^B={1,2,5,6}; methods add(), remove(), discard(), issubset().
  • Program:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("A - B:", A - B)              # {1, 2}
print("B - A:", B - A)              # {5, 6}
print("Symmetric difference:", A ^ B)  # {1, 2, 5, 6}
  • Note: sets are unordered, so printing order may vary; never index a set. set() creates an empty set (while {} creates an empty dictionary).

Solved Q7 (2025-26 Sec C — 7 Marks)

Q: Describe regular expressions using re module. Write a program to find all digits in a string.

Solution:

  • Concept: A regular expression is a pattern matched against text; re provides findall, search, match, sub and split. Use raw strings (r'...') so backslashes are not escaped by Python.
  • Metacharacters: \d digit, \w word char, \s space, . any char, + one-or-more, * zero-or-more, ? optional, [ ] character class, ^/$ anchors.
  • Program:
import re
s = input("Enter a string: ")
digits = re.findall(r'\d+', s)
print("Digits found:", digits)
print("As integers:", [int(d) for d in digits])
  • Trace: input "BCA302 has 5 units" → findall(r'\d+') → ['302', '5'] → integers [302, 5].
  • Why +: without it, \d returns individual digits ['3','0','2','5']; with it, consecutive digits form whole numbers.

Solved Q8 (2024-25 Sec C — 7 Marks)

Q: Write short notes on the following with examples:\na) Operator Precedence\nb) Python Indentation\nc) Type Conversion

Solution:

  • a) Operator precedence: Determines evaluation order when several operators appear together: () → ** → unary signs → * / // % → + - → comparisons → not/and/or. Example 2 + 3 * 4 ** 2 = 50; (2+3)*4**2 would be 80.
  • b) Python indentation: Blocks are defined by indentation after a colon; four spaces per level is the convention. Incorrect indentation raises IndentationError; mixing tabs and spaces raises TabError. Example: if marks >= 40: followed by an indented print("Pass").
  • c) Type conversion: Changing a value from one type to another. Implicit: 5 + 2.5 → 7.5. Explicit: int("12"), float(3), str(3.5), chr(65) → 'A', ord('A') → 65; bad conversions such as int("abc") raise ValueError.
  • Conclusion: these three rules together explain how Python reads, groups and evaluates a program.

Practice Questions (Self-Test)

  1. (2 Marks) Differentiate / from // with 7 and 2.
  2. (2 Marks) What will print(chr(66), ord('B')) display? (Ans: B 66)
  3. (2 Marks) What is a block in Python? Which error occurs for inconsistent indentation?
  4. (7 Marks) Write a program to calculate the sum of two numbers using variables and operators.
  5. (7 Marks) Explain dynamic typing with a program that rebinds one variable to three different types.
  6. (7 Marks) Write a program that reads three numbers and prints the largest using comparison and logical operators.
  7. (7 Marks) Demonstrate implicit and explicit type conversion with at least five examples.