0% found this document useful (0 votes)
1 views116 pages

CSE23CL203 Lecture1 IntroPython DataTypes

This document outlines a hands-on Python laboratory course focused on teaching Python programming and data types over 60 hours. It covers essential topics such as Python installation, variables, input/output, and data types, with a structured syllabus and practice exercises. The course emphasizes interactive and script modes for coding, aiming to build foundational skills for future programming tasks.

Uploaded by

geethaav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views116 pages

CSE23CL203 Lecture1 IntroPython DataTypes

This document outlines a hands-on Python laboratory course focused on teaching Python programming and data types over 60 hours. It covers essential topics such as Python installation, variables, input/output, and data types, with a structured syllabus and practice exercises. The course emphasizes interactive and script modes for coding, aiming to build foundational skills for future programming tasks.

Uploaded by

geethaav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python & Data Types

Lecture 1 | CSE23CL203 – Hands-on Python Laboratory | CO1

Ms. A.V. Geetha


Dept. of Artificial Intelligence & Data Analytics
Sri Ramachandra Faculty of Engineering & Technology, SRIHER
Academic Year 2026–27
Welcome to the Course 10% | Pre-Instructional

What This Lab Course Is About


This is a hands-on course – you learn Python mainly by typing code yourself. Over 60 hours (5 units,
12 hours each), you will move from writing your very first line of Python to building small data-analysis
and text-processing tools.

Think Before Learning


On paper, write down: “One task I do on a computer that I wish could happen automatically.” We
revisit this when discussing why programming languages exist.

Hands-on Python Laboratory Introduction to Python & Data Types 2/72


Learning Objectives

¥ Describe what Python is and why it is widely used.


¥ Set up Python and run a program in script and interactive mode.
¥ Use variables, identifiers, and basic input/output correctly.
¥ Work with numeric data types and strings.
¥ Convert between data types safely.

CO: CO1 Bloom’s: Understand

Why This Matters


Every later unit – lists, functions, classes, file handling, data visualization – is written using the
basic vocabulary you learn today: variables, data types, and how a program talks to its user through
input/output.

Hands-on Python Laboratory Introduction to Python & Data Types 3/72


Module 1 Syllabus – Introduction to Python (12 Hours)

Unit 1 Topics (as per Course Plan)


Lecture Topics Hours
1 Python overview, features, installation, variables, identifiers, I/O, nu- 4
meric types, strings, type conversion
2 Lists, Tuples, Dictionaries, Sets – operations, methods, comparison 4
3 Loops (for, while), Conditional statements (if-elif-else) 2
4 String manipulation (recap); Functions and Modules (def, parameters, 1
return, import)
5 File Handling – read/write/append, with statement, CSV basics 1

You Are Here


Lecture 1 of 5 – Introduction to Python & Data Types. This lecture and the next (Lists/Tuples/Dicts/Sets)
together form the first 1.5-week block (4 hrs/week).

Hands-on Python Laboratory Introduction to Python & Data Types 4/72


How You Will Practice in This Lab

Two-Step Practice Workflow


For every exercise in this course, follow this order:

 Step 1 – Interactive Mode (Jupyter Notebook / IDLE)


Try the exercise here first. Run one line at a time, see results immediately, and experiment freely if
something goes wrong. This is where you think and explore.

 Step 2 – VS Code (Script Mode)


Once it works, rewrite the same solution as a proper .py file in VS Code and run it as a whole. This is
where you build the habit of writing clean, complete, reusable programs – the way real projects are
written.

‡ Exam Tip
Interactive Mode = quick thinking. VS Code = professional habit. You need both.

Hands-on Python Laboratory Introduction to Python & Data Types 5/72


Roadmap for This Lecture

Block A Block B Block C


Block D
Python Overview Variables, Numeric Types
Type Conversion
& Installation Identifiers, I/O & Strings

l Industry Connection
Almost every software job – web apps, AI models, automated reports – is written as text files full
of variables and simple statements exactly like the ones in this lecture. There is no “jump ahead” –
everyone starts here.

Hands-on Python Laboratory Introduction to Python & Data Types 6/72


Block A
Python Overview, Features & Installation
What Is a Programming Language?

Programming Language
A programming language is a set of instructions, written in a fixed vocabulary and grammar, that a
computer can follow exactly. There is no guessing what you meant – the computer does precisely what
is written.
Why Python?
■ High-level: reads almost like plain English, hides low-level machine details.
■ Interpreted: code runs line by line via an interpreter (no separate compile step needed before testing).
■ Dynamically typed: no need to declare data types explicitly.
■ Huge collection of ready-made tools (libraries) for data analysis, automation, web development, and AI.

Hands-on Python Laboratory Introduction to Python & Data Types 8/72


Key Features of Python

Feature Highlights
■ Simple & readable syntax – close to English, minimal punctuation.
■ Free & open-source – no license cost, large community.
■ Portable – same code runs on Windows, Linux, macOS.
■ Extensive standard library – “batteries included” (file handling, math, dates, etc. built in).
■ Object-oriented – supports organizing code into classes and objects (Unit 2).

