Quiz 2

Week 1: Data Types & Representation

2082 words
10 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Week 1: Data Types & Representation > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Topic 01 (What is Computational Thinking) **Cross-links:** BSCS1002-Python (Week 1 — Data Types), BSCS2002-PDSA (Week 2 — Data Structures) ## 1. Motivation: Why Data Types?

Week 1: Data Types & Representation

BSCS1001 — IIT Madras BS Degree Prerequisite: Topic 01 (What is Computational Thinking) Cross-links: BSCS1002-Python (Week 1 — Data Types), BSCS2002-PDSA (Week 2 — Data Structures)

1. Motivation: Why Data Types?

Imagine you receive a form with the following fields filled in:
FieldValueIs This OK?
NameRahul123!@#❌ Names shouldn't have numbers or special chars
Age-5❌ Age can't be negative
Marks108❌ Marks can't exceed 100
Phonehello❌ Phone should be digits
You can spot these errors because you know what kind of data each field should contain. But a computer doesn't — unless we tell it. Data types are the mechanism we use to tell the computer (or another person) what values are allowed and what operations are permitted.
Real-world analogy: A "data type" is like a mold for a key. The mold determines what shape keys can be made (allowed values) and what locks they can open (allowed operations).

What a Data Type Defines

(Diagram)

2. Sanity of Data

Sanity of data means checking that data makes sense — that values are within expected ranges and operations are meaningful.

Two Kinds of Constraints

1. Value Constraints (What values are allowed?)

Data FieldAllowed ValuesWhy?
Marks0 to 100Can't score more than 100 or less than 0
GenderM or FOnly two values (in our dataset)
NameLetters, spacesNo numbers or special characters
Date0 to 365Day of year

2. Operation Constraints (What can we do?)

