Python Fundamentals

Computer Science – XI · Chapter 5 · Questions and Answers

5.1–5.2 Character set and tokens

1. What is a character set? What does the Python character set include?

A character set is the collection of valid characters a language can recognise and use for writing programs. Python's includes letters (A–Z, a–z), digits (0–9), special symbols, whitespace characters (blank space, tab, newline, carriage return) and other ASCII and Unicode characters.

2. What is a token? Name the five types of tokens in Python.

A token is the smallest individual unit in a Python program. The five types are keywords, identifiers, literals, operators and punctuators.

3. What is a keyword? Why are True and true treated differently?

A keyword is a reserved word with a predefined meaning and purpose, used only for that purpose. Python is case sensitive, so keywords must be written exactly as specified: only True is a keyword; true is an ordinary name.

4. What are soft keywords?

In Python 3.10 and later, some words are reserved only in particular situations. match, case and _ act as keywords in specific contexts, and can be used as identifiers elsewhere.

5. What are identifiers? State the rules for forming them.

Identifiers are user-defined names for program elements such as variables, functions, objects and classes. An identifier is a sequence of letters, digits and underscores that:

  • starts with a letter or an underscore;
  • contains no white space or special characters;
  • is not a keyword.

There is no limit on length, but names should be short and meaningful. Valid examples: count, avg_marks, FOR, _1stRank.

6. Choose the invalid identifiers and justify: Data_rec, Num#, 2ab, try, My File, _num1, Sum2Num, false, True, File.py
TokenValid?Reason
Data_recValidLetters and underscore only
Num#InvalidContains special character #
2abInvalidStarts with a digit
tryInvalidKeyword
My FileInvalidContains a space
_num1ValidStarts with underscore
Sum2NumValidLetters and digits, starts with a letter
falseValidKeyword is False; lowercase false is not reserved
TrueInvalidKeyword
File.pyInvalidContains a period (special character)
7. What is a literal? Name the kinds of literals in Python.

A literal is a token that indicates a constant value. Python supports string, numeric (integer, float, complex) and Boolean literals, the special literal None, and literal collections (list, tuple, dictionary, set).

8. What are string literals? How are multiline strings written?

A sequence of characters enclosed in single, double or triple quotes, e.g. "Computer Science", 'Python', '''#number2'''. Triple quotes can represent multiline strings:

"""Python makes coding simple!
Keep learning, keep growing."""
9. What are escape sequences? List five.

Special characters beginning with \ that represent non-graphic symbols or punctuation marks.

SequenceCharacter
\tTab
\nNew line
\'Single quote
\"Double quote
\\Backslash
10. Explain the numeric literals with examples.
  • Integer: positive or negative whole numbers; can be binary (0b1111), decimal (15), octal (0o17) or hexadecimal (0xF).
  • Float: real numbers with a fractional part, e.g. -3.14, 0.5.
  • Complex: numbers of the form a+bj, with real part a and imaginary part b, e.g. 5+3j, 2-5j.
11. What are Boolean literals and the special literal None?

Boolean literals are True and False, representing truth values; they are used for logical conditions and results of comparison and logical operations. None denotes nothing, no value, or absence of value.

12. List the literal collections and give an example of each.
CollectionDescriptionExample
ListComma-separated elements in square brackets; can be changed[25, "Python", 95.5, 'A+']
TupleComma-separated elements in round brackets; cannot be changed(23, "Computer Science", 'A', 35.8)
DictionaryUnordered key-value pairs in curly braces{1: 'one', 2: 'two', 3: 'three'}
SetUnordered elements in curly braces; no duplicates{'sat', 'sun', 20, 3.14}
13. Differentiate between ordered and unordered collections.

In an ordered collection, elements are stored in a specific sequence and each has a fixed position (index), so insertion order is preserved (list, tuple). In an unordered collection, elements have no fixed position, their arrangement may change, and items cannot be accessed by index (dictionary, set).

14. Fill the table using these literals: 12, 'Num#', '''2ab''', 25.6, -5, "123", '+=', '0', {1, 'Ardra', 95}, (2, "Niketh", 'Science'), {"roll":25, "name":"Sneha", "score":85}, ["Nived", 20, 'A']
TypeLiterals
String'Num#', '''2ab''', "123", '+='
Character (string of length 1)'0'
Integer12, -5
Float25.6
List["Nived", 20, 'A']
Tuple(2, "Niketh", 'Science')
Dictionary{"roll":25, "name":"Sneha", "score":85}
Set{1, 'Ardra', 95}

Python has no separate character type; a single character is a string of length 1.

15. What are operators and punctuators?