‡ Exam Tip
Remember Python is both interpreted (runs step by step) and dynamically typed (types decided auto-
matically) – a common two-mark question.

Hands-on Python Laboratory Introduction to Python & Data Types 9/72


Installing and Running Python

Interpreter
The interpreter is the program that reads your Python code and executes it. Installing “Python” on
your machine means installing this interpreter (from [Link], or bundled inside tools like Ana-
conda/Jupyter).

Script Mode
Write code in a .py file, then run the whole file at Interactive Mode
once: Run code cell-by-cell or line-by-line in Jupyter
Notebook/IDLE and see results immediately – best
python hello .py
for learning and experimenting.
Best for programs you will reuse.

Hands-on Python Laboratory Introduction to Python & Data Types 10/72


Your First Python Program

Say Hello
Type this in a file (say [Link]) or an interactive cell:

print ("Hello , World !")

Hands-on Python Laboratory Introduction to Python & Data Types 11/72


Your First Python Program

Say Hello
Type this in a file (say [Link]) or an interactive cell:

print ("Hello , World !")

 What Just Happened?


■ print(...) is a function – a ready-made instruction that performs an action (displaying text). Functions
are studied properly in Session 5.
■ Text inside quotes is a string – covered in Block C.
■ Python reads your file top to bottom, one line at a time.

Hands-on Python Laboratory Introduction to Python & Data Types 11/72


Syntax Recap – Block A

All Syntax Covered So Far

print ("text") # display output


python filename .py # run a script from terminal
# this is a comment # ignored by Python

Before You Try the Exercises


Make sure you can explain: what print() does, the difference between Script Mode and Interactive
Mode, and why Python needs no type declaration.

Hands-on Python Laboratory Introduction to Python & Data Types 12/72


Quick Check – Block A (Q1)

Q1
Python code runs line by line through an interpreter, without a separate compile step. What is this
behaviour called?

Hands-on Python Laboratory Introduction to Python & Data Types 13/72


Quick Check – Block A (Q1)

Q1
Python code runs line by line through an interpreter, without a separate compile step. What is this
behaviour called?
 Answer
Interpreted execution.

Hands-on Python Laboratory Introduction to Python & Data Types 13/72


Quick Check – Block A (Q2)

Q2
True or False: You must write int age = 20 in Python, declaring the type before the variable name.

Hands-on Python Laboratory Introduction to Python & Data Types 14/72


Quick Check – Block A (Q2)

Q2
True or False: You must write int age = 20 in Python, declaring the type before the variable name.

 Answer
False. Python uses dynamic typing – just write age = 20; Python infers the type automatically.

Hands-on Python Laboratory Introduction to Python & Data Types 14/72


Syntax Assessment – Block A (5 Questions)

Answer in one line each


1. Command to run a script named [Link] from the terminal?
2. Function used to display output on screen?
3. True/False: Python requires explicit type declaration before use.
4. Symbol that starts a single-line comment?
5. Which mode runs code cell-by-cell, best for experimenting?

Hands-on Python Laboratory Introduction to Python & Data Types 15/72


Syntax Assessment – Block A (Answers)

 Answers
1. python [Link]
2. print()
3. False – dynamic typing
4. #
5. Interactive Mode (Jupyter Notebook / IDLE)

Hands-on Python Laboratory Introduction to Python & Data Types 16/72


Practice Exercise 1 – Block A

Try Interactive Mode first, then VS Code.

Exercise 1
Write one line of code that prints Welcome to Python Lab.

Hands-on Python Laboratory Introduction to Python & Data Types 17/72


Practice Exercise 1 – Block A

Try Interactive Mode first, then VS Code.

Exercise 1
Write one line of code that prints Welcome to Python Lab.

 Hint
Which function displays text on screen? What punctuation must surround plain text?

Hands-on Python Laboratory Introduction to Python & Data Types 17/72


Practice Exercise 1 – Block A

Try Interactive Mode first, then VS Code.

Exercise 1
Write one line of code that prints Welcome to Python Lab.

 Hint
Which function displays text on screen? What punctuation must surround plain text?

 Solution

print (" Welcome to Python Lab")

Hands-on Python Laboratory Introduction to Python & Data Types 17/72


Practice Exercise 2 – Block A

Exercise 2
You need to write a 50-line program that you will run many times over the semester. Should you use
Script Mode or Interactive Mode? Justify in one line.

Hands-on Python Laboratory Introduction to Python & Data Types 18/72


Practice Exercise 2 – Block A

Exercise 2
You need to write a 50-line program that you will run many times over the semester. Should you use
Script Mode or Interactive Mode? Justify in one line.

 Hint
Which mode lets you save a program permanently and re-run it as a whole, instead of typing it fresh
each time?

Hands-on Python Laboratory Introduction to Python & Data Types 18/72


Practice Exercise 2 – Block A