DataAllowed OperationsNot Allowed
Marks+ (add), < (compare)× (multiplying marks is meaningless)
Name= (compare for equality)+ (can't add two names)
Gender= (check if equal)+, - (meaningless)

Worked Example: Sanity Check

Problem: Check if a student record is valid. Record: {Name: "Alice", Age: 22, Maths: 85, Physics: 110}
FieldSanity RuleCheckVerdict
NameOnly letters and spaces"Alice" ✅Valid
AgeBetween 0 and 15022 ✅Valid
MathsBetween 0 and 10085 ✅Valid
PhysicsBetween 0 and 100110 ❌Invalid
💡 Key Insight: Sanity of data leads directly to the concept of data types. Once we define types, sanity checks become automatic.

3. Basic Data Types

The course defines three basic data types (plus a fourth — String — which is a sequence of characters).

3.1 Boolean

The simplest data type. Named after George Boole, a mathematician.
PropertyDescription
ValuesTrue or False only
OperationsAND, OR, NOT
Result typeBoolean

Boolean Operations (Truth Tables)

AND (AND): True only when BOTH inputs are True.
ABA AND B
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue
OR (OR): True when AT LEAST ONE input is True.
ABA OR B
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue
NOT (NOT): Flips the value.
ANOT A
TrueFalse
FalseTrue

Worked Example: Boolean Evaluation

Evaluate: (True AND False) OR (NOT False)
StepExpressionResult
1True AND FalseFalse
2NOT FalseTrue
3False OR TrueTrue

3.2 Integer

Whole numbers (positive, negative, and zero).
PropertyDescription
Values..., -3, -2, -1, 0, 1, 2, 3, ...
Operations+, -, ×, / (result: Integer)
Comparisons``, = (result: Boolean)

Integer Operations Examples

OperationResultData Type of Result
3 + 58Integer
10 - 73Integer
4 × 624Integer
7 < 3FalseBoolean
5 = 5TrueBoolean
⚠️ Note: In this course, integer division / may produce non-integer results, so we mostly use +, -, × for integers.

3.3 Character

A single letter, digit, or symbol.
PropertyDescription
ValuesA–Z, a–z, 0–9, special characters
Operations= (compare for equality)
Result typeBoolean
Examples of characters: 'A', 'z', '5', '?', ' ' (space) Special characters: , ; : * / & % $ # @ !

3.4 String

A sequence of characters.
PropertyDescription
ValuesAny sequence of characters, e.g., "Hello", "Alice", "M"
Operations= (equality), char in string? (checking membership)
Result typeBoolean; Boolean
Key difference: A Character is a single symbol, a String is a sequence of zero or more characters.

4. Subtypes

A subtype is a more restricted version of a basic type. It limits the allowed values and/or operations.

Why Subtypes?

A plain Integer is too broad. Consider:
  • Marks: Should be 0–100, not any integer
  • Count: Should be 0 or positive, not negative
  • Date: Should be 0–365, not any integer Subtypes allow us to create more specific, meaningful types.

Integer Subtypes

SeqNo (Sequence Number)

pseudo
Range:     0, 1, 2, ..., Max (e.g., 10000)
Operations: None of the integer operations make sense
Purpose:   Identifies a card/row uniquely

Marks

pseudo
Range:     0, 1, 2, 3, ..., 100
Operations: +, - (result: Marks);  <, >, = (result: Boolean)
NOT allowed: ×, ÷ (multiplying marks makes no sense!)

Count

pseudo
Range:     0, 1, 2, 3, ...
Operations: +, - (result: Count); <, >, = (result: Boolean)
NOT allowed: ×, ÷

Date (Day of Year)

python
Range:     0, 1, 2, 3, ..., 365
Operations: print (result: String); <, >, = (result: Boolean)
Meaning:  0 = "1 Jan", 31 = "1 Feb", 365 = "31 Dec"

Character Subtypes

Gender

pseudo
Values:    'M' or 'F'
Operation: = (compare)
Result:    Boolean

String Subtypes

Names

pseudo
Values:    Strings with no special characters
Operation: =
Result:    Boolean

City

pseudo
Values:    Strings with no special characters
Operation: =
Result:    Boolean

Words

pseudo
Values:    Strings with alphanumeric and punctuation
Operation: =
Result:    Boolean

Category

pseudo
Values:    One of: "Noun", "Verb", "Preposition", "Adjective"
Operation: =
Result:    Boolean

Subtype Hierarchy Diagram

(Diagram)

5. Type Transformations

Sometimes we need to convert data from one type to another.

Date to String Transformation

Dates are stored as integers (0–365) but displayed as strings.
Integer ValueDisplay String
0"1 Jan"
31"1 Feb"
59"1 Mar"
python
print(0)   →  "1 Jan"
print(31)  →  "1 Feb"
print(365) →  "31 Dec"

Fractional Marks Transformation

In this course, we avoid floating-point numbers by scaling:
  • Actual mark: 62.5
  • Stored as integer: 6250 (multiply by 100)
  • Display: print(6250)"62.5" (divide by 100 when printing)
pseudo
Value to store = Original mark × 100
Display value  = Stored value ÷ 100
Example:
OriginalScaled (×100)Stored TypeOperationPrinted
76.257625Integer+, -"76.25"
82.58250Integer+, -"82.5"
91.09100Integer+, -"91.0"
Why do this? Integers are simpler, faster, and avoid rounding errors that occur with decimal numbers.

6. Records: Grouping Data Together

A Record (also called struct or tuple) is a data type with multiple named fields, each of which has a name and a value.

Record Example: Marks Card

(Diagram)

Why Records?

Without records, we'd need separate variables for every attribute of every student, which is impossible for a class of 200.
Without RecordsWith Records
Alice_Maths, Bob_Maths, Charlie_Maths...Each card X has X.Maths
Need 200 variables for each subjectOne record type, many instances
Cannot write generic proceduresCan write procedures that work on any card

Accessing Record Fields

We use dot notation: RecordName.FieldName
pseudo
X.Maths     ← The Maths field of card X
X.Name      ← The Name field of card X
X.Gender    ← The Gender field of card X

Other Record Examples

Word in Paragraph Record

FieldData Type
SerialNoSeqNo
WordWords
PartOfSpeechCategory

Shopping Bill Record

FieldData Type
CustomerNameNames
ItemNameWords
CategoryCategory
QuantityCount
AmountMarks (type, for cost)

7. Lists: Sequences of Data

A List is a sequence of data elements, all of the same type.

List vs Record

RecordList
Groups different types of dataGroups same type of data
Fields have namesElements have positions
Example: A single student's dataExample: All students' IDs

Examples of Lists

List NameElement TypeDescription
MarksCardListMarksCard RecordAll marks cards in the dataset
ParagraphWordListWordInPara RecordAll words in a paragraph
ShoppingBillListShoppingBill RecordAll shopping bills
ItemListItem RecordItems in a single bill

Visual Representation

pseudo
MarksCardList = [Card1, Card2, Card3, ..., CardN]
                  ↑       ↑       ↑           ↑
                 SeqNo=1 SeqNo=2 SeqNo=3    SeqNo=N

Key Point About Lists

  • All elements in a list are usually of the same data type
  • Lists can be iterated over (the iterator pattern from Topic 01)
  • Lists can be built gradually by appending elements
Preview: We'll work extensively with lists starting in Week 5. For now, just understand that a list is a collection of items arranged in a specific order.

8. Comparison of Data Types

Basic Data Types Summary Table

TypeValuesOperationsResult TypesUse Case
BooleanTrue, FalseAND, OR, NOTBooleanConditions, flags
Integer..., -2, -1, 0, 1, 2, ...+, -, ×, /, , =Integer, BooleanCounts, sums, indices
CharacterA-Z, a-z, 0-9, special chars=BooleanSingle letters, gender codes
StringAny character sequence=, char-in-string?BooleanNames, words, categories

Type vs Subtype

AspectBasic TypeSubtype
RangeBroad (e.g., all integers)Restricted (e.g., 0-100)
OperationsAll type operationsSubset of operations
ExampleInteger → MarksMarks: 0-100, no ×, ÷

Record vs List

AspectRecordList
StructureNamed fieldsPositional elements
Element typesCan be differentSame type preferred
AccessBy field name: X.NameBy position
AnalogyA row in a tableThe whole table

9. Practice Questions

Basic Questions

Q1. Which basic data type has only two possible values?
Show Answer
Boolean — values are True and False. Q2. Evaluate: (NOT (True AND False)) OR (False AND True) Show Answer
StepExpressionResult
1True AND FalseFalse
2NOT FalseTrue
3False AND TrueFalse
4True OR FalseTrue
Q3. What is the range of values for the Marks subtype?
Show Answer
Marks range from 0 to 100 (inclusive). Q4. Which of these operations are allowed on a Gender field? (a) + (b) = (c) × (d) < Show Answer
Only (b) = (comparison for equality) is allowed on Gender. Arithmetic operations like +, ×, < are meaningless.

Intermediate Questions

Q5. What is wrong with storing marks as a plain Integer data type? Why do we need a Marks subtype?
Show Answer
If marks are stored as Integer, the computer would allow:
  • Negative marks (-5) → invalid
  • Marks above 100 (150) → invalid
  • Multiplication of marks → meaningless
A Marks subtype restricts:
  • Range to 0-100
  • Operations to +, -, <, >, = only (no ×, ÷) Q6. Convert these fractional marks to their scaled integer representation: (a) 45.75 (b) 80.0 (c) 99.99 Show Answer
OriginalScaled (×100)
45.754575
80.08000
99.999999
Q7. If Date values are stored as integers 0-365, what date does value 59 represent? (Hint: 0 = 1 Jan, 31 = 1 Feb)
Show Answer
  • 0 = 1 Jan (31 days in January)
  • 31 = 1 Feb (28 days in February in non-leap year)
  • 31 + 28 = 59 = 1 March Q8. What is the difference between a Record and a List? Give one example of each. Show Answer
AspectRecordList
FieldsNamed (e.g., X.Name, X.Maths)Positional (by index)
TypesCan mix typesUsually same type
ExampleA single MarksCard (has Name, Maths, Physics, etc.)MarksCardList (all cards together)

Advanced Questions

Q9. Design a Record type for a Library Book. What fields would it have and what data types/subtypes would each field use?
Show Answer
java
Record: Book
    - BookID:        SeqNo (unique identifier)
    - Title:         String (book name)
    - Author:        Names (author name)
    - ISBN:          String (unique book number)
    - YearPublished: Integer (subtype: 1900-2024)
    - Pages:         Count (number of pages)
    - IsIssued:      Boolean (True if checked out)
    - Category:      String (subtype: Fiction/Non-fiction/Reference)
Q10. Can you add two Names together? Can you compare two Names with =? Explain why or why not for each.
Show Answer
  • = (equality): ✅ Yes! We can check if two names are the same (e.g., "Alice" == "Alice" → True). Result is Boolean.
  • + (addition): ❌ No! Adding names doesn't make sense — what would "Alice" + "Bob" mean? Names are identifiers, not quantities.
This is exactly what data types enforce: only meaningful operations are allowed. Q11. Explain why marks × marks is not allowed but marks + marks is allowed. Show Answer
  • marks + marks: Adding marks makes sense — we sum scores to get a total. The result is also of type Marks (or Total).
  • marks × marks: Multiplying marks has no real-world meaning. What would "85 × 72" represent? It's not a score, not a count, nothing useful. The Marks subtype correctly forbids this.
This illustrates the key principle: data types model real-world constraints. Q12. Trace the Boolean expression: (A OR B) AND (NOT A) for all four combinations of A and B. Show Answer
ABA OR BNOT A(A OR B) AND (NOT A)
FFFTF
FTTTT
TFTFF
TTTFF
The expression is True only when A is False AND B is True.

📚 Cross-References

CourseTopicConnection
BSCS1002 (Python)Week 1 — Data TypesPython's int, bool, str types
BSCS1002 (Python)Week 2 — OperatorsBoolean operators in Python
BSCS2002 (PDSA)Week 1 — Abstract Data TypesFormal definition of types

Quiz Tip: Questions about allowed operations on specific data types are very common in Quiz 1. Memorize the operation tables! Join Discord PreviousWhat is Computational Thinking?NextPseudocode Basics
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.