📌 Snapshot
- Python basics from keywords and variables to operators, input and type conversion, with output traces.
- Valid identifiers, data types, mutable and immutable types, and operator precedence worked step by step.
- Why input returns text, how explicit and implicit conversion differ, and the three kinds of error.
- Predict the output practice and the exact traps NTA sets on operators, precedence and conversion.
📖 Detailed Notes
Written and reviewed by Rohit Singh, Computer Science & Commerce faculty at UniDrill (MCA, Osmania University · 6 years teaching). Based on NCERT Computer Science Class XI, Chapter 5.
You type 2 and the program shows 22
A beginner writes a program to double a number. The user types 2 and expects 4. The program prints 22. Nothing is broken: Python did exactly what it was told. The user's 2 arrived as the text "2", and multiplying text by 2 repeats it. Almost every Python mistake in this chapter has the same root: Python does precisely what the symbols mean, and the meaning depends on the type of the data.
So the chapter is really about three questions. What is each value (its type)? What do the operators do to it? And what happens when the types don't match? Learn those and the output of any program can be predicted by hand, which is how NTA tests it.
What Python is, and how you run it
An ordered set of instructions given to a computer to do a task is a program, and the language used to write it is a programming language. Python is a high level language, so its programs are source code, translated into machine language by an interpreter. The interpreter takes the statements one by one, translating and executing each, until an error is met or the whole program has run. A compiler, on the contrary, translates the entire source code into object code and reports errors after scanning the whole program.
| Feature of Python | What it means |
|---|---|
| High level, free and open source | Close to human language; anyone can use it freely |
| Interpreted | An interpreter runs the program statement by statement |
| Easy to understand | Clearly defined syntax and a simple structure |
| Case sensitive | NUMBER and number are different names |
| Portable | Runs on different operating systems and hardware |
| Rich library | Many predefined functions |
| Uses indentation | Blocks and nested blocks are marked by indentation |
You use the interpreter in two ways. The shell shows the prompt >>>, meaning it is ready for instructions.
| Feature | Interactive mode | Script mode |
|---|---|---|
| How | Type one statement at the >>> prompt |
Write many statements in a file and run the file |
| Result | Executed and shown at once | Output appears in the shell when the file runs |
| Saved? | No: statements must be retyped to run again | Yes: saved with the extension .py |
| Best for | Testing a single line | Programs you want to keep and reuse |
In IDLE you run a script with Run → Run Module.
Keywords and identifiers
Keywords are reserved words with a fixed meaning for the interpreter. They must be spelled exactly as given, because Python is case sensitive.
| Group | Keywords |
|---|---|
| Constants | False, None, True |
| Logic and tests | and, or, not, is, in |
| Decisions | if, elif, else |
| Loops | for, while, break, continue |
| Functions and classes | def, return, lambda, class, yield |
| Importing | import, from, as |
| Handling errors | try, except, finally, raise, assert |
| Scope and others | global, nonlocal, del, pass, with |
These 33 words make up the list. Only True, False and None start with a capital letter.
Beyond the textbook. For the exam: the keyword list is the 33 words in the table above. In reality: recent versions of Python have two more reserved words, async and await, so the list has 35 keywords. Why it matters: it does not change any rule: a keyword still cannot be used as a name.
An identifier is a name given to a variable, function or other entity. The rules:
| Rule | Detail |
|---|---|
| Start | An uppercase or lowercase letter or an underscore. It cannot start with a digit |
| Rest | Any mix of a to z, A to Z, 0 to 9 and underscore |
| Length | Any length, though short and meaningful is better |
| Not a keyword | A keyword cannot be an identifier |
| No special symbols | Symbols such as !, @, #, %, the dollar sign, a space or a hyphen are not allowed |
Worked example: which of these identifiers are invalid?
| Name | Valid? | Reason |
|---|---|---|
Serial_no. |
No | Contains a dot |
1st_Room |
No | Starts with a digit |
Total Marks |
No | Contains a space |
total-Marks |
No | The hyphen is read as a minus sign |
True |
No | It is a keyword |
Total_Marks |
Yes | Letters and underscore |
_Percentage |
Yes | Starting with an underscore is allowed |
true |
Yes | Case sensitive: not the keyword True |
A name such as Hundred followed by a dollar sign is also invalid because of the symbol. Use names that tell the reader what they hold, such as marks1, marks2, marks3 and avg, rather than a, b, c.
Pause and predict: is none a valid identifier? Is None?
Check your answer: none is valid, because Python is case sensitive and only None is the keyword. None is not valid as an identifier.
Variables: names that refer to objects
A variable is identified by a name (an identifier). In Python, a variable refers to an object, an item stored in memory, which may be a number, a string and so on. You create one with an assignment statement. There is no separate declaration: a variable is created automatically when you first assign a value, and it must be assigned before it is used in an expression, otherwise there is an error.
| Code |
|---|
message = "Keep Smiling" |
print(message) |
userNo = 101 |
print('User Number is', userNo) |
| Output |
|---|
Keep Smiling |
User Number is 101 |
The string is written in quotes (single or double) and the number is not. Wherever a variable name appears in an expression, the interpreter replaces it with its value.
| Code |
|---|
length = 10 |
breadth = 20 |
area = length * breadth |
print(area) |
| Output |
|---|
200 |
Everything is an object. Every value, numeric, string or other, is an object that can be assigned to a variable or passed to a function. Each object has a unique identity (ID) that stays the same for its lifetime, rather like its memory address, and the function id() returns it. Assignment copies only the reference, not the data. After num2 = num1, both names refer to the same object.
| Code |
|---|
num1 = 300 |
num2 = num1 |
print(num2 is num1) |
num1 = num2 + 100 |
print(num1, num2) |
print(num1 is num2) |
| Output |
|---|
True |
400 300 |
False |
Integers are immutable, so num2 + 100 does not change the object 300. It builds a new object 400, and num1 now refers to it while num2 still refers to 300.
Beyond the textbook. For the exam: equal values assigned from the same name share one object, and is compares identity. In reality: the standard Python implementation keeps ready made objects for small integers (about -5 to 256), so two separately created small integers usually are the same object, but two separately created large ones need not be. Why it matters: use == to compare values and keep is for checking identity and for None.
Comments are notes for humans that the interpreter ignores. A comment starts with # and runs to the end of the line. They document the purpose, input and output of a program, which matters when someone else maintains it. Do not over comment.
Data types
Every value has a data type, which decides what values it can hold and what operations are allowed. The built in function type() tells you the type.
| Category | Type | Example | Mutable? |
|---|---|---|---|
| Number | int | -12, 0, 125 | No |
| Number | float | -2.04, 4.0, 14.23 | No |
| Number | complex | 3 + 4j | No |
| Boolean | bool | True, False | No |
| Sequence | str (string) | 'Hello', "452" | No |
| Sequence | list | [5, 3.4, "New Delhi", 45] | Yes |
| Sequence | tuple | (10, 20, "Apple", 3.4) | No |
| Set | set | {10, 20, 3.14} | Yes |
| Mapping | dict (dictionary) | {'Fruit': 'Apple', 'Price(kg)': 120} | Yes |
| None | NoneType | None | Not applicable |
Points to hold on to:
| Type | Key facts |
|---|---|
| bool | A subtype of integer with two constants, True and False. False is the value zero; a value that is non-zero, non-null and non-empty counts as True |
| str | A group of characters in single or double quotes; the quotes are not part of the string; you cannot do numerical operations on a string, even "452" |
| list | Items separated by commas, in square brackets |
| tuple | Items in round brackets; cannot be changed once created |
| set | Unordered, in curly brackets, no duplicates: {1, 2, 1, 3} shows as {1, 2, 3} |
| None | A single value meaning absence of value; it is not the same as False or 0 |
| dict | Key and value pairs in curly brackets, with a colon between key and value; a value is found with its key in square brackets; faster access to data |
Mutable and immutable. A variable whose value can be changed after creation is mutable; one that cannot be changed is immutable. When you try to update an immutable variable, the old object is not changed: a new one is created under the same name. Lists, sets and dictionaries are mutable. Integers, floats, booleans, complex numbers, strings and tuples are immutable.
| Code |
|---|
list1 = [5, 3, 4] |
list1[0] = 9 |
print(list1) |
tuple1 = (10, 20, 30) |
tuple1[0] = 99 |
| Output |
|---|
[9, 3, 4] |
TypeError: 'tuple' object does not support item assignment |
Worked example: choose a data type. Say which type suits each value and why.
| Data | Type | Why |
|---|---|---|
| Number of months in a year | int | A whole number |
| Resident of Delhi or not | bool | Only two outcomes, True or False |
| Mobile number | str | We never calculate with it, and it may begin with 0 or a plus sign |
| Pocket money | float (or int) | May have paise |
| Volume of a sphere | float | Usually a fraction |
| Name or address of a student | str | Text |
| Names of the months | tuple | A fixed collection that never changes |
| Students in a class | list | Changes as students join or leave |
| Artefacts in a museum | set | Each must appear once |
| Phone book | dict | Name is the key, number is the value |
Use a list for a simple collection that changes often, a tuple when nothing should change, a set when each item must be unique, and a dictionary for fast lookup by a key.
Operators
An operator performs an operation on operands. In 10 + num, 10 and num are the operands and + is the operator. Unary operators have one operand (-x, not) and binary operators have two.
Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition (also joins strings) | 5 + 6 and "Hello" + "India" |
11 and HelloIndia |
- |
Subtraction | 5 - 6 |
-1 |
* |
Multiplication (also repeats a string) | 5 * 6 and 'India' * 2 |
30 and IndiaIndia |
/ |
Division, always gives a float | 8 / 4 |
2.0 |
% |
Modulus: remainder | 13 % 5 |
3 |
// |
Floor division: quotient without the decimal part | 13 // 4 |
3 |
** |
Exponent: power | 3 ** 4 |
81 |
Relational operators compare two values and give True or False: == (equal), != (not equal), >, <, >= and <=. Strings are compared lexicographically using the ASCII values of the characters, comparing the first characters and then the next, and so on. So "Good" > "Afternoon" is True because G (71) is greater than A (65), and "Bye" == "BYE" is False because capital and small letters have different codes.
Assignment operators. = assigns, and each shorthand does the operation and assigns the result: x += y means x = x + y, and the same holds for -=, *=, /=, %=, //= and **=.
| Code |
|---|
num1 = 10 |
num1 += 2 |
print(num1) |
num1 /= 4 |
print(num1) |
str1 = 'Hello' |
str1 += 'India' |
print(str1) |
| Output |
|---|
12 |
3.0 |
HelloIndia |
Notice that /= gives 3.0, a float, because / always returns a float.
Logical operators are and, or and not, always written in lower case. Every value is logically True or False. By default all values are True except None, False, 0 and empty collections such as "", (), [] and {}.
| Operator | Result |
|---|---|
x and y |
True only when both are true |
x or y |
True when at least one is true |
not x |
Reverses the logical state |
| Code |
|---|
num1 = 10 |
num3 = 0 |
print(bool(num1 and num3)) |
print(bool(num1 or num3)) |
print(not num1) |
| Output |
|---|
False |
True |
False |
Identity operators is and is not check whether two names refer to the same object (that is, whether id() is the same). Membership operators in and not in check whether a value is in a sequence.
| Code |
|---|
a = [1, 2, 3] |
print(2 in a, '1' in a, 10 not in a) |
| Output |
|---|
True False True |
'1' in a is False because the list holds the number 1, not the text '1'.
Worked example: predict each result. Take num1 = 4, num2 = 3, num3 = 2.
| Statement | Working | Result |
|---|---|---|
num1 += num2 + num3 |
$4 + (3 + 2)$ | 9 |
num1 = num1 ** (num2 + num3) with num1 = 4 |
$4^{5}$ | 1024 |
num1 = '5' + '5' |
Strings are joined | 55 (text) |
print(4.00 / (2.0 + 2.0)) |
$4.0 / 4.0$ | 1.0 |
print(10 != 9 and 20 >= 20) |
True and True | True |
print(float(10)) |
Convert to float | 10.0 |
Beyond the textbook. For the exam: // removes the decimal part, and and and or give True or False. In reality: // rounds down, so -7 // 2 is -4 (not -3) and -7 % 2 is 1. Also, and and or return one of their operands: 0 or 5 gives 5 and 10 and 20 gives 20, and that is why the textbook wraps them in bool(). Why it matters: the rule that explains both is that the remainder always takes the sign of the divisor, and that or returns the first true operand.
Expressions and precedence
An expression is a combination of constants, variables and operators and always evaluates to a value. A single value or variable is also an expression, but a lone operator is not. A statement is a unit of code the interpreter can execute, such as an assignment or a print.
When an expression mixes operators, precedence decides which is applied first. Higher precedence goes first, and operators of equal precedence go from left to right. Brackets override precedence. Unary operators have higher precedence than binary operators.
| Rank (high to low) | Operators | Description |
|---|---|---|
| 1 | ** |
Exponentiation |
| 2 | ~, unary +, unary - |
Complement, unary plus and minus |
| 3 | *, /, %, // |
Multiply, divide, modulo, floor division |
| 4 | +, - |
Addition and subtraction |
| 5 | <=, <, >, >=, ==, != |
Relational |
| 6 | =, %=, /=, //=, -=, +=, *=, **= |
Assignment |
| 7 | is, is not |
Identity |
| 8 | in, not in |
Membership |
| 9 | not |
Logical NOT |
| 10 | and |
Logical AND |
| 11 | or |
Logical OR |
Worked example: evaluate by precedence.
| Expression | Steps | Result |
|---|---|---|
20 + 30 * 40 |
Multiplication before addition: 20 + 1200 | 1220 |
20 - 30 + 40 |
Same level, left to right: (20 - 30) + 40 = -10 + 40 | 30 |
(20 + 30) * 40 |
Brackets first: 50 × 40 | 2000 |
15.0 / 4 + (8 + 3.0) |
Brackets: 11.0; division: 3.75; add | 14.75 |
24 // 4 // 2 |
Same level, left to right: 6 // 2 | 3 |
2 + 9 * ((3 * 12) - 8) / 10 |
36 - 8 = 28; 9 × 28 = 252; 252 / 10 = 25.2; 2 + 25.2 | 27.2 |
10 + 6 * 2 ** 2 != 9 // 4 - 3 |
Left: 10 + 6 × 4 = 34. Right: 2 - 3 = -1. Compare 34 != -1 | True |
Common wrong step. For 24 // 4 // 2, working from the right: 4 // 2 = 2, then 24 // 2 = 12. Equal precedence means left to right, so the answer is 3.
Beyond the textbook. For the exam: equal precedence is evaluated left to right, and the ranking is the table above. In reality: the exponent operator is the exception, and it groups right to left, so 2 ** 3 ** 2 is 2 ** 9, which is 512, not 64. Also, in real Python the relational, identity and membership operators share one level, which is why 1 < 2 < 3 works as a chain. Why it matters: when in doubt, use brackets; they are never wrong.
Input and output
The input() function reads what the user types and gives it back as a string, whatever was typed. Its optional argument is a prompt displayed first. Entry ends when the user presses Enter.
The print() function evaluates its arguments and writes them, then moves to the next line. It has two optional arguments: sep, the separator placed between values (default: a space) and end, the text added after the last value (default: a new line).
| Statement | Output | Why |
|---|---|---|
print("Hello") |
Hello |
A string |
print(10 * 2.5) |
25.0 |
The expression is evaluated first; int times float is float |
print("I" + "love" + "my" + "country") |
Ilovemycountry |
+ joins strings with no space |
print("I'm", 16, "years old") |
I'm 16 years old |
Commas pass several arguments; a space is put between them |
print("a", "b", sep="-") |
a-b |
sep replaces the space |
print("Hi", end="!") then print("there") |
Hi!there |
end replaces the new line |
Using + between a string and a number gives an error, while a comma works with any types.
Type conversion
The user's 2 became "22" because input gave the string "2". To get 4 the program must convert the string to an integer first.
| Code |
|---|
num1 = input("Enter a number and I'll double it: ") |
num1 = int(num1) |
num1 = num1 * 2 |
print(num1) |
| Step | Statement | Value of num1 | Type |
|---|---|---|---|
| 1 | num1 = input(...), user types 2 |
"2" | str |
| 2 | num1 = int(num1) |
2 | int |
| 3 | num1 = num1 * 2 |
4 | int |
| 4 | print(num1) |
prints 4 |
Without step 2, step 3 repeats the string, giving "22".
Explicit conversion (type casting) happens when the programmer forces the change. It can lose information.
| Function | What it does | Example | Result |
|---|---|---|---|
int(x) |
Converts to an integer | int(20.67) |
20 (the fraction is dropped, not rounded) |
float(x) |
Converts to a float | float(30) |
30.0 |
str(x) |
Converts to a string | str(70) |
'70' |
chr(x) |
Gives the character whose code is x | chr(66) |
'B' |
ord(c) |
Gives the code of the character c | ord('A') |
65 |
int('3.14') raises a ValueError, because "3.14" is not a whole number in text form. To get 3, convert in two steps: int(float('3.14')).
Python will not convert silently when it risks losing information. Joining text and a number fails:
| Code |
|---|
priceIcecream = 25 |
priceBrownie = 45 |
totalPrice = priceIcecream + priceBrownie |
print("The total in Rs." + totalPrice) |
This gives a TypeError, because Python cannot join a string and an integer. The fix is to state the conversion:
| Code |
|---|
print("The total in Rs." + str(totalPrice)) |
| Output |
|---|
The total in Rs.70 |
If the prices were the strings '25' and '45', then + would join them as '2545'. Only after int() is applied to each does the sum become 70.
Implicit conversion (coercion) happens automatically. When an int and a float meet in an expression, the int is converted to float (type promotion), because the wider type holds the result without losing information.
| Code |
|---|
num1 = 10 |
num2 = 20.0 |
sum1 = num1 + num2 |
print(sum1) |
print(type(sum1)) |
| Output |
|---|
30.0 |
<class 'float'> |
| Feature | Explicit conversion | Implicit conversion |
|---|---|---|
| Who decides | The programmer | The interpreter |
| Also called | Type casting | Coercion |
| How | int(), float(), str() |
Automatic, e.g. int promoted to float |
| Risk | Possible loss of information | None: goes to the wider type |
Pause and predict: what are 10 + 20.0, int(-2.7) and str(7) + '1'?
Check your answer: 30.0, -2 and '71'. The first is promoted to float. The second drops the fraction towards zero. The third joins two strings.
Beyond the textbook. For the exam: chr(x) gives the character for the code x, and ord(c) gives the code of the character c. In reality: the two are inverses: ord(chr(66)) is 66. They are easy to swap, so use this trick: ord is short for ordinal, the position number, which is the code. Why it matters: this is the same ASCII table from the encoding chapter, so chr(ord('A') + 2) is 'C'.
Putting it together: small programs
A program reads input, converts it, calculates and prints. Here is the pattern for converting Celsius to Fahrenheit using the formula $F = C \times \tfrac{9}{5} + 32$.
| Code |
|---|
celsius = float(input("Enter temperature in Celsius: ")) |
fahrenheit = celsius * 9 / 5 + 32 |
print("Temperature in Fahrenheit:", fahrenheit) |
| Input | Calculation | Output |
|---|---|---|
| 100 (boiling point) | $100 \times 9 / 5 + 32 = 180 + 32$ | Temperature in Fahrenheit: 212.0 |
| 0 (freezing point) | $0 + 32$ | Temperature in Fahrenheit: 32.0 |
For simple interest, $SI = \dfrac{P \times R \times T}{100}$ and the amount is $P + SI$. With $P = 1000$, $R = 5$, $T = 2$, $SI = 100$ and the amount is 1100.0 (a float, because float() was used for the inputs).
Swapping two values is a classic. With a third variable:
| Code |
|---|
a = 5 |
b = 9 |
temp = a |
a = b |
b = temp |
print(a, b) |
| Output |
|---|
9 5 |
The temporary variable is needed because after a = b the old value of a would be lost. Python can also swap in one line: a, b = b, a, because the whole right side is evaluated first and then assigned.
Worked example: tuple assignment. Trace num1, num2 = 2, 6 and then num1, num2 = num2, num1 + 2.
| Step | What happens | num1 | num2 |
|---|---|---|---|
| 1 | num1, num2 = 2, 6 |
2 | 6 |
| 2 | Right side evaluated with the old values: (6, 2 + 2) = (6, 4) | 2 | 6 |
| 3 | Assigned together | 6 | 4 |
The output of print(num1, num2) is 6 4. Common wrong step: updating num1 first to 6 and then computing num1 + 2 as 8, giving 6 8.
Debugging: the three kinds of error
A bug is a mistake in a program. Debugging is finding and removing bugs. There are three kinds.
| Feature | Syntax error | Logical error | Runtime error |
|---|---|---|---|
| What goes wrong | The rules of the language are broken | The program's meaning is wrong | A correct statement cannot be carried out while running |
| When it shows | Before running; the interpreter shows a message and stops | Never shows a message; only the wrong output is evidence | After the program starts; it stops abruptly |
| Example | (7 + 11 has a missing right bracket |
10 + 12 / 2 to get the average of 10 and 12 |
Dividing by zero, or int('abc') |
A logical error is also called a semantic error. For 10 + 12 / 2 (meant as the average of 10 and 12), Python gives 16.0, because division goes first. The right code is (10 + 12) / 2, which gives 11.0. The program ran perfectly and was still wrong.
| Code |
|---|
num1 = 10.0 |
num2 = int(input("num2 = ")) |
print(num1 / num2) |
If the user types 5, this prints 2.0. If the user types 0, it stops with a ZeroDivisionError, and if the user types a word instead of a number, int() stops it with a ValueError. Both are runtime errors: the code is correct, but this particular input cannot be handled.
Worked example: classify the error.
| Statement | Error type | Reason |
|---|---|---|
25 / 0 |
Runtime | Valid code, impossible while executing |
print("Total" + 70) |
Runtime (TypeError) | Valid syntax, but the types cannot be joined |
average = a + b / 2 meant as (a + b) / 2 |
Logical | Runs but gives a wrong value |
print("Hi" |
Syntax | Closing bracket missing |
Good documentation also helps: state the objective at the start, use meaningful variable and program names (not single letters or your own name), indent properly, keep naming conventions the same throughout, and use comments where they help understanding, but not too many.
Exam traps
| The trap | Why it's tempting | The truth |
|---|---|---|
"input() returns a number if you type a number." |
The user typed digits | It always returns a string. Convert with int() or float() |
"8 / 4 is 2." |
Both are whole numbers | / always gives a float, so 2.0. Use // for a whole quotient |
"True and true are the same." |
They read the same | Python is case sensitive: True is a keyword and true is an ordinary name |
"24 // 4 // 2 is 12." |
Working from the right | Equal precedence goes left to right: 6 // 2 = 3 |
| "A tuple can be changed like a list." | Both are sequences | A tuple is immutable; trying to change an item gives a TypeError |
"'Rs.' + 70 prints Rs.70." |
Python should understand | It raises a TypeError. Use str(70) |
| "A logical error stops the program with a message." | All errors are errors | The program runs; only the output is wrong |
"int(20.67) gives 21." |
Rounding habit | int() drops the fraction and gives 20 |
60-second revision
| Topic | Lock this in |
|---|---|
| Python | High level, free, open source, interpreted, case sensitive, portable, indentation for blocks |
| Modes | Interactive (>>>, one statement) and script (.py file) |
| Identifier | Starts with a letter or underscore; letters, digits, underscore only; not a keyword |
| Comment | Starts with #, ignored by the interpreter |
| Mutable | list, set, dictionary |
| Immutable | int, float, complex, bool, str, tuple |
| Arithmetic | / float division, // floor division, % remainder, ** power |
| Logical | and, or, not; values 0, None, False and empty collections are False |
| Identity / membership | is, is not / in, not in |
| Precedence | Power, then unary, then multiplication group, then addition group, relational, not, and, or |
| input / print | input gives a string; print has sep and end |
| Conversion | Explicit: int(), float(), str(), chr(), ord(); implicit: int to float |
| Errors | Syntax (before running), logical (wrong output), runtime (stops while running) |
Operator and function sheet
| Quantity | Formula or form | When to use |
|---|---|---|
| Quotient and remainder | $a = b \times \lfloor a / b \rfloor + (a \bmod b)$ | Checking // and % together: 13 = 4 × 3 + 1 |
| Power | x ** n means $x^{n}$ |
Squares, cubes, any power |
| Average | (a + b + c) / 3 |
Brackets needed because of precedence |
| Celsius to Fahrenheit | $F = C \times 9 / 5 + 32$ | Temperature programs |
| Simple interest | $SI = P \times R \times T / 100$ | Interest and amount programs |
| Character codes | ord('A') is 65, chr(65) is 'A' |
ASCII conversions |
Where this chapter connects
- Previous: Introduction to Problem Solving is where the algorithms come from that you now write as programs.
- Next: Flow of Control adds the if statement and loops, so programs can choose and repeat.
- Data types in depth: Strings, Lists and Tuples and Dictionaries develop the sequence and mapping types introduced here.
- Earlier links: Computer System explains interpreters and compilers, and Encoding Schemes and Number System explains the codes behind
ordandchr.
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which statement about Python is INCORRECT?
▸ Show answer & explanation
Answer: C
Python marks blocks and nested blocks using indentation. Curly braces are used for sets and dictionaries, not for blocks. The other three statements are correct.
Q2. Which of the following is a valid identifier in Python?
▸ Show answer & explanation
Answer: C
An identifier may contain letters, digits and underscores but cannot start with a digit. The name 2ndPlace starts with a digit, total marks has a space, and for is a keyword.
Q3. Which of the following cannot be used as a variable name because it is a keyword?
▸ Show answer & explanation
Answer: B
True with a capital T is a reserved word. Python is case sensitive, so true in small letters is just an ordinary name, and Total and total1 are also valid.
🔒 12 more practice MCQs
Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.
Already registered? Just log in and they'll all appear here.
Q4. What is printed by print(chr(ord('A') + 2))?
▸ Show answer & explanation
Answer: A
ord('A') is 65, adding 2 gives 67, and chr(67) is the character C. Option B would be the output of print(ord('A') + 2), without chr.
Q5. What is the value of 24 // 4 // 2?
▸ Show answer & explanation
Answer: A
The two operators have equal precedence, so they go from left to right: 24 // 4 is 6 and 6 // 2 is 3. Going from the right would wrongly give 12. Floor division of integers gives an integer, so the result is not 3.0.
Q6. Consider: (1) age = input('Enter your age: ') (2) the user types 19. What is the data type of age?
▸ Show answer & explanation
Answer: C
The input function always returns what was typed as a string, so age holds the text 19. It must be converted with int() before any arithmetic.
Q7. Consider: (1) num = input('Enter a number: ') (2) the user types 2 (3) num = num + num (4) print(num). What is printed?
▸ Show answer & explanation
Answer: B
The input is the string 2, and the plus operator joins two strings, so 2 and 2 join to form 22. No error occurs because both operands are strings.
Q8. What happens when int('3.14') is executed?
▸ Show answer & explanation
Answer: C
The text 3.14 is not a valid whole number, so int cannot convert it directly. The conversion int(float('3.14')) works in two steps and gives 3. Option D assumes rounding, which int never does.
Q9. The expression (7 + 11 is an example of which kind of error?
▸ Show answer & explanation
Answer: C
The right bracket is missing, which breaks the rules of the language, so the interpreter reports it before running. Logical errors, also called semantic errors, give wrong output, and runtime errors happen while executing, for example when dividing by zero.
Q10. Which of the following data types is immutable?
▸ Show answer & explanation
Answer: D
A tuple cannot be changed once created. Lists, dictionaries and sets are mutable.
Q11. Consider the statements. (1) A set cannot contain duplicate entries. (2) A dictionary stores data as key and value pairs. (3) The items of a tuple can be changed after it is created. Which are correct?
▸ Show answer & explanation
Answer: A
Statement 1 and statement 2 are correct. Statement 3 is wrong because a tuple is immutable, and changing an item raises a TypeError.
Q12. Consider: (1) num1 = 10 (2) num3 = 0 (3) print(bool(num1 and num3), bool(num1 or num3)). What is printed?
▸ Show answer & explanation
Answer: B
The and operator needs both operands to be true, and 0 is false, so the first value is False. The or operator needs only one true operand, and 10 is true, so the second value is True.
Q13. Match List I with List II. List I: (i) // (ii) % (iii) is (iv) in. List II: (p) tests whether a value is present in a sequence (q) gives the remainder (r) tests whether two names refer to the same object (s) gives the quotient with the decimal part removed
▸ Show answer & explanation
Answer: A
Floor division gives the quotient without the decimal part, the percent operator gives the remainder, is compares identity and in tests membership. Option B swaps the first two and option C swaps the last two.
Q14. Consider: (1) print('A', 'B', sep='-') (2) print('C', end='!') (3) print('D'). What is the output?
▸ Show answer & explanation
Answer: A
The first print joins its values with a hyphen and ends with the default new line. The second print ends with an exclamation mark instead of a new line, so the third print continues on the same line, giving C!D. Option B ignores sep.
Q15. Consider: (1) a, b = 2, 6 (2) a, b = b, a + 2 (3) print(a, b). What is printed?
▸ Show answer & explanation
Answer: A
The whole right side is evaluated first using the old values, giving 6 and 4, and then both names are assigned together. Option B results from changing a first and then using the new a.
📊 Previous-Year Questions
Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.
View solved CUET PYQ papers →Ready to drill Computer Science?
Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.
Get UniDrill Pro