Exercise 2
You need to write a 50-line program that you will run many times over the semester. Should you use
Script Mode or Interactive Mode? Justify in one line.

 Hint
Which mode lets you save a program permanently and re-run it as a whole, instead of typing it fresh
each time?

 Solution
Script Mode – save it as a .py file so it can be re-run as a whole, instead of re-typing it cell by cell.

Hands-on Python Laboratory Introduction to Python & Data Types 18/72


Block B
Variables, Identifiers & Input/Output
Variables – Naming a Value

Variable
A variable is a name that refers to a value stored in memory. Think of it as a labelled box: the label is
the variable name, and the box holds the value.

age = 20
name = " Priya "
height = 5.4

Reading Assignment

age = 20
Read right to left: “Take value 20, store it in box age.” The = is assignment, not mathematical equality.

Hands-on Python Laboratory Introduction to Python & Data Types 20/72


Identifiers – Rules for Naming

Identifier
An identifier is the name given to a variable, function, class, or any other user-defined item in Python.

Naming Rules
■ Must start with a letter or underscore ( ), not a digit.
■ Can contain letters, digits, underscores – no spaces or symbols (-, @, etc.).
■ Case-sensitive: Age and age are different identifiers.
■ Cannot be a Python keyword (reserved word like if, for, class).
■ Convention: lowercase with underscores, e.g. student name (snake case).

Common Mistake
2nd value = 10 ⇒ SyntaxError – identifiers cannot start with a digit.

Hands-on Python Laboratory Introduction to Python & Data Types 21/72


Output – Talking to the User

Output
Output is information the program displays. The print() function is Python’s main output tool.

name = "Arun"
marks = 88
print ("Name:", name , " Marks :", marks )

 Explanation
print() can take several items separated by commas – it automatically prints them in order, separated
by a single space.

Hands-on Python Laboratory Introduction to Python & Data Types 22/72


Formatted Strings (f-strings) – Gently, Step by Step

f-string
An f-string is written with a lowercase f right before the opening quote: f"...". It places a variable’s
value directly inside the text.

 Step 1 – The Old Way (Commas)

print ("Name:", name , " Marks :", marks )

Hands-on Python Laboratory Introduction to Python & Data Types 23/72


Formatted Strings (f-strings) – Gently, Step by Step

f-string
An f-string is written with a lowercase f right before the opening quote: f"...". It places a variable’s
value directly inside the text.

 Step 1 – The Old Way (Commas)

print ("Name:", name , " Marks :", marks )

 Step 2 – The f-string Way

print (f"Name: {name}, Marks : { marks }")

The f tells Python to look inside {} and substitute the variable’s value there.

Hands-on Python Laboratory Introduction to Python & Data Types 23/72


Formatted Strings (f-strings) – Gently, Step by Step

f-string
An f-string is written with a lowercase f right before the opening quote: f"...". It places a variable’s
value directly inside the text.

 Step 1 – The Old Way (Commas)

print ("Name:", name , " Marks :", marks )

 Step 2 – The f-string Way

print (f"Name: {name}, Marks : { marks }")

The f tells Python to look inside {} and substitute the variable’s value there.

 Why f-strings Are Preferred


Cleaner to read; can even format numbers, e.g. f"CGPA: {cgpa:.2f}" for exactly 2 decimal places.

Hands-on Python Laboratory Introduction to Python & Data Types 23/72


Input – Getting Data from the User

Input
Input is data the program receives from the user, using the input() function. input() always returns
a string, even if the user types a number.

Worked Example

name = input (" Enter your name: ")


age = input (" Enter your age: ")
print (" Hello ", name , "- next year you ’ll be", int(age) + 1)

Common Mistake
age + 1 directly ⇒ TypeError, because age is a string until converted with int().

Hands-on Python Laboratory Introduction to Python & Data Types 24/72


Instructor-Led Activity 1: Live I/O Demo

Live Coding (Instructor Demonstrates)


The instructor writes and runs, live, a short program that asks for the student’s name and two exam
marks, then prints the average using an f-string. The class predicts the output format before it runs.

name = input (" Enter your name: ")


m1 = input (" Enter Mark 1: ")
m2 = input (" Enter Mark 2: ")
avg = (int(m1) + int(m2)) / 2
print (f"{name}’s average is {avg}")

Class Discussion – Predict Before Running


Suppose the student types name = Arun, Mark 1 = 78, Mark 2 = 92. What will print() display?

Hands-on Python Laboratory Introduction to Python & Data Types 25/72


Answer: Live I/O Demo

Hands-on Python Laboratory Introduction to Python & Data Types 26/72


Answer: Live I/O Demo

 Expected Output

Arun ’s average is 85.0

Hands-on Python Laboratory Introduction to Python & Data Types 26/72


Answer: Live I/O Demo

 Expected Output

Arun ’s average is 85.0

 Explanation
■ input() always returns a string, so m1 and m2 are "78" and "92" until converted with int().
■ Without int(), m1 + m2 would concatenate the strings ("7892") instead of adding numbers – or raise a
TypeError for m1 / 2.
■ The result avg is a float because / always performs true division.

