📌 Snapshot
- Python basics from keywords to nested loops, with output tracing and error spotting for exam questions.
- Why a variable cannot start with a digit, why input always gives a string, and why 5 // 2 is 2 and 5 / 2 is 2.5.
- Operators and precedence solved step by step, so you can evaluate any expression the way Python does.
- if, elif, else, for and range traced line by line, plus the three kinds of error and how to tell them apart.
📖 Detailed Notes
Written and reviewed by Rohit Singh, Computer Science & Commerce faculty at UniDrill (MCA, Osmania University · 6 years teaching). Based on NCERT Informatics Practices Class XI, Chapter 3.
Why does one missing bracket stop everything?
A computer follows instructions exactly, with no guessing. Leave out one closing bracket and Python refuses to run the program at all. Leave out the right idea and it runs happily and gives the wrong answer. Learning Python is learning to give exact instructions, and exam questions test the same skill: read a few lines, say what happens, and say what would go wrong.
An ordered set of instructions executed by a computer is a program, and the language used to write it is a programming language. Python is a popular, easy to learn language created by Guido van Rossum in 1991. It is used in software development, web development, scientific computing, big data and Artificial Intelligence. Python is an open source, high level, interpreter based language. The programs in this book use Python 3.
Working with Python: two modes
To write and run a Python program you need a Python interpreter (also called the Python shell). The prompt >>> shows that the interpreter is ready to receive instructions.
| Feature | Interactive mode | Script mode |
|---|---|---|
| How you work | Type a statement at the prompt, press Enter, see the result at once | Write the program in a file, save it, then run the file |
| Can you save the code? | No. You must retype to run it again | Yes. Files have the extension .py and are called scripts |
| Best for | Testing a single line quickly | Programs of more than a few lines |
| Tool | Python shell | Any editor, such as IDLE, Python's built in editor (Integrated Development and Learning Environment) |
In IDLE you choose File, New File, write the program and save it, then use Run, Run Module to execute it. The output appears in the shell.
Keywords and identifiers
Keywords are reserved words that have a fixed meaning for the interpreter. Python is case sensitive, so keywords must be written exactly as defined: True, False and None begin with a capital letter, and words such as if, for, while, and, or, not, in, is, def, class, import and return are all lower case.
Identifiers are the names you give to variables, functions and other entities. The rules:
| Rule | Valid example | Invalid example and why |
|---|---|---|
| Starts with a letter or an underscore | _Percentage, total1 |
1st_Room: starts with a digit |
| Followed by letters, digits or underscores only | Total_Marks |
total-Marks: hyphen is a special symbol |
| No special symbols (such as ! @ # % or the dollar sign) and no spaces | marksMaths |
Total Marks (space) and a name ending in a dollar sign, like Hundred |
| Must not be a keyword | true (different case) |
True is reserved |
| Any length, but short and meaningful is preferred | avg |
none |
Worked example: which identifiers are valid? Check Serial_no., 1st_Room, Hundred followed by a dollar sign, Total Marks, Total_Marks, total-Marks, _Percentage, True.
| Step | What we do | Result |
|---|---|---|
| 1 | Check the first character | 1st_Room starts with a digit, so it is invalid |
| 2 | Scan for symbols or spaces | Serial_no. (dot), the Hundred name (dollar sign), Total Marks (space) and total-Marks (hyphen) are invalid |
| 3 | Compare with the keyword list | True is a keyword, so it is invalid |
| 4 | What is left | Total_Marks and _Percentage are valid |
The common wrong step is to accept total-Marks because it "looks readable". Python reads the hyphen as a minus sign, so it can never be part of a name.
Why meaningful names matter. To find an average you could write avg = (marksMaths + marksEnglish + marksIP)/3. Names like marksMaths tell the reader what the data is. Names like a, b and c do not.
Variables and comments
A variable is an identifier whose value can change. You create one with an assignment statement, and the interpreter replaces the variable name with its current value wherever it appears.
| Code |
|---|
gender = 'M' |
message = "Keep Smiling" |
price = 987.9 |
A variable must be given a value before it is used, otherwise Python raises an error. A comment begins with # and runs to the end of the line. The interpreter ignores it. It exists only to explain the code to humans.
Worked example: sum of two numbers.
| Code |
|---|
#To find the sum of two given numbers |
num1 = 10 |
num2 = 20 |
result = num1 + num2 |
print(result) |
| Output |
|---|
30 |
The first two lines store values, the third computes 10 + 20, and print() shows the result. The comment line does nothing.
Data types
Every value has a data type, which says what kind of data a variable can hold and what operations can be done on it. The built in function type() reports it.
| Category | Types | Example values |
|---|---|---|
| Number | int, float, complex | -12, 123 · -2.04, 4.0 · 3 + 4i |
| Boolean | bool (a subtype of integer) | True, False |
| Sequence | string, list, tuple | 'Hello' · [5, 3.4, "New Delhi"] · (10, 20, "Apple") |
| Mapping | dictionary | {'Fruit': 'Apple', 'Price(kg)': 120} |
| Others | set, None | — |
For Boolean values, True counts as a non zero value and False is the value zero.
| Code |
|---|
quantity = 10 |
print(type(quantity)) |
price = -1921.9 |
print(type(price)) |
| Output |
|---|
<class 'int'> |
<class 'float'> |
Sequences are ordered collections in which each item is indexed by an integer.
| Type | Brackets | Can items be changed? | Items of different types? |
|---|---|---|---|
| String | Single or double quotes | No numeric operations, even on "452" |
Characters only |
| List | Square brackets [ ] |
Yes | Yes |
| Tuple | Parentheses ( ) |
No, fixed once created | Yes |
The quotes around a string are not part of it. They only tell the interpreter where the string starts and stops. A dictionary stores key value pairs in curly brackets { }, with a colon between key and value, and you read a value by writing its key in square brackets. Keys are usually strings, and values can be of any type.
| Code |
|---|
dict1 = {'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120} |
print(dict1['Price(kg)']) |
| Output |
|---|
120 |
Beyond the textbook. For the exam: a dictionary is an unordered mapping data type, and there is only one standard mapping type. In reality: from Python 3.7 onwards a dictionary remembers the order in which items were inserted, though you still look values up by key and never by position. Why it matters: answer "unordered" if the question uses the book's wording. Do not use position to read a value from a dictionary.
Pause and predict: what data type does Python give to type("452"), and can you add 1 to it?
Check your answer: it is a string (str), because the digits sit inside quotes. Adding the number 1 to it raises an error, since numerical operations cannot be done on strings, even numeric looking ones.
Operators
An operator performs a mathematical or logical operation on values. The values it works on are operands. In 10 + num, 10 and num are operands and + is the operator.
Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 6 |
11 |
- |
Subtraction | 5 - 6 |
-1 |
* |
Multiplication | 5 * 6 |
30 |
/ |
Division (quotient with decimal) | 5 / 2 |
2.5 |
% |
Modulus (remainder) | 13 % 5 |
3 |
// |
Floor division (integer quotient) | 5 // 2 and 2 // 5 |
2 and 0 |
** |
Exponent | 3 ** 4 |
81 |
The + operator joins two strings (concatenation), so "Hello" + "India" gives 'HelloIndia'. The * operator repeats a string when the other operand is an integer, so 'India' * 2 gives 'IndiaIndia'. Both also work for lists and tuples.
Why // and % come as a pair. Divide 13 by 5. The whole number of fives is 2 (13 // 5) and what is left over is 3 (13 % 5). Check: $5 \times 2 + 3 = 13$. Whenever a question mixes // and %, rebuild the number this way.
Beyond the textbook. For the exam: // gives the quotient with the decimal part removed. In reality: it rounds down (floors), which differs from "removing the decimal part" when a number is negative. -5 // 2 is -3, not -2, and -13 % 5 is 2. Why it matters: CUET questions at this level use positive numbers, so the simple rule works, but knowing floor division prevents surprises in later chapters.
Relational operators compare values and give True or False: == (equal), != (not equal), >, <, >=, <=. Strings are compared lexicographically, character by character using the ASCII values of the characters. So "Good" > "Afternoon" is True, because G comes after A.
Assignment operators store values. = assigns, and the shortcuts +=, -=, *=, /=, %=, //= and **= update a variable. x += y means x = x + y.
Logical operators and, or, not must be in lower case.
| Operator | Result is True when |
|---|---|
| and | both operands are True |
| or | at least one operand is True |
| not | reverses the truth value of its operand |
Membership operators in and not in check whether a value is present in a sequence. With numSeq = [1, 2, 3], 2 in numSeq is True but '1' in numSeq is False, because the string '1' is not the integer 1.
Expressions and precedence
An expression is a combination of constants, variables and operators, and it always evaluates to a value. A single value or a lone variable counts as an expression, but a standalone operator does not.
When an expression has several operators, precedence decides which one is applied first. Higher precedence goes first. Operators of equal precedence work from left to right. Parentheses override everything, and the part inside ( ) is evaluated first.
| Order (high to low) | Operators |
|---|---|
| 1 | ** |
| 2 | *, /, //, % |
| 3 | +, - |
| 4 | Relational: <, <=, >, >=, ==, != |
| 5 | not |
| 6 | and |
| 7 | or |
Worked example: evaluate step by step. Evaluate 20 + 30 * 40, then (20 + 30) * 40, then 15.0 / 4.0 + (8 + 3.0).
| Step | What we do | Result |
|---|---|---|
| 1 | In 20 + 30 * 40, multiplication comes before addition |
$20 + 1200$ |
| 2 | Add | 1220 |
| 3 | In (20 + 30) * 40, brackets force the addition first |
$50 \times 40$ |
| 4 | Multiply | 2000 |
| 5 | In 15.0 / 4.0 + (8 + 3.0), brackets first, then division |
$3.75 + 11.0$ |
| 6 | Add | 14.75 |
The common wrong step is to work strictly left to right and get $(20 + 30) \times 40 = 2000$ for the first expression.
Worked example: operators and booleans. Let num1 = 4, num2 = 3, num3 = 2. Find the output.
| Code |
|---|
num1 += num2 + num3 |
print(num1) |
num1 = num1 ** (num2 + num3) |
print(num1) |
print(4.00 / (2.0 + 2.0)) |
print(10 != 9 and 20 >= 20) |
print(5 % 10 + 10 < 50 and 29 <= 29) |
| Line | Working | Value |
|---|---|---|
num1 += num2 + num3 |
$4 + (3 + 2) = 9$ | num1 is 9 |
num1 = num1 ** (num2 + num3) |
$9^{5} = 59049$ | num1 is 59049 |
print(4.00 / (2.0 + 2.0)) |
$4.0 / 4.0$ | 1.0 |
print(10 != 9 and 20 >= 20) |
True and True | True |
print(5 % 10 + 10 < 50 and 29 <= 29) |
$5 + 10 = 15$, then 15 < 50 is True, and 29 <= 29 is True | True |
The arithmetic runs first, the relational comparisons come next and and runs last. That is exactly the precedence table in action.
Input and output
The input() function reads what the user types and always returns it as a string, even if the user types digits. The syntax is variable = input([Prompt]), where the prompt is optional text shown on screen. To use the value as a number, convert it with int() (or float()). If the text is not numeric, an error occurs.
| Code |
|---|
age = input("Enter your age: ") |
print(type(age)) |
age = int(age) |
print(type(age)) |
| Output |
|---|
<class 'str'> |
<class 'int'> |
The print() function evaluates the expression and displays the result. With several arguments separated by commas, it prints them with a space in between.
| Code |
|---|
print("Hello") |
print(10 * 2.5) |
| Output |
|---|
Hello |
25.0 |
Why 25.0 and not 25? One operand is a float (2.5), so the result is a float. Mixed arithmetic of int and float always gives a float.
Pause and predict: a user types 7 when asked to enter a number, and the program runs n = input("Enter: ") followed by print(n + n). What is printed?
Check your answer: 77. The input is the string '7', and + joins two strings. If you wanted 14, you must write int(input("Enter: ")).
Debugging: three kinds of error
Programs fail in different ways. Debugging is identifying and removing errors.
| Error | When it appears | Does the program run? | Example |
|---|---|---|---|
| Syntax error | Rules of the language are broken | No. The interpreter shows a message and stops | (7 + 11 has a missing right parenthesis |
| Runtime error | The statement is correct but cannot be executed | Starts, then stops abnormally | Division by zero gives "division by zero" |
| Logical error (semantic error) | The logic is wrong | Yes, but the output is wrong | 10 + 12/2 to find the average gives 16.0 instead of 11.0 |
Why logical errors are the hardest. There is no error message. The program looks perfect and the answer is quietly wrong. The fix is (10 + 12) / 2, because division has higher precedence than addition.
Worked example: classify the error. (a) 25 / 0 (b) print("Hi" (c) averaging with a + b / 2.
| Item | Reason | Type |
|---|---|---|
25 / 0 |
The statement is valid, but dividing by zero cannot be executed | Runtime error |
print("Hi" |
The bracket is not closed, so the rule of writing is broken | Syntax error |
a + b / 2 as an average |
Runs without complaint but gives the wrong result | Logical error |
Functions
A function is a set of statements grouped under a name to perform a task. It is defined once and reused by calling its name. For example, a function CalcCompInt could hold the compound interest steps so you do not rewrite them at every place in the program.
Python has many built in functions, such as print() and input(). A module is a Python file that groups many functions, and you bring one into your program with import. To use a function you need to know three things.
| Part | Meaning |
|---|---|
| Function name | The name used to call it |
| Arguments | The values passed inside the parentheses. A function may take none |
| Return value | The result passed back to the calling point. Some functions return nothing |
| Category | Built in functions |
|---|---|
| Input and output | input(), print() |
| Data type conversion | bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple() |
| Mathematical | abs(), divmod(), max(), min(), pow(), sum() |
| Other | len(), range(), type(), __import__() |
| Code |
|---|
num = int(input("Enter the first number")) |
square = num * num |
print("the square of", num, " is ", square) |
In this program the first line uses two built in functions, int() and input(). The input function gets the text typed by the user, and int() takes that text as its argument and returns an integer. The print() function has four arguments.
Decision making: if, if else, if elif else
Normally statements run one after another. Conditional statements let the program choose a path. Python marks a block of statements by indentation, which is leading whitespace at the start of a line. All statements at the same indentation level belong to one block, and wrong indentation is a syntax error. A colon : ends each condition line.
| Form | What it does |
|---|---|
if |
Runs its block only when the condition is true |
if ... else |
Runs the if block when the condition is true, otherwise the else block |
if ... elif ... else |
Checks several conditions in order and runs the first block whose condition is true |
| Code |
|---|
number = int(input("Enter a number: ")) |
if number > 0: |
print("Number is positive") |
elif number < 0: |
print("Number is negative") |
else: |
print("Number is zero") |
If the first condition is false, the next is checked, and so on. As soon as one is true, its block runs and the whole if statement ends. The number of elif parts depends on how many conditions you need. If no condition is true, the else block runs.
Worked example: trace an if else. The program subtracts the smaller number from the larger. The user enters 5 and then 6.
| Code |
|---|
num1 = int(input("Enter first number: ")) |
num2 = int(input("Enter second number: ")) |
if num1 > num2: |
diff = num1 - num2 |
else: |
diff = num2 - num1 |
print("The difference of", num1, "and", num2, "is", diff) |
| Output |
|---|
The difference of 5 and 6 is 1 |
| Step | What happens | State |
|---|---|---|
| 1 | num1 = 5, num2 = 6 | |
| 2 | Is 5 > 6? | False, so the else block runs |
| 3 | diff = 6 - 5 | diff is 1 |
| 4 | print runs (it is outside the if else) | Output shown above |
The common wrong step is to forget that print is not indented, so it runs after the if else whichever branch was taken.
Why elif and not many separate if statements? With separate if lines, Python checks every condition even after one was true. With elif, only the first true branch runs. That is both faster and avoids two blocks running for one input.
Loops: for and range()
Repeating work is called looping or iteration. The for statement repeats a block for each item in a range of values or a sequence (a string, list or tuple). When the items are used up, the loop ends and the statement after it runs. Use for when you know in advance how many times to repeat.
Syntax: for <control-variable> in <sequence or range>: followed by an indented body.
| Code |
|---|
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
for num in numbers: |
if (num % 2) == 0: |
print(num, 'is an even Number') |
| Output |
|---|
2 is an even Number |
4 is an even Number |
6 is an even Number |
8 is an even Number |
10 is an even Number |
The range() function has the form range(start, stop, step). It gives integers from start up to, but not including, stop, in jumps of step. If start is missing it is 0, and if step is missing it is 1. All values must be integers, and step can be negative but not zero.
| Call | Values produced | Why |
|---|---|---|
list(range(10)) |
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Starts at 0, stops before 10 |
list(range(2, 10)) |
[2, 3, 4, 5, 6, 7, 8, 9] |
Starts at 2 |
list(range(0, 30, 5)) |
[0, 5, 10, 15, 20, 25] |
Jumps of 5, 30 excluded |
list(range(0, -9, -1)) |
[0, -1, -2, -3, -4, -5, -6, -7, -8] |
Negative step counts down |
Beyond the textbook. For the exam: range() creates a sequence of integers, and you see it with list(range(...)). In reality: in Python 3 range() does not build the whole list. It produces numbers one at a time when needed, which saves memory, and wrapping it in list() is what turns it into a visible list. Why it matters: typing print(range(5)) alone shows range(0, 5), not the numbers.
Worked example: trace a for with range. Predict the output.
| Code |
|---|
for num in range(5): |
if num > 0: |
print(num * 10) |
| Iteration | num | Is num > 0? | Printed |
|---|---|---|---|
| 1 | 0 | No | nothing |
| 2 | 1 | Yes | 10 |
| 3 | 2 | Yes | 20 |
| 4 | 3 | Yes | 30 |
| 5 | 4 | Yes | 40 |
The common wrong step is to include 5 because range(5) "means up to 5". The loop stops before 5, so the last value of num is 4.
Worked example: loop over a string and a range with step.
| Code |
|---|
country = 'INDIA' |
for i in country: |
print(i) |
for i in range(20, 30, 2): |
print(i) |
The first loop prints I, N, D, I, A on separate lines, one character per iteration. The second loop prints 20, 22, 24, 26 and 28 on separate lines, because it jumps by 2 and stops before 30.
Nested loops
A loop inside another loop is a nested loop. For each single pass of the outer loop, the inner loop runs completely.
| Code |
|---|
for var1 in range(3): |
print("Iteration " + str(var1 + 1) + " of outer loop") |
for var2 in range(2): |
print(var2 + 1) |
print("Out of inner loop") |
print("Out of outer loop") |
| Output |
|---|
Iteration 1 of outer loop |
1 |
2 |
Out of inner loop |
Iteration 2 of outer loop |
1 |
2 |
Out of inner loop |
Iteration 3 of outer loop |
1 |
2 |
Out of inner loop |
Out of outer loop |
How to read it. The outer loop runs 3 times and the inner loop runs 2 times per outer pass, so the inner print(var2 + 1) runs $3 \times 2 = 6$ times. The line "Out of inner loop" is indented under the outer loop, so it runs 3 times. The last line has no indent, so it runs once.
Pause and predict: if the inner loop in the program above were range(4), how many times would the number lines be printed in total?
Check your answer: $3 \times 4 = 12$ times. The number of inner runs is the outer count multiplied by the inner count.
Exam traps
| The trap | Why it's tempting | The truth |
|---|---|---|
"5 / 2 gives 2." |
Whole numbers in, so a whole number out | / always gives a decimal result: 2.5. Use // for 2 |
"input() returns a number if I type digits." |
The screen shows digits | It always returns a string |
| "An identifier can start with a digit." | Names like 1st look natural | It must start with a letter or underscore |
"True and true are the same." |
They look alike | Python is case sensitive. True is a keyword, true is not |
"range(1, 5) includes 5." |
The word range suggests inclusive | The stop value is excluded: 1, 2, 3, 4 |
| "Tuples can be modified like lists." | Both hold ordered items | Items in a tuple cannot be changed after creation |
| "A logical error stops the program." | Errors usually stop things | Logical errors do not stop it. The output is wrong |
"elseif is a valid Python keyword." |
It reads naturally | The keyword is elif |
"2 in [1, 2, 3] and '2' in [1, 2, 3] are both True." |
They look alike | The second is False: a string is not the integer 2 |
60-second revision
| Topic | Lock this in |
|---|---|
| Python | Created by Guido van Rossum in 1991 · open source, high level, interpreter based |
| Modes | Interactive (>>>, one line, not saved) · script (.py file, IDLE) |
| Identifier rules | Start with letter or underscore · letters, digits, underscore only · not a keyword · case sensitive |
| Data types | int, float, complex, bool · string, list, tuple · dictionary · set, None |
| Mutable or not | List can change · tuple cannot · string cannot |
| Operators | / decimal, // floor, % remainder, ** power · + joins and * repeats strings |
| Precedence | **, then * / // %, then + -, then relational, then not, and, or · brackets first |
| input() | Always returns a string, so convert with int() or float() |
| Errors | Syntax (stops before running) · runtime (stops while running) · logical (wrong output) |
| Conditionals | if, if else, if elif else · indentation defines blocks · colon ends the condition |
| Loops | for over a range or sequence · range(start, stop, step) stop excluded · nested loop runs inner fully per outer pass |
Where this chapter connects
- Previous: Emerging Trends mentions Pandas, the Python library for data analysis that Class XII builds on.
- Next: Working with Lists and Dictionaries takes the list and dictionary introduced here and shows how to change and traverse them.
- Class XII link: Data Handling using Pandas I applies these same Python basics to tables of data.
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which of the following is a valid Python identifier?
▸ Show answer & explanation
Answer: C
An identifier may start with a letter or underscore and contain letters, digits and underscores. Option A starts with a digit, B contains a hyphen and D is a keyword.
Q2. Consider: (1) a = 17 (2) b = 5 (3) print(a // b, a % b). What is printed?
▸ Show answer & explanation
Answer: A
17 divided by 5 gives quotient 3 with remainder 2, so floor division gives 3 and modulus gives 2. Option B uses ordinary division, C swaps the two values and D gives the wrong remainder.
Q3. Consider: (1) x = input("Enter: ") (2) the user types 12 (3) print(x + x). What is printed?
▸ Show answer & explanation
Answer: B
input() returns the text 12 as a string, and the plus operator joins two strings. To get 24 the program would have to convert x with int() first.
🔒 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 the value of the expression 8 + 4 // 3 - 2 ?
▸ Show answer & explanation
Answer: B
Floor division comes before addition and subtraction, so 4 // 3 is 1. Then 8 + 1 - 2 is 7. Option A and C come from working left to right, and D uses ordinary division.
Q5. Which of the following lists the three kinds of error in a program?
▸ Show answer & explanation
Answer: A
The three errors are syntax, logical (semantic) and runtime. Keyword and identifier are not error categories, and compile or link errors are not named as the types in this chapter.
Q6. A program computes the average of 10 and 12 by writing 10 + 12 / 2 and prints 16.0. What kind of error is this?
▸ Show answer & explanation
Answer: C
The program runs without any message but gives a wrong answer, because division is done before addition. The correct form is (10 + 12) / 2, which gives 11.0.
Q7. How many times does the word Hi get printed? Consider: (1) for i in range(2, 9, 3): (2) print("Hi") with the print statement indented inside the loop.
▸ Show answer & explanation
Answer: B
range(2, 9, 3) gives 2, 5 and 8, which is three values, so the loop runs three times. The stop value 9 is not included. Option A and D miscount the values and C counts the numbers from 2 to 8.
Q8. Which function call creates the list [0, 5, 10, 15, 20, 25] ?
▸ Show answer & explanation
Answer: A
Starting at 0 with a step of 5 and stopping before 30 gives 0 to 25. Option C stops before 25 so it misses 25, B has step 1 and D has an invalid step order for this list.
Q9. Consider: (1) s = "Go" (2) print(s + s, len(s)). What is printed?
▸ Show answer & explanation
Answer: A
The plus operator joins the strings to give GoGo, and len(s) is 2, the number of characters in Go. Option B adds a space inside the string, C uses the wrong length and D ignores the join.
Q10. Which of the following statements about a tuple is correct?
▸ Show answer & explanation
Answer: B
A tuple uses parentheses and is fixed once created. Square brackets are for a list, key value pairs belong to a dictionary, and a tuple can hold items of different types.
Q11. Consider: (1) nums = [1, 2, 3] (2) print(2 in nums, '2' in nums). What is printed?
▸ Show answer & explanation
Answer: B
The integer 2 is in the list, so the first result is True. The string '2' is a different value from the integer 2, so the second result is False.
Q12. Which statement about the input() function is correct?
▸ Show answer & explanation
Answer: B
Whatever is typed is returned as a string, and converting needs int() or float(). The prompt is optional, and input() works in both interactive and script modes.
Q13. Assertion (A): The expression 5 / 2 gives 2.5 in Python. Reason (R): The division operator returns the quotient with its decimal part.
▸ Show answer & explanation
Answer: A
The division operator keeps the decimal part, so 5 divided by 2 gives 2.5. The reason states exactly how the operator behaves, so it explains the assertion. Floor division is the operator that drops the decimal part.
Q14. Consider: (1) total = 0 (2) for n in range(1, 5): total = total + n (3) print(total). The addition in step 2 is inside the loop. What is printed?
▸ Show answer & explanation
Answer: B
range(1, 5) gives 1, 2, 3 and 4, and their sum is 10. Option A includes 5 as well, C is the last value of n and D is the sum of 1, 2 and 3 only.
Q15. Match List I with List II. List I: (i) Syntax error (ii) Runtime error (iii) Logical error (iv) Comment. List II: (p) Division by zero while running (q) Ignored by the interpreter (r) Wrong output with no message (s) Missing closing bracket
▸ Show answer & explanation
Answer: A
A missing bracket is a syntax error, division by zero happens at run time, a wrong output without a message is a logical error, and a comment is skipped by the interpreter. The other options swap at least two pairs.
📊 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