Chapter 13: Introduction to Data Types and Variables
It is the first week of the new session, and Meera has been asked to keep the records for her class. She opens a fresh notebook and starts writing.
On the first page she writes the class strength: 42. On the second page she writes each student’s name, one below the other, in the order they sit. On the third page she copies the four house names — Ganga, Yamuna, Kaveri, Narmada — and she writes each one only once, because a house name repeated twice would mean nothing. On the fourth page she writes the daily attendance, and here she only ever writes one of two things against a name: present or absent. On the last page she writes each student’s roll number beside their name, so that she can look up any student quickly.
Meera has not thought about it, but she has just used five different ways of holding information. A count. An ordered list. A collection with no repeats. A yes-or-no. A pairing of one thing with another.
A computer needs the same five ways, and Python gives them names.
Diagram
Fig. 13.0-1 – a student’s open record notebook with five labelled pages fanned out: page 1 showing a single number 42, page 2 a numbered list of names, page 3 four house names each written once, page 4 a column of present/absent ticks and crosses, page 5 two columns pairing roll numbers with names
This chapter answers each of the questions below.
13.1 Your First Python Program
Think about how you tell a younger cousin to make tea. You do not say everything at once. You say one step, then the next, then the next, in an order that makes sense. If you jumble the order, or leave a step out, the tea does not happen.
A computer needs the same treatment, only stricter. It will not guess what you meant. It carries out exactly what you write, in exactly the order you write it.
A program is a set of instructions written in a language the computer can carry out. Python is one such language. A single instruction in a program is called a statement, and Python runs the statements one after another, from the top of the file downwards.
Showing a result
The very first thing any program has to be able to do is show you something. If a program works out a total, checks a temperature, or reads a sensor, that result is useless until it comes out on the screen. So the first Python instruction worth learning is the one that puts text on the screen.
That instruction is print(). You write the word print, then a pair of round brackets, and inside the brackets you put whatever you want shown. Text has to sit inside quotation marks, so that Python knows it is text and not the name of something.
Notice that the two lines came out in the same order you wrote them. That is Python running your statements top to bottom.
print here is a function — a block of code that already exists, does a particular job, and can be called by its name. You did not write the code that pushes letters onto the screen. Somebody already wrote it and gave it the name print, and you simply called it and handed it your text.
The brackets are what tell Python to actually call the function. Whatever you put inside the brackets is passed to the function to work on.
13.1.1 The Interactive Window and the Editor Window
Python gives you two different places to type, and they are meant for two different purposes. Both are part of IDLE, the simple editing tool that comes with Python.
The first is the interactive window, also called the shell. It shows a prompt made of three angle brackets, >>>. You type one line, press Enter, and Python runs that line immediately and shows the result. It is a scratch pad. It is perfect for checking a small doubt — what does this line do, what is this value — but nothing you type there is kept. Close the window and it is all gone. See Fig. 13.1-1.
Diagram
Fig. 13.1-1 – screenshot of the IDLE interactive window showing the >>> prompt with a single print statement typed at it and its output displayed on the line below
The second is the editor window. This is where a real program is written, because here your lines are saved as a file and can be run again tomorrow. To open it, select File, then New File. Type your program, then select File and Save, and give the file a name ending in .py, such as lab_notice.py. The .py ending is how the computer knows the file holds Python code.
Running a saved program
To run what you have written, select Run, then Run Module. Pressing F5 does the same thing. The program runs, and its output appears in the interactive window. To come back to a program you wrote earlier, select File, then Open, and pick the file.
13.1.2 Errors in a Python Program
Every programmer writes code that fails. This is normal, and Python is quite helpful about it — when something goes wrong it stops and prints a message saying what it did not like. Learning to read that message is a large part of learning to program.
Errors come in two kinds, and the difference is about when the problem is noticed.
A syntax error is a mistake in the way the code is written — a word, a bracket, or a quotation mark that is not allowed in Python. Python checks the whole file before it runs anything, so a syntax error is caught before the program starts. Nothing at all is executed, not even the correct lines above the mistake.
Suppose you leave out the closing quotation mark:
print("Robotics Lab, Class 9)Python never runs this line. It reports a SyntaxError and says that the piece of text was never closed. In the editor you can often spot this yourself, because the colour of the text changes when a quotation mark is missing — the rest of the line takes on the colour Python uses for text.
A runtime error is different. The code is written correctly, so Python accepts it and starts running. The problem only appears part way through, when Python is asked to do something it cannot actually do. The statements before that point have already run and their output has already appeared.
total = 350
count = 0
print(total / count)Here the first two lines run without any trouble. The third line asks Python to divide by zero, which has no answer, so Python stops there and prints a message ending with ZeroDivisionError: division by zero. Nothing after that line runs. See Fig. 13.1-2.
Diagram
Fig. 13.1-2 – two horizontal strips comparing the two error types; the upper strip labelled “syntax error” shows the whole program blocked at a checking stage with no output produced; the lower strip labelled “runtime error” shows the first two statements running and producing output, then the third statement halting with an error message
So the short way to tell them apart: a syntax error means Python could not read your program; a runtime error means Python read it fine but could not carry out one of the instructions.
13.2 Variables and Assignment of Values
Imagine the notice board outside your school office. The school’s name appears on it eleven times — on the timetable, on the fee notice, on the sports circular, and so on. Now the school is renamed. Somebody has to go and change it in all eleven places, and if they miss one, the board becomes wrong.
Programs have exactly this problem. A value such as a name, a price, or a count is usually needed in several places, and it often has to change. Writing the value itself in all those places makes the program long to write and easy to get wrong.
The answer is to store the value once, under a name, and use the name everywhere else. Change the value in that one spot and every use of the name follows. Such a name is called a variable.
Putting a value into a variable
You give a variable its value using the equals sign, =. This is called the assignment operator. It takes whatever is on its right and stores it under the name on its left.
class_strength = 42Read that from right to left: the value 42 is stored, and the name class_strength now refers to it. From this point on, wherever you write class_strength, Python looks up the name, finds 42, and uses 42 in its place.
This is not the equals sign of mathematics. In mathematics, \(x = 5\) states a fact. In Python, x = 5 is an instruction: put 5 into x. That is why a line like class_strength = class_strength makes no sense as a statement of fact but is perfectly ordinary as an instruction.
The same name printed two different things, because between the two print() calls the stored value was replaced. A variable holds exactly one value at a time. Assigning a new value does not add to the old one; it replaces it, and the old value is gone.
13.2.1 Naming a Variable
Python is not fussy about what you call your variables, but it does have a few firm rules.
A variable name may contain uppercase letters (A–Z), lowercase letters (a–z), digits (0–9) and the underscore character. It may not contain a space, and it may not begin with a digit. It also may not be one of Python’s own reserved words, such as if, for or class, because those already mean something to Python.
Table 13.2 shows a few names and whether Python will accept them.
Capital letters matter
Python treats uppercase and lowercase as different. marks, Marks and MARKS are three separate names. If you store a value in marks and then ask for Marks, Python has no idea what you mean and reports a NameError.
Choosing a name that helps
The rules say what is allowed. Good sense says what is wise. A name like t = 50 is legal but tells nobody anything — is that a time, a temperature, or a total? time_taken = 50 costs a few more keystrokes and saves the next reader, who is very often you, a week later.
Long names are fine. number_of_students is a better name than n, and list_of_names is better than l. Aim for a name that says what the value is, not what type of thing it is.
13.4 Data Types in Python
In the school office there is a register with a column of roll numbers and a column of phone numbers. Both columns are full of digits. Yet nobody would ever add two phone numbers together, or work out the average of a set of them. The digits look the same; what you are allowed to do with them is not the same at all.
A computer faces the same situation, and it settles it by giving every value a kind. The kind of a value is called its data type. The data type decides what the value can hold and what may sensibly be done with it — whether it can be added, whether it can be split into letters, whether it can hold more than one item.
You never have to announce the data type in Python. When you assign a value, Python works out the type from the way the value is written. 42 is written without a decimal point, so it is a whole number. "42" is written inside quotation marks, so it is text.
Checking a value’s type
Python has a built-in function that tells you the type of any value: type(). You put the value inside the brackets and it reports the type.
Read the last part of each line: int for the whole number, float for the decimal number, str for the text, bool for the true-or-false value. Those short names are how Python refers to its types, and you will see them in error messages too.
The rest of this section covers the types you need: numeric types (int and float), Boolean, the sequence types (tuple, list, strings), sets and dictionary.
13.4.1 Numeric Data Types
Numbers in a program come in two everyday shapes. A count of students is a whole number — there is no such thing as half a student on the roll. A temperature reading or a price is usually not whole, and cutting off the part after the point would lose real information.
Python keeps these apart. An integer is a whole number with nothing after a decimal point: 42, 0, -7. Python calls this type int.
A floating-point number, or float for short, is a number written with a decimal point: 3.5, 98.6, -86.58. Python calls this type float.
The comparison that surprises most people is 5 against 5.0. Their value is the same, but their type is not. 5 is an int. 5.0 is a float, because it is written with a decimal point. The decimal point is the whole difference.
Writing very large and very small numbers
Suppose a value is 0.0000001, or 3400000000. Counting zeros on the screen is slow and easy to get wrong. Python lets you write such numbers in exponential notation, also called E notation, using the letter e.
The number before the e is multiplied by 10 raised to the power of the number after the e:
\[\text{value} = m \times 10^{n}\]
Here \(m\) is the part written before the e, and \(n\) is the whole number written after it. A negative \(n\) makes the value smaller than one.
Two more, to fix the idea. 10e5 means \(10 \times 10^{5}\), which is 1000000.0. And 1e-4 means \(1 \times 10^{-4}\), which is \(\dfrac{1}{10000}\), or 0.0001. Any number written this way is a float, even when the result happens to be whole — notice the .0 at the end of both answers.
One honest limitation of floats
A float is stored in a fixed amount of memory, so a value that needs endless digits has to be stored to a limited accuracy. Most of the time you never notice. Occasionally you do:
print(0.1 + 0.2)Output:
0.30000000000000004
That is not a bug in Python; every language that stores decimals this way behaves the same. It is worth knowing because it means you should not expect a float to be exact to the last digit, especially after many calculations. For anything that must be exact, such as a count, use an int.
13.4.2 Boolean Data Type
A great deal of what a program has to record is not a number or a name at all. It is a plain yes or no. Is the student present? Is the gate closed? Has the fee been paid? Has the touch sensor on a robot been pressed?
For these, Python has the Boolean data type, which it calls bool. A Boolean value can be only one of two things: True or False. There is no third possibility, and that is exactly why it suits a yes-or-no fact.
Both words must be written with a capital first letter and no quotation marks.
The quotation marks matter here more than anywhere else. True without quotes is a Boolean value. "True" with quotes is a piece of text that happens to spell the word — Python reports its type as str, and it will not work where a Boolean is expected.
Booleans become far more useful in the next chapters, where a program has to choose between two courses of action. For now, the point is simply that a yes-or-no fact has a type of its own, and does not need to be squeezed into a number or a piece of text.
13.4.3 Sequence Data Types
A single number or a single name is often not enough. A class has forty-two names, not one. A robot’s path has a series of turns, not one turn. Marks come as a whole set.
For this, Python has types that hold many items in one variable, kept in a fixed order. Such a type is called a sequence. The order is part of the information — the third name on the attendance list is the third student, not just any student.
Because the items sit in order, each one has a position, and that position is called its index. Python counts positions from 0, not from 1. The first item is at index 0, the second at index 1, and so on. This feels odd at first and becomes natural quickly.
You take out one item by writing the variable name followed by the index in square brackets. You take out a range of items — called slicing — by writing two indices separated by a colon. In a slice, the first index is included and the second is not.
The three sequence types in this chapter are tuple, list and strings. They differ in what they hold and in whether they can be changed after they are made, but indexing and slicing work the same way in all three.
13.4.3.1 Strings
Any text a program deals with — a name, a message, a notice, a line read from a file — is held as a string. A string is a sequence of characters, and the characters are kept in order, exactly as typed.
You create a string by putting the text inside quotation marks. Single quotes and double quotes both work and mean the same thing. Triple quotes are used for text that runs over more than one line.
single_quoted = 'This is a string.'
double_quoted = "This is also a string."
triple_quoted = '''This string can
run over two lines.'''Having two kinds of quotes is useful when the text itself contains a quotation mark. Text with an apostrophe in it is easiest to write inside double quotes.
Joining two strings end to end is called concatenation, and it is done with +.
The " " in the middle is a string containing a single space. Without it the two parts would run together as MeeraNair, because + joins strings exactly as they are and adds nothing of its own.
Positions inside a string
Every character in a string has an index, starting at 0. See Fig. 13.4-1.
Diagram
Fig. 13.4-1 – the word “Python” written with each letter in its own box, the index numbers 0 to 5 written beneath the boxes, and a bracket above boxes 1 to 3 labelled “text[1:4] gives yth”
The slice school[8:14] begins at index 8 and stops just before index 14, so it gives the six characters from 8 to 13. The len() function gives the number of characters, and the count includes the two spaces.
Useful things strings can do
Python provides ready-made actions for strings, written after the string with a dot. upper() gives a copy in capitals, lower() gives a copy in small letters, strip() gives a copy with spaces at the two ends removed, and replace() gives a copy with one piece of text swapped for another.
Look carefully at the second line of output. upper() changed the letters but left the stray spaces, because upper() does one job only. The third line applies strip() first and then replace() on the result.
Some characters cannot be typed straight into a string — a new line, for instance. For these Python uses an escape sequence, a backslash followed by a letter. The common one is \n, which stands for a line break.
print("Line one\nLine two")Output:
Line one
Line two
Strings cannot be edited in place
A string is immutable, which means that once it is made, its contents cannot be changed. Trying to replace one character directly fails.
This is why notice.strip() in the program above did not change notice. The tidied text was a fresh string, printed and then thrown away. To keep it, you would have to assign it: notice = notice.strip().
Putting values inside text
Building a sentence out of + signs gets clumsy as soon as numbers are involved. An f-string is a neater way: put the letter f immediately before the opening quotation mark, and then write any variable name inside curly brackets in the text. Python replaces each bracketed name with its value.
The :.2f after the variable name asks for the value shown as a decimal number with two places after the point, so 78.456 appears rounded as 78.46. F-strings are used a great deal because they read almost like the sentence they produce.
13.4.3.2 List
Storing forty-two names in forty-two separate variables would be unworkable. A list solves this: it is a single variable that holds a whole collection of items, in order, and lets you add to it or remove from it whenever you like.
You create a list by writing the items inside square brackets, separated by commas. A list may hold numbers, strings, or a mixture of different types.
marks = [78, 65, 90, 55, 82]
houses = ["Ganga", "Yamuna", "Kaveri"]
record = ["Meera", 9, 78.5, True]
empty_list = []Indexing and slicing work exactly as they did for strings.
The slice came back as a list of its own, shown with its square brackets. len() gives the number of items in the list — five — not the number of digits.
Changing what a list holds
A list is mutable: it can be changed after it is created. Python gives it a set of ready-made actions for this. append() adds an item at the end, insert() puts an item at a given index, remove() deletes the first matching item, and pop() removes the item at a given index and hands it back to you.
Follow the changes one at a time. After append() the list ends with Narmada. insert(1, "Tapti") puts Tapti at index 1 and pushes everything after it one place along. remove("Kaveri") takes Kaveri out, and the list closes up behind it.
The last two lines use the in operator, which checks whether an item is present anywhere in the list and answers with a Boolean.
13.4.3.3 Tuple
Some collections should never change. The three coordinates of a fixed point, a date already recorded, the position where a robot began its run — if a stray line of code could alter these, a hard-to-find bug becomes possible.
A tuple is an ordered collection, like a list, but immutable. Once made, its items cannot be added to, removed, or replaced. You create one by writing the items inside round brackets, separated by commas.
position = (2.5, 4.0)
date_recorded = (2025, 9, 20)Reading from a tuple is the same as reading from a list — square brackets, index from 0, slices with a colon, and len() for the count.
The line x, y = position is called unpacking: Python matches the items of the tuple to the names on the left, in order. The opposite also works — writing position = 2.5, 4.0 without any brackets packs the two values into a tuple automatically.
13.4.3.4 Tuple and List Compared
Both hold items in order, both are indexed from 0, both support slicing and len(). The differences are set out in Table 13.3.
The difference in memory and speed is real but small, and for the short collections in a school program it makes no noticeable difference. Choose between the two on meaning, not on speed.
13.4.4 Sets
Think of the list of subjects offered by a school. Physics appears once. Writing it twice would not mean the school offers it twice — it would simply be a mistake. The same is true of the house names in a school, or the roll numbers of the students who have paid their fees. These are collections where a repeat means an error, and where the order does not carry any meaning either.
A set is Python’s type for exactly this. A set holds items with no duplicates, and it does not keep them in any order you can rely on.
You create a set by passing a collection to the set() function, or by writing the items inside curly brackets.
houses = set(["Ganga", "Yamuna", "Kaveri"])
subjects = {"physics", "chemistry", "biology"}If the collection you pass has repeated items, the set keeps only one of each. Nothing is reported as wrong; the duplicates simply do not go in.
Five numbers went in, but only three of them are different, so the count is 3. Adding 7 again leaves the count unchanged, because 7 is already there. Adding 23, which is new, takes the count to 4.
That last point is the honest limitation of sets. What you gain is instant removal of duplicates and a quick check of whether an item is present. What you give up is position — you cannot ask for the third item, and you cannot slice.
13.4.5 Dictionary
There is one more shape that information often takes, and none of the types so far fits it. Look at a school’s admission form. Against the label “Name” is a name. Against “Class” is a class. Against “House” is a house. The information is not a bare collection of values; each value is attached to a label that says what it is.
A dictionary stores information in exactly this shape: as pairs, each pair made of a key and a value. The key is the label you look things up by, and it must be unique within that dictionary — just as a form cannot have two boxes both labelled “Name”.
You write a dictionary inside curly brackets. Each pair is written as the key, a colon, and then the value, and the pairs are separated by commas.
student = {"name": "Meera", "class": 9, "house": "Ganga"}To take a value out, you write the key in square brackets — not a position, but the key itself. This is the real difference between a dictionary and a list. In a list you must know where a value is; in a dictionary you only need to know what it is called. See Fig. 13.4-2.
Diagram
Fig. 13.4-2 – two side-by-side sketches; on the left a list drawn as numbered boxes 0, 1, 2 with values inside and an arrow labelled “found by position”; on the right a dictionary drawn as pairs of labelled tags “name”, “class”, “house” each joined to its value by an arrow labelled “found by key”
Two different things happened on the two assignment lines, and Python decided between them by itself. "house" was already a key, so its value was replaced. "roll" was not a key at all, so a new pair was added. That is why len() reports 4 pairs and not 5.
The in operator on a dictionary checks the keys, not the values. "class" in student is True because there is a key called "class". Asking "Meera" in student would give False, even though Meera is stored, because Meera is a value and not a key.
A dictionary is looked up by key, never by position, so you should not think of its pairs as having an index. Writing student[0] does not give the first pair; it looks for a key that is the number 0, and reports a KeyError when there is none.
13.5 Choosing the Right Data Type
A carpenter with a saw, a chisel and a file does not pick one at random. Each tool suits a particular job, and using the wrong one makes the work harder and the result worse.
Data types work the same way. Python will not stop you storing a phone number as a number or a set of house names as a list. The program will run. It will simply be more awkward than it needed to be, and more likely to go wrong later. Choosing well at the start saves that trouble.
The choice comes down to a few plain questions about the information itself.
Table 13.4 applies these questions to some records a school actually keeps.
Numbers that are not quantities
Here is the choice students get wrong most often. A phone number, a PIN code and an admission number all look like numbers. They are not quantities. You never add two PIN codes, and their average means nothing. Store them as strings.
A related surprise: a float drops a trailing zero when it is displayed. A price stored as 245.50 prints as 245.5, because both stand for the same number. If the display must show two decimal places, an f-string with :.2f does that job.
One record, several types
A real record almost always mixes types, and a dictionary is usually what holds the mixture together.
Four different types sit inside one dictionary, and each is the one that fits its own value. The quantity is a whole count, so int. The price has paise, so float. The name is text, so a string. Availability is yes or no, so a Boolean.
When the choice is genuinely open
Sometimes two types would both work, and then meaning decides. A pair of coordinates could be a list or a tuple. Choose a tuple if the pair is a reading already taken, and a list if the robot’s position is going to be updated as it moves. The type you pick is a message to whoever reads the program next, including you.
13.6 Indentation in Python
Look at how a recipe is written. The main steps run down the left edge. Under “make the batter” there are three smaller steps, and they are printed slightly to the right so that you can see at a glance that they belong to that one step. The shifting-in is not decoration. It tells you what goes with what.
Python does the same thing, and it means it seriously. In most languages the shifting-in of code is only for the eye, and brackets say which statements belong together. In Python the shifting-in is the grouping.
The blank space at the start of a line is called indentation. A group of statements written at the same indentation, belonging together, is called a block.
The colon and the block
A block always follows a line ending in a colon, :. The colon is the signal that a block is about to start, and every line of that block is indented further than the line with the colon.
Consider a program that prints a result only when a student has passed. The if statement runs its block when the condition after it holds, and skips the block when it does not. Conditions are the subject of the next chapter; what matters here is which lines belong to the if.
The two indented lines form the block belonging to the if. The last line is back at the left edge, so it is not part of that block and runs whatever the marks are. Change marks to 20 and run it again: the output is just Checking complete, because the whole block was skipped while the unindented line still ran. See Fig. 13.6-1.
Diagram
Fig. 13.6-1 – the five-line program printed with a shaded band drawn around the two indented print statements labelled “block belonging to the if”, and an arrow at the last line labelled “outside the block, always runs”
Blocks inside blocks
A block can contain another line ending in a colon, and that line starts a block of its own, indented further still. This is called nesting, and the depth of indentation shows the level.
if marks >= 33:
print("Pass")
if marks >= 75:
print("Distinction")print("Distinction") is indented twice, so it belongs to the inner if, which itself belongs to the outer one. It runs only when both conditions hold.
Indentation is not optional
If a colon is followed by a line that is not indented, Python does not guess. It stops with an IndentationError saying that an indented block was expected. Nothing runs at all, because this is a fault in the way the code is written.
The more troublesome case is code that runs but does the wrong thing. If a line that was meant to be inside a block is left at the outer level, Python accepts it happily — the program is still valid — and it runs at the wrong times. There is no error message to point at. This is why lining up your blocks carefully is worth the few seconds it costs.
13.7 Summary
- A program is a set of instructions written in a language the computer can carry out. Each instruction is a statement, and Python runs statements one after another from the top downwards.
- A function is a piece of code that performs a task and can be run by calling its name.
print()is the function that displays something on the screen. - The interactive window runs one line at a time and keeps nothing. The editor window is where a program is written and saved as a
.pyfile, and run with Run Module or F5. - A syntax error is a mistake in the way the code is written. Python finds it before running anything, so no part of the program runs.
- A runtime error appears while the program is running, when Python is asked to do something it cannot do. The statements before that point have already run.
- A variable is a name that stands for a stored value. Values are given to variables with the assignment operator,
=, which stores whatever is on its right under the name on its left. - A variable holds one value at a time. Assigning a new value replaces the old one.
- Variable names may use letters, digits and underscores. They may not contain a space, may not begin with a digit, and may not be one of Python’s reserved words. Names are case sensitive.
- A comment is a note that Python ignores, written after a
#. A block comment sits on its own line; an inline comment sits at the end of a line of code. - A data type is the kind of a value, and it fixes what may be stored and what may be done with it. Python works out the type from the way the value is written, and
type()reports it. - An integer is a whole number, type
int. A floating-point number has a decimal point, typefloat. The value 5 and the value 5.0 have the same size but different types. - E notation writes a number as a part multiplied by a power of ten, so
2.5e3stands for 2500.0. Any number written this way is a float. - Floats are stored to a limited accuracy, so they should not be relied on to be exact to the last digit.
- A Boolean value, type
bool, can only beTrueorFalse, written with capital letters and no quotation marks. It suits any yes-or-no fact. - A sequence holds items in order. Each item has an index, counted from 0, and a range of items can be taken out by slicing, where the first index is included and the second is not.
- A string is a sequence of characters, written inside single, double or triple quotes. Strings can be joined with
+, measured withlen(), and worked on with methods such asupper(),lower(),strip()andreplace(). - Strings are immutable. Every string method returns a new string and leaves the original unchanged.
- An escape sequence stands for a character that cannot be typed directly;
\nstands for a line break. - An f-string places the value of a variable inside text, by putting
fbefore the opening quote and the variable name inside curly brackets. - A list holds a collection of items in order and is mutable, so items can be added, removed or changed with
append(),insert(),remove()andpop(). - A tuple also holds items in order but is immutable, which suits a record that must stay fixed once made. Its values can be unpacked into separate variables in one line.
- The
inoperator checks whether an item is present in a collection and answers with a Boolean. - A set holds items with no duplicates and no order that can be relied on, so it cannot be indexed or sliced. Adding an item that is already present changes nothing.
- A dictionary stores pairs of a key and a value, and a value is found by its key rather than by a position. Keys must be unique. Assigning to an existing key replaces its value; assigning to a new key adds a pair.
- Choosing a type is a matter of what the information is: a count is an int, a measurement a float, a yes-or-no a Boolean, a changing collection a list, a fixed record a tuple, a duplicate-free collection a set, and a set of labelled values a dictionary.
- Values that look like numbers but are never used as quantities, such as phone numbers and PIN codes, should be stored as strings.
- Indentation is the blank space at the start of a line, and in Python it is what groups statements into a block. A block follows a line ending in a colon, and every line of the block is indented by the same amount.
- Indentation is not optional. A missing indent gives an
IndentationError, and a wrongly placed line can run at the wrong time without any error being reported.
13.8 Key Terms
- Assignment operator — the
=sign, which stores the value on its right under the variable name on its left. - Block — a group of statements at the same indentation that belong together and follow a line ending in a colon.
- Block comment — a comment written on a line of its own, usually explaining the lines that follow.
- Boolean — the data type that can hold only
TrueorFalse, used for a yes-or-no fact. - Comment — a note in a program, written after a
#, which Python ignores. - Data type — the kind of a value, which fixes what it can hold and what may be done with it.
- Dictionary — a collection of key-and-value pairs, in which a value is found by its key rather than by a position.
- F-string — a string written with
fbefore the opening quote, in which a variable name inside curly brackets is replaced by its value. - Floating-point number — a number written with a decimal point, of type
float. - Function — a piece of code that performs a task and can be run by calling its name.
- IDLE (Integrated Development and Learning Environment) — the simple editing and running tool supplied with Python.
- Immutable — describing a value whose contents cannot be changed after it is created, such as a string or a tuple.
- Indentation — the blank space at the start of a line, which in Python decides which block the line belongs to.
- Index — the position of an item in a sequence, counted from 0.
- Inline comment — a comment written at the end of a line of code, explaining that line.
- Integer — a whole number with no decimal part, of type
int. - Key — the label in a dictionary by which a value is stored and looked up; it must be unique.
- List — an ordered collection written in square brackets, which can be added to, changed and shortened.
- Mutable — describing a value whose contents can be changed after it is created, such as a list.
- Program — a set of instructions written in a language the computer can carry out.
- Runtime error — an error found while the program is running, when Python cannot carry out an instruction.
- Sequence — a data type that holds several items in a fixed order, so that each item has an index.
- Set — a collection that holds no duplicates and keeps no order that can be relied on.
- Slicing — taking a range of items out of a sequence by giving two indices, the first included and the second not.
- Statement — a single instruction in a program.
- String — a sequence of characters used to hold text, written inside quotation marks.
- Syntax error — an error in the way the code is written, found before the program runs, so that nothing runs.
- Tuple — an ordered collection written in round brackets, which cannot be changed after it is created.
- Variable — a name that stands for a stored value, so that the value can be used and changed through that name.
13.9 Objective Questions
(Which of the following is not a valid variable name in Python?)
_marksstudent22studentstotal_marks
(Which data type does not allow the same value to be stored twice?)
- list
- tuple
- set
- string
(Fill in the blank: In Python, the index of the first item of a sequence is ________.)
(Fill in the blank: A comment in a Python program begins with the ________ character.)
(True or False: The contents of a tuple can be changed after it has been created.)
(True or False: A syntax error is reported only after the earlier statements of the program have already run.)
(Match each data type in Column A with a value of that type in Column B.)
Column A Column B a. int i. Falseb. float ii. "Ganga"c. str iii. 3.5d. bool iv. 42(Write the output of the following program.)
word = "Robotics"
print(word[0])
print(word[2:5])13.10 Concept Questions
(Define a variable. Explain why a program stores a value under a name instead of writing the value itself wherever it is needed.)
(Differentiate between a syntax error and a runtime error. Give one example of each, and state in each case whether any part of the program runs before the error is reported.)
(A school stores every student’s phone number as an integer. Give two reasons why this is a poor choice, and state which data type should be used instead.)
(Write the value that each of the following stands for, showing your working:
4.5e2and3e-3. State the data type of both results.)(Write a Python program that stores a student’s name, class and house in a dictionary, prints only the name, then changes the house to a different one and prints the whole dictionary.)
(A program has an
ifstatement followed by a block of two indented lines. What would happen if the second of those two lines were moved to the left edge? State whether Python would report an error, and explain when that line would now run.)
13.11 Case-Based Questions
(A school library keeps one record for every book. The record for one book is shown below.)
What is recorded Value for this book Title Everyday Machines Number of copies 4 Price of one copy 349.50 Currently issued no - Name the data type that suits each of the four records, and give a reason for your choice for the price.
- Write the Python statement that stores all four records together in one dictionary named
book. - The librarian also wants to keep the subjects a book belongs to, with no subject listed twice and the order not mattering. Name the data type that suits this, and explain why.
(A class teacher keeps the names of the students present today in a list. The following lines are run when two more students arrive late.)
present = ["Meera", "Arjun", "Kabir"]
present.append("Sara")
present.insert(1, "Ravi")
print(len(present))- Write the contents of
presentafter all three lines have run, in the correct order, and state what the program prints. - The teacher now wants to record, for each student, whether the fee has been paid. Name the data type that suits this record and give one reason for your choice.
- Explain why a list, and not a tuple, is the right choice for holding the names of the students present.
13.3 Comments in a Program
When a science teacher writes a diagram on the board, the drawing alone is not enough. Small notes around it say what each part is and why it is there. The diagram shows what; the notes explain why.
A program needs the same kind of notes. Your code shows what the computer will do. It does not show why you chose to do it that way, or where you got a number from, or what a section of the program is meant to achieve. Six weeks later, that missing explanation is the difference between understanding your own program in a minute and puzzling over it for half an hour.
A comment is a line, or part of a line, that Python ignores completely. It is there only for the person reading the code. You write a comment by putting a hash character,
#, and everything after it on that line is treated as a note.There are two ways to place one. A block comment begins on a line of its own and usually explains the lines that follow. An inline comment sits at the end of a line of code and explains just that line.
a short program with both kinds of comment Problem: record the room where the robotics lab is held, and display it, with notes explaining the code.
Output:
The first line is a block comment. The two notes at the ends of the other lines are inline comments. None of the three has any effect on what the program does — the output would be exactly the same without them.
Q. If Python ignores comments, do they slow the program down?
A. No. Python skips over them, and they are not part of what the program actually carries out.
Because Python ignores a commented line, a
#is also a quick way to switch a line off while you are testing, without deleting it. Put a#in front of the line, run the program, and put the line back later by removing the#.writing a note without the hash character What goes wrong: the note is typed as ordinary text — say,
this line shows the room— and Python tries to run it as an instruction. The program stops with aSyntaxErrorbefore anything happens. The fix: every note, on its own line or at the end of a line, must begin with#.A last word on what to write. A comment that repeats the code adds nothing:
print(lab_room) # prints lab_roomtells the reader what they can already see. Useful comments say why — why this value, why this order, what this block of code is for.