Hands-on Python Laboratory Introduction to Python & Data Types 26/72


Syntax Recap – Block B

All Syntax Covered So Far

age = 20 # variable assignment


name = input (" Enter name: ") # input () -> always a string
print ("Name:", name) # comma - separated print
print (f"Name: {name}") # f- string

Before You Try the Exercises


Make sure you can name a variable correctly, explain why input() returns a string, and write a basic
f-string.

Hands-on Python Laboratory Introduction to Python & Data Types 27/72


Quick Check – Block B (Q1)

Q1
Which of these are valid Python identifiers? 2marks, marks, student-name, Student1

Hands-on Python Laboratory Introduction to Python & Data Types 28/72


Quick Check – Block B (Q1)

Q1
Which of these are valid Python identifiers? 2marks, marks, student-name, Student1

 Answer
Valid: marks, Student1. Invalid: 2marks (starts with a digit), student-name (hyphen not allowed).

Hands-on Python Laboratory Introduction to Python & Data Types 28/72


Quick Check – Block B (Q2)

Q2
Predict the output: name = "Sam"
print(f"Hi {name}!")

Hands-on Python Laboratory Introduction to Python & Data Types 29/72


Quick Check – Block B (Q2)

Q2
Predict the output: name = "Sam"
print(f"Hi {name}!")

 Answer
Hi Sam!

Hands-on Python Laboratory Introduction to Python & Data Types 29/72


Syntax Assessment – Block B (5 Questions)

Answer in one line each


1. Correct syntax to store the text "Arun" in a variable name?
2. Function used to take input from the user?
3. What punctuation lets you embed a variable inside an f-string?
4. Is 2age a valid identifier? Why or why not?
5. What data type does input() always return?

Hands-on Python Laboratory Introduction to Python & Data Types 30/72


Syntax Assessment – Block B (Answers)

 Answers
1. name = "Arun"
2. input()
3. Curly braces {} inside an f"..." string
4. No – identifiers cannot start with a digit
5. str

Hands-on Python Laboratory Introduction to Python & Data Types 31/72


Practice Exercise 1 – Block B

Try Interactive Mode first, then VS Code.

Exercise 1
Take a student’s name and roll number as input, and print: Roll No 21: Divya (using an f-string).

Hands-on Python Laboratory Introduction to Python & Data Types 32/72


Practice Exercise 1 – Block B

Try Interactive Mode first, then VS Code.

Exercise 1
Take a student’s name and roll number as input, and print: Roll No 21: Divya (using an f-string).

 Hint
Use input() twice, then build the sentence with an f-string and curly-brace placeholders.

Hands-on Python Laboratory Introduction to Python & Data Types 32/72


Practice Exercise 1 – Block B

Try Interactive Mode first, then VS Code.

Exercise 1
Take a student’s name and roll number as input, and print: Roll No 21: Divya (using an f-string).

 Hint
Use input() twice, then build the sentence with an f-string and curly-brace placeholders.

 Solution

name = input (" Enter name: ")


roll = input (" Enter roll number : ")
print (f"Roll No {roll }: {name}")

Hands-on Python Laboratory Introduction to Python & Data Types 32/72


Practice Exercise 2 – Block B

Exercise 2
Find and correct the errors: 2nd name = "Arun" and class = 10.

Hands-on Python Laboratory Introduction to Python & Data Types 33/72


Practice Exercise 2 – Block B

Exercise 2
Find and correct the errors: 2nd name = "Arun" and class = 10.
 Hint
Recall the two identifier rules broken here: what can’t a name start with, and what word can’t be used
as a name?

Hands-on Python Laboratory Introduction to Python & Data Types 33/72


Practice Exercise 2 – Block B

Exercise 2
Find and correct the errors: 2nd name = "Arun" and class = 10.
 Hint
Recall the two identifier rules broken here: what can’t a name start with, and what word can’t be used
as a name?

 Solution

second_name = "Arun" # cannot start with a digit


student_class = 10 # ’class ’ is a reserved keyword

Hands-on Python Laboratory Introduction to Python & Data Types 33/72


Practice Exercise 3 – Block B

Exercise 3
Write a program that asks for two numbers using input() and prints their sum as an integer.

Hands-on Python Laboratory Introduction to Python & Data Types 34/72


Practice Exercise 3 – Block B

Exercise 3
Write a program that asks for two numbers using input() and prints their sum as an integer.

 Hint
Remember: input() always returns a string – what must you do before adding two of them as numbers?

Hands-on Python Laboratory Introduction to Python & Data Types 34/72


Practice Exercise 3 – Block B

Exercise 3
Write a program that asks for two numbers using input() and prints their sum as an integer.

 Hint
Remember: input() always returns a string – what must you do before adding two of them as numbers?

 Solution

a = int( input (" Enter first number : "))


b = int( input (" Enter second number : "))
print (f"Sum: {a + b}")