An operator is a symbol that tells the interpreter to perform a specific operation on operands (+, *, //, >, !=). Punctuators are special symbols that help organise the structure of programs, such as [ , @ { ).

5.3–5.4 Variables and data types

16. What is a variable? What three aspects of an object are associated with it?

A variable is an identifier that refers to an object (memory location) holding a value. In x = 3, x refers to an object for the integer 3. The three aspects are the identity (address of the memory location), the data type and the value.

17. Does Python require explicit declaration of variables? How does the type of a variable change?

No. Assigning a value creates an object with that value and the variable refers to it; the variable's type is the type of the object. Assigning a value of a different type changes the type:

num = 10        # int
msg = "Hello"   # str
num = 3.5       # now float
18. What is a data type? Give the Python class names of the main types.

A data type is a set of values together with the operations defined on them. Python treats data types as classes:

  • Numeric: int, float, complex
  • Sequence: str, list, tuple
  • Dictionary: dict
  • Boolean: bool
  • Set: set, frozenset
19. How can the data type of a value be found? What is the output?
a = 5
b = 5.0
c = 2+3j
s = "hello"
L = [1,2,3]
print(type(a)); print(type(b)); print(type(c)); print(type(s)); print(type(L))

The built-in function type() gives the data type.

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'list'>
20. Identify the data types of (a) n=25 (b) PI=3.14 (c) name="Guido" (d) flag=True

(a) int (b) float (c) str (d) bool

21. Identify the data types: (a) 234 (b) 0.54 (c) "True" (d) False (e) (1, 45.65, "Raihan") (f) {3, "Neelima", 'F'} (g) [5, "Joel", "M"]

(a) int (b) float (c) str (because it is in quotes) (d) bool (e) tuple (f) set (g) list

22. Differentiate between mutable and immutable data types. Which types belong to each?

Mutable types allow modification of their values after creation: list, dictionary, set. Immutable types cannot be changed once created: int, float, str, tuple (and bool, complex).

23. What happens in memory when an immutable variable is updated? Explain with num=10; temp=num; num=num*num.

Python does not change the existing object; it creates a new object with the updated value and makes the variable refer to it.

  • num = 10: num refers to an object holding 10.
  • temp = num: temp refers to the same object.
  • num = num*num: a new object holding 100 is created and num refers to it. temp still refers to the object holding 10.

5.5 Operators

24. What are operands? Differentiate unary and binary operators.

Operands are the data on which an operator acts; in 5 + 3, 5 and 3 are operands and + is the operator. Unary operators need one operand (unary +, unary –, not); binary operators need two (+, *, >, and).

25. List the categories of operators in Python.

Arithmetic, relational, logical, assignment, identity and membership operators.

26. Explain the arithmetic operators with examples (num1 = 5, num2 = 2).
OperatorOperationExampleResult
+Addition; string concatenationnum1 + num2; "Hello" + "Guys"7; HelloGuys
–Subtractionnum1 - num23
*Multiplication; string repetitionnum1 * num2; "Hello" * 210; HelloHello
/Division (always float)num1 / num22.5
%Modulus (remainder)num1 % num21
//Floor division (rounds down)num1 // num2; 5.0 // 2.02; 2.0
**Exponent (power)num1 ** num225
27. How does the data type of operands affect the result of an arithmetic operation?
  • int and int give int (except /).
  • float and float give float.
  • int and float: the int is promoted to float, so the result is float (7 + 2.5 gives 9.5).
  • The / operator always returns a float.
28. Prepare a table like Table 5.3 including complex as an operand.
Operand 1Operand 2ResultExample
intcomplexcomplex7 + (2+3j) gives (9+3j)
complexintcomplex(2+3j) + 7 gives (9+3j)
floatcomplexcomplex2.5 + (2+3j) gives (4.5+3j)
complexfloatcomplex(2+3j) + 2.5 gives (4.5+3j)
complexcomplexcomplex(2+3j) + (1+1j) gives (3+4j)

Whenever a complex operand is involved, the result is complex.

29. What are unary plus and unary minus?

When + and – are used with a single operand they only indicate that the number is positive or negative, e.g. -5.

30. Explain the relational operators. What is the result type?

Relational operators compare two operands and always give a Boolean value (True or False). They are: == (equal to), != (not equal to), >, >=, <, <=.

>>> 5 == 2
False
>>> "Good" != "Bad"
True
>>> 5 >= 5
True
31. How are strings compared? Why is "Good" < "good" True? What happens with 3 < "3"?

Strings are compared by alphabetical order based on Unicode values. Uppercase letters have smaller Unicode values than lowercase ones, so "Good" < "good" is True.

Comparing a number with a string using <, >, <= or >= gives a TypeError. Where types are compatible, Python converts implicitly: 3.0 < 4 is True because 4 is converted to float.

32. Explain the logical operators with examples.

The operators are and, or (binary) and not (unary).

  • and: if the first operand is True the result is the second operand; if False the result is the first operand.
  • or: if the first operand is True the result is the first operand; if False the result is the second operand.
  • not: reverses the logical state.
>>> (15>12) and (15>5)
True
>>> (15<12) or (15>0)
True
>>> not False
True
33. Which values are treated as False? Evaluate 3 and 0 and "Hello" or "".

None, False, 0, empty string "", empty tuple (), empty list [], empty dictionary {} and other empty values are False; all other values are True.

3 and 0 gives 0 (first operand is True, so the second is returned). "Hello" or "" gives "Hello" (first operand is True, so it is returned).

34. What is the assignment operator? How does str1 = str1 + ' friends' work?

The assignment operator = makes the variable on the left refer to the object holding the value of the expression on the right. For str1 = 'hello' then str1 = str1 + ' friends', a new object 'hello friends' is created (strings are immutable) and str1 now refers to it. The old object has no reference.

35. List the compound assignment operators.
CompoundEquivalent
a += ba = a + b
a -= ba = a - b
a *= ba = a * b
a /= ba = a / b
a %= ba = a % b
a //= ba = a // b
a **= ba = a ** b
36. What will be the value of ans if ans=25 initially? (a) ans += 10 (b) ans //= 10 (c) ans %= 10 (d) ans -= ans*5

(a) 25 + 10 = 35
(b) 25 // 10 = 2
(c) 25 % 10 = 5
(d) 25 – (25 × 5) = 25 – 125 = –100

37. Explain the identity operators.

is is True if both variables refer to the same memory object; is not is True if they do not. They can also check the type of a variable.

>>> num1 = 5
>>> num2 = num1
>>> num1 is num2
True
>>> type(num1) is int
True
>>> num1 is not num2
False

var1 is var2 is True if id(var1) == id(var2), where id() gives the memory address of an object.

38. Explain the membership operators.

in is True if a value is found in the sequence (string, list, tuple); not in is True if it is not found.

>>> a = [10, 15, 100]
>>> 10 in a
True
>>> '15' in a
False
>>> '15' not in a
True

'15' is a string, so it is not found in a list of integers.

5.6 Expressions

39. What is an expression? Is an operator alone an expression?

An expression is a combination of operands (variables, constants, values) and operators that is evaluated to produce a result (return value), e.g. 5+3, x/y, a>b. A value or a standalone variable is also an expression, but an operator alone is not.

40. What is operator precedence? Give the order of precedence.

When an expression has different operators, the one with higher precedence is evaluated first. Operators of equal precedence are evaluated left to right. Parentheses are evaluated first.

OrderOperators
1**
2unary + -
3* / % //
4+ -
5relational < <= > >= == !=
6assignment and compound assignment
7is, is not
8in, not in
9not
10and
11or
41. Evaluate 5 + 7 – 2 * 4 and 5 + (7 – 2) * 4 step by step.

5 + 7 – 2 * 4: 2 * 4 = 8; 5 + 7 = 12; 12 – 8 = 4.

5 + (7 – 2) * 4: 7 – 2 = 5; 5 * 4 = 20; 5 + 20 = 25.

42. Find the value and type of each expression, given a=5, b=10, c=2.5, d="hello".
ExpressionValueType
(i) a / b0.5float
(ii) a + b - c12.5float
(iii) d * 3'hellohellohello'str
(iv) d + "friends"'hellofriends'str
(v) b // 33int
(vi) (a + b) % 21int
(vii) a ** 3 - b * c100.0 (125 – 25.0)float
(viii) a > bFalsebool
(ix) (a>b) and (b>c)Falsebool
(x) (a%10) > 0True (5 > 0)bool
(xi) (a/b) > cFalse (0.5 > 2.5)bool
(xii) ('h'+'a') * 3'hahaha'str
(xiii) "Hi" < "Hello"False ('i' comes after 'e')bool
(xiv) 'A' == 'a'Falsebool
(xv) a * (b - c) / 218.75 (5 × 7.5 / 2)float

5.7 Statements

43. What is a statement? Explain the assignment statement, including multiple assignment.

A statement is an instruction given to the computer to perform a task such as input, output, assignment or control of program flow. Examples of assignment: num = 125, msg = 'Hello World', num = num / 10.

  • a = b = c = 10 assigns the same value; all three refer to the same object.
  • a, b, c = 10, 15, 20 assigns values in order: a to 10, b to 15, c to 20. Expressions may be used instead of literals.

After a = b = c = 10, executing c += 1 makes c refer to a new object (11) while a and b still refer to 10.

44. Explain the input() function. What type of data does it return?

Syntax: var = input([prompt]). It displays the optional prompt, waits for the user to type data and press Enter, and returns the data. It always returns a string, even if a number is typed. To use the input as a number, convert it with int() or float():

name = input("Enter your name: ")
num1 = int(input("Enter first number: "))
45. Explain the print() function with the sep and end parameters.

Syntax: print(value [, …, sep = char1, end = char2]). It sends text, numbers or results to the screen.

  • sep: separator between values; default is a space.
  • end: string added after the last value; default is a new line.
>>> print("Hello", "friends")
Hello friends
>>> print("Hello" + "friends")
Hellofriends
>>> print(10, 20, 30, sep=' ', end='.')
10 20 30.
46. What are comments? How are single-line and multi-line comments written?

Comments are lines that the interpreter ignores; they explain the code and make it readable, and are part of documentation. A single-line comment begins with #. A multi-line comment is written within a pair of triple quotes (""" or ''').

# accept two numbers
"""This is a
multi-line comment"""

5.8 Python programs

47. What is sequential flow?

Executing instructions one by one in the order in which they appear.

48. Write an algorithm and program to accept a name and print a greeting.

Step 1: Start
Step 2: Input Name
Step 3: Print "Hello", Name, "Welcome"
Step 4: Stop

name = input("Enter your name: ")
print("Hello", name, "Welcome!")

Flowchart: Start → Input Name → Print "Hello", Name, "Welcome" → Stop.

49. Write an algorithm and program to find the sum of two numbers. Why is int() used?

Step 1: Start
Step 2: Input A, B
Step 3: S = A + B
Step 4: Print S
Step 5: Stop

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
s = int(num1) + int(num2)
print("Sum = ", s)

input() returns strings. Without int(), + would concatenate ("12" + "43" gives "1243"). int() converts them to integers so they can be added (12 + 43 = 55). Use float() for decimals.

50. Sum and average of three numbers.

Step 1: Start
Step 2: Input A, B, C
Step 3: SUM = A + B + C
Step 4: AVG = SUM / 3
Step 5: Print SUM, AVG
Step 6: Stop

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
total = a + b + c
avg = total / 3
print("Sum =", total)
print("Average =", avg)
51. Area and perimeter of a rectangle.

Step 1: Start
Step 2: Input L, B
Step 3: AREA = L × B
Step 4: PERI = 2 × (L + B)
Step 5: Print AREA, PERI
Step 6: Stop

l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
print("Area =", l * b)
print("Perimeter =", 2 * (l + b))
52. Input the diameter of a circle and find its area and perimeter.

Step 1: Start
Step 2: Input D
Step 3: R = D / 2
Step 4: AREA = 3.14 × R × R
Step 5: PERI = 3.14 × D
Step 6: Print AREA, PERI
Step 7: Stop

d = float(input("Enter diameter: "))
r = d / 2
print("Area =", 3.14 * r * r)
print("Perimeter =", 3.14 * d)

For d = 12: area = 113.04, perimeter = 37.68.

53. Convert an amount in paise into rupees and paise (575 paise gives Rs. 5 Ps. 75).

Step 1: Start
Step 2: Input P
Step 3: R = P // 100
Step 4: PS = P % 100
Step 5: Print R, PS
Step 6: Stop

p = int(input("Enter amount in paise: "))
rupees = p // 100
paise = p % 100
print("Rs.", rupees, "Ps.", paise)

Floor division gives the rupees and modulus gives the remaining paise. For 575: Rs. 5 Ps. 75.

54. Convert seconds into Hr : Min : Sec format (7700 seconds gives 2 Hrs : 8 Mins : 20 Secs).

Step 1: Start
Step 2: Input S
Step 3: H = S // 3600
Step 4: R = S % 3600
Step 5: M = R // 60
Step 6: SEC = R % 60
Step 7: Print H, M, SEC
Step 8: Stop

s = int(input("Enter time in seconds: "))
h = s // 3600
r = s % 3600
m = r // 60
sec = r % 60
print(h, "Hrs :", m, "Mins :", sec, "Secs")

For 7700: h = 2, r = 500, m = 8, sec = 20.

55. Swap two numbers using a third variable.

Step 1: Start
Step 2: Input A, B
Step 3: T = A
Step 4: A = B
Step 5: B = T
Step 6: Print A, B
Step 7: Stop

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
t = a
a = b
b = t
print("After swapping: a =", a, "b =", b)
56. Swap two numbers without using a third variable.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a = a + b
b = a - b
a = a - b
print("After swapping: a =", a, "b =", b)

Example: a = 4, b = 7 → a = 11 → b = 11 – 7 = 4 → a = 11 – 4 = 7. Python also allows the multiple assignment a, b = b, a.

57. Convert Celsius to Fahrenheit and find the boiling and freezing points of water on the Fahrenheit scale.

Step 1: Start
Step 2: Input C
Step 3: F = C × 9/5 + 32
Step 4: Print F
Step 5: Stop

c = float(input("Enter temperature in Celsius: "))
f = c * 9 / 5 + 32
print("Fahrenheit =", f)

Boiling point: 100 °C → 212 °F. Freezing point: 0 °C → 32 °F.