Hands-on Python Laboratory Introduction to Python & Data Types 34/72


Block C
Numeric Data Types & Strings
Numeric Data Types

Overview
Type Meaning Example
int marks = 78
Integer: whole number, no decimal
point
float cgpa = 8.5
Floating-point number: has a deci-
mal point
complex Has a real and imaginary part (rarely 3 + 4j
used in this course)

Dynamic Typing
Python figures out the data type automatically from the value assigned – called dynamic typing. You
never write “this is an integer” explicitly, unlike languages such as C or Java.

Hands-on Python Laboratory Introduction to Python & Data Types 36/72


Numeric Operators

Worked Example – Arithmetic

a = 17; b = 5
print (a + b, a - b, a * b)
print (a / b) # true division -> float
print (a // b) # floor division -> int
print (a % b) # remainder
print (a ** b) # exponent ( power )

Hands-on Python Laboratory Introduction to Python & Data Types 37/72


Numeric Operators

Worked Example – Arithmetic

a = 17; b = 5
print (a + b, a - b, a * b)
print (a / b) # true division -> float
print (a // b) # floor division -> int
print (a % b) # remainder
print (a ** b) # exponent ( power )

 Solution
22 12 85 3.4 3 2 1419857

‡ Exam Tip
/ always gives a float; // (floor division) gives the whole-number quotient, discarding the remainder.

Hands-on Python Laboratory Introduction to Python & Data Types 37/72


Strings – Sequences of Text

String
A string (str) is a sequence of characters enclosed in single ’...’ or double "..." quotes. Strings
are indexed – each character has a position number starting at 0.

s = " PYTHON "


print (s[0]) # ’P’ -- first character , index 0
print (s[ -1]) # ’N’ -- last character , negative index
print (s [1:4]) # ’YTH ’ -- slicing : index 1 up to (not including ) 4
print (len(s)) # 6 -- length of the string

Slicing
Slicing means extracting a sub-part of a string using start:stop. The character at stop is not
included.

Hands-on Python Laboratory Introduction to Python & Data Types 38/72


Common String Methods

Frequently Used Methods


.upper() / Converts to uppercase / lowercase
.lower()
.strip() Removes leading/trailing spaces
.replace(a,b) Replaces all occurrences of a with b
.split(sep) Splits string into a list of parts
.find(x) Returns index of first occurrence of x (or -1)

name = " Priya Kumar "


print (name. strip (). upper ())
print (name. strip (). split ())

Hands-on Python Laboratory Introduction to Python & Data Types 39/72


Instructor-Led Activity 2: String Puzzle

Live Prediction (Instructor Demonstrates)


Instructor projects a string s = "Hands-on Python Lab" and asks students to predict, one at a time,
the results of s[0:5], s[-3:], [Link](), and [Link](), before running each live.

s = "Hands -on Python Lab"


print (s [0:5])
print (s[ -3:])
print (s. upper ())
print (s. split ())

Hands-on Python Laboratory Introduction to Python & Data Types 40/72


Answer: String Puzzle

Hands-on Python Laboratory Introduction to Python & Data Types 41/72


Answer: String Puzzle

 Expected Output

Hands
Lab
HANDS -ON PYTHON LAB
[’Hands -on ’, ’Python ’, ’Lab ’]

Hands-on Python Laboratory Introduction to Python & Data Types 41/72


Answer: String Puzzle

 Expected Output

Hands
Lab
HANDS -ON PYTHON LAB
[’Hands -on ’, ’Python ’, ’Lab ’]

 Explanation
■ s[0:5] takes indices 0 to 4 – “Hands” (5 characters, index 5 not included).
■ s[-3:] counts 3 characters back from the end – “Lab”.
■ .upper() converts every letter to uppercase; the hyphen is unaffected.
■ .split() with no argument splits on whitespace, returning a list of 3 words.

Hands-on Python Laboratory Introduction to Python & Data Types 41/72


Syntax Recap – Block C

All Syntax Covered So Far

a + b, a - b, a * b # add , subtract , multiply


a / b, a // b, a % b # true div , floor div , remainder
a ** b # exponent
s[i], s[a:b], len(s) # index , slice , length
s. upper () , s. lower () # case conversion
s. strip () , s. split () # trim spaces , split into list

Before You Try the Exercises


Make sure you can distinguish / from //, and can index/slice a string confidently.

Hands-on Python Laboratory Introduction to Python & Data Types 42/72


Quick Check – Block C (Q1)

Q1
What is 17 // 5 in Python?

Hands-on Python Laboratory Introduction to Python & Data Types 43/72


Quick Check – Block C (Q1)

Q1
What is 17 // 5 in Python?

 Answer
3 – floor division discards the remainder.

Hands-on Python Laboratory Introduction to Python & Data Types 43/72


Quick Check – Block C (Q2)

Q2
What does "PYTHON"[2:5] return?

Hands-on Python Laboratory Introduction to Python & Data Types 44/72


Quick Check – Block C (Q2)

Q2
What does "PYTHON"[2:5] return?

 Answer
’THO’ – indices 2, 3, 4 (index 5 not included).

Hands-on Python Laboratory Introduction to Python & Data Types 44/72


Quick Check – Block C (Q3)

Q3
True or False: Strings in Python are mutable (their characters can be changed in place).

Hands-on Python Laboratory Introduction to Python & Data Types 45/72


Quick Check – Block C (Q3)

Q3
True or False: Strings in Python are mutable (their characters can be changed in place).

 Answer
False. Strings are immutable – s[0] = "X" raises a TypeError.

Hands-on Python Laboratory Introduction to Python & Data Types 45/72


Syntax Assessment – Block C (5 Questions)

Answer in one line each


1. Operator for floor division?
2. Operator for exponent (power)?
3. Syntax to get characters from index 2 up to (not including) index 5 of string s?
4. Method to convert a string to uppercase?
5. Function to get the length of a string s?

Hands-on Python Laboratory Introduction to Python & Data Types 46/72


Syntax Assessment – Block C (Answers)

 Answers
1. //
2. **
3. s[2:5]
4. [Link]()
5. len(s)

Hands-on Python Laboratory Introduction to Python & Data Types 47/72


Practice Exercise 1 – Block C

Try Interactive Mode first, then VS Code.

Exercise 1
Given three integer marks 78, 85, 91, print their total and average (rounded using //, and then using
/).

Hands-on Python Laboratory Introduction to Python & Data Types 48/72


Practice Exercise 1 – Block C

Try Interactive Mode first, then VS Code.

Exercise 1
Given three integer marks 78, 85, 91, print their total and average (rounded using //, and then using
/).

 Hint
Add the three marks first, then apply // for a whole-number average and / for a decimal one.

Hands-on Python Laboratory Introduction to Python & Data Types 48/72


Practice Exercise 1 – Block C

Try Interactive Mode first, then VS Code.

Exercise 1
Given three integer marks 78, 85, 91, print their total and average (rounded using //, and then using
/).

 Hint
Add the three marks first, then apply // for a whole-number average and / for a decimal one.

 Solution

m1 , m2 , m3 = 78, 85, 91
total = m1 + m2 + m3
print (" Total :", total )
print (" Average (int):", total // 3)
print (" Average ( float ):", total / 3)

Hands-on Python Laboratory Introduction to Python & Data Types 48/72


Practice Exercise 2 – Block C

Exercise 2
Given s = "Data Analytics", print the string reversed and its length.

Hands-on Python Laboratory Introduction to Python & Data Types 49/72


Practice Exercise 2 – Block C

Exercise 2
Given s = "Data Analytics", print the string reversed and its length.

 Hint
Slicing with a step of -1 reverses a string. Which built-in function gives the length?

Hands-on Python Laboratory Introduction to Python & Data Types 49/72


Practice Exercise 2 – Block C

Exercise 2
Given s = "Data Analytics", print the string reversed and its length.

 Hint
Slicing with a step of -1 reverses a string. Which built-in function gives the length?

 Solution

s = "Data Analytics "


print (s[:: -1]) # reversed
print (len(s)) # length

Hands-on Python Laboratory Introduction to Python & Data Types 49/72


Practice Exercise 3 – Block C

Exercise 3
Given price = "499.99" (a string), print it rounded to the nearest whole number.

Hands-on Python Laboratory Introduction to Python & Data Types 50/72


Practice Exercise 3 – Block C

Exercise 3
Given price = "499.99" (a string), print it rounded to the nearest whole number.

 Hint
First convert the string to a float, then use Python’s built-in rounding function.

Hands-on Python Laboratory Introduction to Python & Data Types 50/72


Practice Exercise 3 – Block C

Exercise 3
Given price = "499.99" (a string), print it rounded to the nearest whole number.

 Hint
First convert the string to a float, then use Python’s built-in rounding function.

 Solution

price = " 499.99 "


print ( round ( float ( price ))) # 500

Hands-on Python Laboratory Introduction to Python & Data Types 50/72


Block D
Type Conversion
Type Conversion (Casting)

Type Conversion
Type conversion (casting) means converting a value from one data type to another using int(),
float(), str(), bool().

x = "25" # string , not a number !


y = int(x) # y is now int 25
z = float (y) # z is now float 25.0
w = str(z) # w is back to a string "25.0"

Common Mistake
age = "20"
next_year = age + 1 # TypeError !

You cannot add a number directly to a string, even if it “looks like” a number. Convert first: int(age)
+ 1.

Hands-on Python Laboratory Introduction to Python & Data Types 52/72


Checking Types with type()

Worked Example

a = 10; b = 10.5; c = " Hello "; d = True


print (type(a), type(b), type(c), type(d))

Hands-on Python Laboratory Introduction to Python & Data Types 53/72


Checking Types with type()

Worked Example

a = 10; b = 10.5; c = " Hello "; d = True


print (type(a), type(b), type(c), type(d))

 Solution
<class ’int’> <class ’float’> <class ’str’> <class ’bool’>

‡ Exam Tip
bool is technically a subtype of int: True == 1 and False == 0 evaluate to True.

Hands-on Python Laboratory Introduction to Python & Data Types 53/72


Syntax Recap – Block D

All Syntax Covered So Far

int(x) # convert x to integer


float (x) # convert x to float
str(x) # convert x to string
bool(x) # convert x to True/ False
type(x) # check the current data type of x

Before You Try the Exercises


Make sure you can explain why "5" + 5 fails, and how to fix it with the right conversion function.

Hands-on Python Laboratory Introduction to Python & Data Types 54/72


Quick Check – Block D (Q1)

Q1
What error occurs when you run "5" + 5?

Hands-on Python Laboratory Introduction to Python & Data Types 55/72


Quick Check – Block D (Q1)

Q1
What error occurs when you run "5" + 5?

 Answer
TypeError – you cannot add a str and an int directly; convert first with int("5") or str(5).

Hands-on Python Laboratory Introduction to Python & Data Types 55/72


Quick Check – Block D (Q2)

Q2
Predict the output: print(int("10") + int("20"))

Hands-on Python Laboratory Introduction to Python & Data Types 56/72


Quick Check – Block D (Q2)

Q2
Predict the output: print(int("10") + int("20"))

 Answer
30 – both strings are converted to int before the addition.

Hands-on Python Laboratory Introduction to Python & Data Types 56/72


Syntax Assessment – Block D (5 Questions)

Answer in one line each


1. Function to convert a string to an integer?
2. Function to check the current data type of a variable x?
3. What does str(45) return?
4. What does bool(0) evaluate to?
5. What is the result of int("7") + 3?

Hands-on Python Laboratory Introduction to Python & Data Types 57/72


Syntax Assessment – Block D (Answers)

 Answers
1. int()
2. type(x)
3. "45" (a string)
4. False
5. 10

Hands-on Python Laboratory Introduction to Python & Data Types 58/72


Practice Exercise 1 – Block D

Try Interactive Mode first, then VS Code.

Exercise 1
Convert the integer 45 to a string and print "Weight: 45 kg" by concatenating.

Hands-on Python Laboratory Introduction to Python & Data Types 59/72


Practice Exercise 1 – Block D

Try Interactive Mode first, then VS Code.

Exercise 1
Convert the integer 45 to a string and print "Weight: 45 kg" by concatenating.

 Hint
You cannot join a string and an integer with + directly – which function turns a number into text first?

Hands-on Python Laboratory Introduction to Python & Data Types 59/72


Practice Exercise 1 – Block D

Try Interactive Mode first, then VS Code.

Exercise 1
Convert the integer 45 to a string and print "Weight: 45 kg" by concatenating.

 Hint
You cannot join a string and an integer with + directly – which function turns a number into text first?

 Solution

weight = 45
print (" Weight : " + str( weight ) + " kg")

Hands-on Python Laboratory Introduction to Python & Data Types 59/72


Practice Exercise 2 – Block D

Exercise 2
Take a person’s age as input (a string by default), convert it to an integer, and print "Adult" if age is 18
or above, else "Minor".

Hands-on Python Laboratory Introduction to Python & Data Types 60/72


Practice Exercise 2 – Block D

Exercise 2
Take a person’s age as input (a string by default), convert it to an integer, and print "Adult" if age is 18
or above, else "Minor".

 Hint
Convert the input to int first, then compare it against 18 using >=.

Hands-on Python Laboratory Introduction to Python & Data Types 60/72


Practice Exercise 2 – Block D

Exercise 2
Take a person’s age as input (a string by default), convert it to an integer, and print "Adult" if age is 18
or above, else "Minor".

 Hint
Convert the input to int first, then compare it against 18 using >=.

 Solution

age = int( input (" Enter age: "))


if age >= 18:
print (" Adult ")
else:
print (" Minor ")

(if-else is formally covered in the next module – this previews the idea.)

Hands-on Python Laboratory Introduction to Python & Data Types 60/72


Concept Map 15% | Post-Instructional

Python Basics

Variables & I/O Numeric Types & Strings

Type Conversion

Hands-on Python Laboratory Introduction to Python & Data Types 61/72


Key Takeaways

¥ Numeric types: int, float; watch / vs //.


¥ Python is high-level, interpreted, dynamically typed.
¥ Strings are indexed and sliceable, with many built-in
¥ Variables are labelled boxes; identifiers name them.
methods.
¥ input() always returns a string.
¥ Convert types explicitly with int()/float()/str().

Hands-on Python Laboratory Introduction to Python & Data Types 62/72


Essential Syntax to Remember

Input/Output Conversion
Slicing
input() int(), float(),
s[start:stop]
print() str(), bool()

Hands-on Python Laboratory Introduction to Python & Data Types 63/72


1-Minute Reflection

Reflect
In one sentence: “Why does input() always return a string, even when the user types a number?”

Hands-on Python Laboratory Introduction to Python & Data Types 64/72


Exit Ticket X

Before you leave, answer these in 2 minutes:


1. What data type does input() always return?
2. Write the output of "Hello"[1:4].
3. Convert the string "3.14" into a float – write the exact line of code.

Hands-on Python Laboratory Introduction to Python & Data Types 65/72


Student Practice Exercises (To Be Solved by Students)

Practice Set – Solve Individually, Then Compare with a Partner


1. Write a program that takes your name and two subject marks as input, converts the marks to integers, and
prints the total and average using an f-string.
2. Given s = "Sri Ramachandra", write code to print: the first 3 characters, the string reversed (hint:
s[::-1]), and the string in uppercase.
3. Take a floating-point CGPA as input from the user and print it rounded to one decimal place, along with its
data type before and after conversion.

Hands-on Python Laboratory Introduction to Python & Data Types 66/72


NCERT-Aligned Practice – Introduction & Data Types

Reference
These exercises are in the style of NCERT Class XI Computer Science (Getting Started with Python;
Data Handling chapters), extending what you have just practiced with the kind of questions asked at the
school level – useful for revisiting fundamentals.

Try Interactive Mode first, then VS Code.

Hands-on Python Laboratory Introduction to Python & Data Types 67/72


NCERT-Style Exercise 1

Exercise
Classify the following into their Python data types: 25, 25.5, "Delhi", True, 3+4j.

Hands-on Python Laboratory Introduction to Python & Data Types 68/72


NCERT-Style Exercise 1

Exercise
Classify the following into their Python data types: 25, 25.5, "Delhi", True, 3+4j.

 Hint
Check for a decimal point, quotes, True/False, and the letter j.

Hands-on Python Laboratory Introduction to Python & Data Types 68/72


NCERT-Style Exercise 1

Exercise
Classify the following into their Python data types: 25, 25.5, "Delhi", True, 3+4j.

 Hint
Check for a decimal point, quotes, True/False, and the letter j.

 Solution
25 → int, 25.5 → float, "Delhi" → str, True → bool, 3+4j → complex (a number type NCERT
introduces alongside int/float).

Hands-on Python Laboratory Introduction to Python & Data Types 68/72


NCERT-Style Exercise 2

Exercise
What will be the output of the following code?
a = 5
b = 2
print (a / b)
print (a // b)
print (a % b)

Hands-on Python Laboratory Introduction to Python & Data Types 69/72


NCERT-Style Exercise 2

Exercise
What will be the output of the following code?
a = 5
b = 2
print (a / b)
print (a // b)
print (a % b)

 Hint
Recall: / always gives a float, // gives the whole-number quotient, % gives the remainder.

Hands-on Python Laboratory Introduction to Python & Data Types 69/72


NCERT-Style Exercise 2

Exercise
What will be the output of the following code?
a = 5
b = 2
print (a / b)
print (a // b)
print (a % b)

 Hint
Recall: / always gives a float, // gives the whole-number quotient, % gives the remainder.

 Solution
2.5 2 1

Hands-on Python Laboratory Introduction to Python & Data Types 69/72


NCERT-Style Exercise 3

Exercise
A variable x is assigned the value 10, and later in the same program it is assigned the value "ten". Is
this allowed in Python? What is this behaviour called?

Hands-on Python Laboratory Introduction to Python & Data Types 70/72


NCERT-Style Exercise 3

Exercise
A variable x is assigned the value 10, and later in the same program it is assigned the value "ten". Is
this allowed in Python? What is this behaviour called?

 Hint
Think about whether Python fixes a variable’s type permanently at creation.

Hands-on Python Laboratory Introduction to Python & Data Types 70/72


NCERT-Style Exercise 3

Exercise
A variable x is assigned the value 10, and later in the same program it is assigned the value "ten". Is
this allowed in Python? What is this behaviour called?

 Hint
Think about whether Python fixes a variable’s type permanently at creation.

 Solution
Yes, this is allowed. A variable can be reassigned to a value of a different data type at any time – this
flexibility is called dynamic typing.

Hands-on Python Laboratory Introduction to Python & Data Types 70/72


Looking Ahead to Lecture 2

Coming Up
In Lecture 2, we move from single values to collections of values: Lists, Tuples, Dictionaries, and Sets
– how to store many items in one variable, and how to access, modify, and choose the right structure for
a task.
Pre-Read Prompt
Before Lecture 2, think: what real-life “list” do you keep (e.g., shopping list, to-do list)? Can it have
duplicate items? Does order matter?

Hands-on Python Laboratory Introduction to Python & Data Types 71/72


References

Allen B. Downey, Think Python: How to Think Like a Computer Scientist, 2nd Ed., Green Tea Press,
2015.
Charles R. Severance, Python for Everybody, 1st Ed., Shroff Publishers, 2017.

Hands-on Python Laboratory Introduction to Python & Data Types 72/72

You might also like