4. Elements of Python: Questions and Answers

Select a question to reveal its answer.

Part AMultiple Choice Questions

1Who developed the Python programming language?
  • a) Dennis Ritchie
  • b) Guido van Rossum
  • c) James Gosling
  • d) Bjarne Stroustrup
Answer

b) Guido van Rossum

Python was created by Guido van Rossum in 1991.

2Python is a(n) ______ language.
  • a) compiled, statically typed
  • b) interpreted, dynamically typed
  • c) assembly
  • d) machine
Answer

b) interpreted, dynamically typed

Python code is executed line by line.

3The symbol >>> in the Python shell is called:
  • a) Output symbol
  • b) Python prompt
  • c) Comment symbol
  • d) Error indicator
Answer

b) Python prompt

It shows that Python is ready to accept commands.

4REPL stands for:
  • a) Read-Eval-Print-Loop
  • b) Run-Execute-Print-Loop
  • c) Read-Execute-Process-Loop
  • d) Run-Eval-Process-Line
Answer

a) Read-Eval-Print-Loop

5IDLE stands for:
  • a) Integrated Development and Learning Environment
  • b) Interactive Data and Language Editor
  • c) Integrated Debugging and Linking Environment
  • d) Internal Development Language Editor
Answer

a) Integrated Development and Learning Environment

6Python programs are saved with the extension:
  • a) .pt
  • b) .python
  • c) .py
  • d) .pyt
Answer

c) .py

7In IDLE, a program is run from the menu using:
  • a) Run > Run Module (F5)
  • b) File > Save (F2)
  • c) Edit > Run (F1)
  • d) Shell > Run (F10)
Answer

a) Run > Run Module (F5)

8Single-line comments in Python begin with:
  • a) //
  • b) #
  • c) /*
  • d) --
Answer

b) #

9A string enclosed in triple quotes (''' or """) that is not assigned to a variable can serve as a:
  • a) single-line comment
  • b) multi-line comment
  • c) keyword
  • d) identifier
Answer

b) multi-line comment

Python has no separate multi-line comment symbol.

10Which of these is NOT a Python keyword?
  • a) None
  • b) True
  • c) print
  • d) lambda
Answer

c) print

print is a built-in function, not a keyword. All keywords except None, True and False are in lowercase.

11Which of these is a valid identifier?
  • a) 2A
  • b) user@name
  • c) total value
  • d) basic_pay
Answer

d) basic_pay

2A starts with a digit, user@name has a special character and total value has a space.

12The function input() always returns a value of type:
  • a) int
  • b) float
  • c) string
  • d) Boolean
Answer

c) string

Use int() or float() to convert it to a number.

13Which of these is a mutable data type?
  • a) String
  • b) Tuple
  • c) List
  • d) Boolean
Answer

c) List

List, Set and Dictionary are mutable; numeric, string, Boolean and tuple are immutable.

14Which of these collections is unordered?
  • a) List
  • b) Tuple
  • c) Set
  • d) String
Answer

c) Set

Elements of a set have no defined order and cannot be accessed by index.

15Which data type stores data as key-value pairs?
  • a) List
  • b) Set
  • c) Tuple
  • d) Dictionary
Answer

d) Dictionary

16The operator // is used for:
  • a) Division
  • b) Modulus
  • c) Floor division
  • d) Exponentiation
Answer

c) Floor division

5 // 2 = 2 and -5 // 2 = -3.

17The value of 5 % 2 in Python is:
  • a) 2
  • b) 1
  • c) 2.5
  • d) 0
Answer

b) 1

% gives the remainder after division.

18The value of 'Hi' * 3 is:
  • a) 'Hi3'
  • b) 'HiHiHi'
  • c) Error
  • d) 'Hi Hi Hi'
Answer

b) 'HiHiHi'

A string can be multiplied by an integer only.

19Which operator has the highest precedence?
  • a) Parentheses ( )
  • b) **
  • c) *
  • d) +
Answer

a) Parentheses ( )

20Which operator is used to check whether two variables refer to the same object in memory?
  • a) ==
  • b) in
  • c) is
  • d) and
Answer

c) is

Part BFill in the Blanks

1The Python programming language was developed by ______.
Answer

Guido van Rossum (in 1991).

2The Python interpreter is also called the Python ______.
Answer

Shell.

3The symbol >>> is called the Python ______.
Answer

Prompt.

4In ______ mode, statements are executed immediately but cannot be saved for future use.
Answer

Interactive mode.

5In scripting mode, a program is saved as a file with ______ extension.
Answer

.py

6Google Colab, Replit and Kaggle Notebooks are examples of ______ platforms for Python.
Answer

Online.

7Single-line comments in Python begin with ______.
Answer

# (hash symbol).

8A ______ is a reserved word that has a special meaning in Python.
Answer

Keyword.

9A name used to define a variable, function, class or module is called an ______.
Answer

Identifier.

10Identifiers in Python are ______, i.e. Grade, grade and GRADE are different.
Answer

Case-sensitive.

11A variable whose data type changes automatically when it is reassigned is called ______ typed.
Answer

Dynamically typed.

12The function ______ is used to find the data type of a variable.
Answer

type().

13Python has no character data type; a single character is a ______ of length one.
Answer

String.

14An object whose value cannot be changed after creation is called ______.
Answer

Immutable.

15{} creates an empty ______ and set() creates an empty ______.
Answer

Dictionary; set.

16The operator ** is used for ______.
Answer

Exponentiation (power).

17The ______ operators in and not in are used to check whether a value is found in a sequence.
Answer

Membership.

18The function used to display output is ______.
Answer

print().

Part CMatch the Following

1Match the data types with examples.
Column AColumn B
1. inta) 35.5
2. floatb) 27
3. strc) [10, 20, 30]
4. listd) "Delhi"
5. dicte) {'Biju': 65}
Answer
Data typeExample
1. intb) 27
2. floata) 35.5
3. strd) "Delhi"
4. listc) [10, 20, 30]
5. dicte) {'Biju': 65}
2Match the operators with their names.
Column AColumn B
1. //a) Modulus
2. %b) Floor division
3. **c) Not equal
4. !=d) Exponentiation
Answer
OperatorName
1. //b) Floor division
2. %a) Modulus
3. **d) Exponentiation
4. !=c) Not equal
3Match the expressions with their results.
Column AColumn B
1. 5 / 2a) 25
2. 5 // 2b) 2.5
3. 5 % 2c) 2
4. 5 ** 2d) 1
Answer
ExpressionResult
1. 5 / 2b) 2.5
2. 5 // 2c) 2
3. 5 % 2d) 1
4. 5 ** 2a) 25
4Match the data types with their nature.
Column AColumn B
1. Lista) Immutable, ordered
2. Tupleb) Mutable, unordered, unique elements
3. Setc) Mutable, ordered
4. Dictionaryd) Mutable, key-value pairs
Answer
Data typeNature
1. Listc) Mutable, ordered
2. Tuplea) Immutable, ordered
3. Setb) Mutable, unordered, unique elements
4. Dictionaryd) Mutable, key-value pairs
5Match the modes of Python execution with their descriptions.
Column AColumn B
1. Interactive modea) Runs in a web browser, no installation needed
2. Scripting modeb) Statements executed immediately in the shell
3. Online platform modec) Program with many statements saved as a .py file
Answer
ModeDescription
1. Interactive modeb) Statements executed immediately in the shell
2. Scripting modec) Program with many statements saved as a .py file
3. Online platform modea) Runs in a web browser, no installation needed

Part DShort Answer Questions

1Define the Python programming language. Mention any two features of Python.
Answer

Python is an interpreted, dynamically-typed, easy-to-learn programming language used worldwide by beginners and experts. It was created by Guido van Rossum in 1991. Features: it is free and open-source; it is portable and platform-independent (runs on Windows, macOS and Linux); it supports procedural, object-oriented and functional programming; and code is executed line by line.

2What are the uses of Python?
Answer

Python is used for web development, game development, data science and analysis, artificial intelligence, Internet of Things (IoT), cybersecurity, machine learning and scientific computing.

3How can Python be installed?
Answer

Python is free and can be installed on Windows, macOS and Linux. The latest version can be downloaded from the official website https://www.python.org. The package includes the Python interpreter and a basic code editor.

4What are the three ways to write and run Python programs?
Answer
  1. Interactive mode
  2. Scripting mode
  3. Online platform mode
5What is interactive mode in Python? Write one advantage of it.
Answer

The Python shell is an interactive environment where code is executed immediately after pressing Enter (REPL: Read-Eval-Print-Loop). The prompt >>> shows Python is ready. Advantage: immediate feedback, so it is good for testing single-line statements. Statements cannot be saved for future use.

6What is scripting mode? How is it different from interactive mode?
Answer
Interactive modeScripting mode
One statement at a time, executed immediatelyMany statements written together as a program
Statements cannot be savedSaved as a file with .py extension
Used for testing single-line statementsUsed to write and run complete programs (File > New File, then Run > Run Module / F5)
7What is the use of IDLE?
Answer

IDLE (Integrated Development and Learning Environment) is Python's integrated environment containing a built-in editor, debugger and interpreter, so programs can be written, saved and run in one place. Other popular IDEs/editors are Geany, PyCharm, Jupyter Notebook, Thonny, VS Code and Spyder.

8What is online platform mode? Give its advantages and limitations.
Answer

Python code is written and executed in a web-based interface with no local installation. Examples: Google Colab, Replit, Kaggle Notebooks, Deepnote, Binder.

AdvantagesLimitations
No installation requiredInternet connection required
Program is written in the browserLimited file handling
Output is displayed instantlyNot suitable for large projects
Works on any operating system
9What are comments in Python? Why are they used?
Answer

Comments are notes written within the program code to explain it, making it easier for programmers to read and understand. They are used for internal documentation. The Python interpreter completely ignores them during execution.

10What are the two types of comments in Python?
Answer
  • Single-line comment: begins with # and everything after it on that line is a comment. Example: # Simple program
  • Multi-line comment: a string in triple single quotes (''') or triple double quotes (""") not assigned to a variable. Python has no separate multi-line comment symbol.
11What are Python keywords? Give any four examples.
Answer

A keyword is a reserved word with a special meaning in Python, used to define the syntax and structure of a program. All keywords except None, True and False are in lowercase. Examples: if, else, while, for, def, class, import, return.

12Define identifiers. Write rules for naming identifiers.
Answer

An identifier is a name used to define a variable, function, class or module.

  • Only letters (A-Z, a-z), digits (0-9) or underscore are allowed.
  • Must not start with a digit.
  • Python keywords cannot be used.
  • Whitespaces and special characters are not allowed.
  • Identifiers are case-sensitive (Grade, grade and GRADE are different).
13Give some valid and invalid identifiers.
Answer
ValidInvalidReason
totalamountuser@namecontains special character @
score1returnPython keyword
valuetotal valuecontains whitespace
basic_pay2Astarts with a digit
14What is a variable in Python?
Answer

A variable is a symbolic name used to store data that may change value during program execution. It can store integers, floats, strings, lists, dictionaries, etc. A variable is created by assigning a value with the assignment operator (=). Example: rollno=12, name="Arun", price=85.5.

15Explain dynamic typing.
Answer

Python variables are dynamically typed: there is no need to declare them before use, and the data type changes automatically when the variable is reassigned to a different type of value. Example: n=10 (integer), then n="Hello" (string), then n=True (Boolean).

16Define data type. Name any four built-in Python data types.
Answer

A data type is a classification of data values that specifies what kind of value a variable can hold and which operations can be performed on it. Four built-in types: int, float, str, list (others: complex, bool, tuple, set, dict, NoneType).

17What are the three numeric data types in Python?
Answer
  • Integer (int): positive or negative whole numbers without a decimal part, e.g. 27, -36, 412, 0.
  • Float: numbers with a fractional part, e.g. 3.5, 0.0, -12.75.
  • Complex: numbers of the form a + bj, where a is the real part and b the imaginary part. complex(2, 5) gives (2+5j).
18What is the Boolean data type?
Answer

A Boolean value is one of two logical values, True or False. It belongs to the class bool. Example: a=True; type(a) gives <class 'bool'>.

19What is a sequence? Name the sequence types in Python.
Answer

A sequence is an ordered group of values arranged one after another; each value has a fixed position (index) and is accessed using it. The three sequence types are string, list and tuple.

20Explain strings in Python.
Answer

A string is a sequence of Unicode characters created using single or double quotes. There is no character data type; a single character is a string of length one. Characters are accessed by index, which starts from 0; a negative index counts from the end. Strings belong to the class str and are immutable. Example: s1="Programming": s1[0] is P, s1[4] is r, s1[-1] is g.

21Explain lists in Python.
Answer

A list is an ordered sequence of items separated by commas and enclosed in square brackets [ ]. Items are accessed by index, and lists are mutable. Example: x=[10, "Delhi", 65.5, 'A2', 40]; x[0] is 10, x[3] and x[-2] are both 'A2', x[-1] is 40.

22What is a tuple? How does it differ from a list?
Answer

A tuple is an ordered collection of objects of any data type, separated by commas and enclosed in parentheses ( ). The only difference from a list is that tuples are immutable. Example: t1=(40, "Computer", 65.5, 'Phone'); t1[0] is 40 and t1[-1] is Phone.

23What is None in Python?
Answer

None represents the absence of a value; it indicates nothing, null or an empty result. It belongs to the class NoneType. Example: x=None; print(x) displays None.

24What is a set? Mention any two characteristics of a set.
Answer

A set is a collection of unordered, unique elements, enclosed in braces { } and separated by commas. Characteristics: elements have no defined order, so they cannot be accessed by index; duplicate elements are eliminated; sets are mutable; mathematical set operations like union, intersection and difference can be performed. Example: {10,20,30,20} gives {10, 20, 30}. set() creates an empty set.

25What is a dictionary in Python?
Answer

A dictionary stores data as key-value pairs inside braces { } and allows efficient lookup or modification of values using their keys. Values can be of any data type. Key-value pairs can be added and removed. It belongs to class dict and is mutable. {} creates an empty dictionary.

mark={'Diya': 70, 'Biju': 65, 'Thomas': 58}
print(mark['Biju'])      # 65
mark['Fathima']=75       # add a key-value pair
del mark['Diya']         # remove a key-value pair
26Differentiate between mutable and immutable objects.
Answer
Mutable objectsImmutable objects
Value can be changed after creationValue cannot be changed after creation
List, Set, DictionaryNumeric, String, Boolean, Tuple
27Differentiate between a list and a tuple.
Answer
ListTuple
Enclosed in square brackets [ ]Enclosed in parentheses ( )
MutableImmutable
Example: [10, 20, 30]Example: (10, 20, 30)
28Differentiate between a set and a dictionary.
Answer
SetDictionary
Collection of unordered, unique elementsCollection of key-value pairs
Enclosed in { }, elements onlyEnclosed in { }, as key: value
Elements cannot be accessed by indexValues accessed by their keys
set() creates an empty set{} creates an empty dictionary
29What is an operator? List the types of Python operators.
Answer

Operators are special symbols that carry out operations on values or variables. Types: arithmetic, assignment, relational, logical, identity and membership operators.

30Explain arithmetic operators with examples.
Answer
OperatorNameExample
+Addition / concatenation5 + 2 = 7; 'New' + 'Delhi' = 'NewDelhi'
-Subtraction5 - 2 = 3
*Multiplication / string repetition5 * 2 = 10; 'Hi' * 3 = 'HiHiHi'
/Division5 / 2 = 2.5
//Floor division5 // 2 = 2; -5 // 2 = -3
%Modulus (remainder)5 % 2 = 1
**Exponentiation5 ** 2 = 25
31Explain assignment operators with examples.
Answer
OperatorExampleSame asResult (a=10)
=a=1010
+=a+=5a=a+515
-=a-=5a=a-55
*=a*=5a=a*550
/=a/=5a=a/52.0
//=a//=5a=a//52
%=a%=5a=a%50
**=a**=5a=a**5100000
32Explain relational operators with examples (a=8, b=5).
Answer
OperatorNameExampleResult
==Equala==bFalse
!=Not equala!=bTrue
<Less thana<bFalse
>Greater thana>bTrue
<=Less than or equala<=bFalse
>=Greater than or equala>=bTrue
33Describe logical operators in detail with examples.
Answer

Logical operators combine one or more conditions and return True or False. Assume a=20, b=10.

OperatorDescriptionExampleResult
andTrue only if both conditions are Truea > b and b < aTrue
anda < b and b < aFalse
orTrue if at least one condition is Truea > b or b > aTrue
ora < b or b > aFalse
notReverses the resultnot (a < b)True
notnot (b < a)False
34Explain identity operators with examples.
Answer

Identity operators check whether two variables refer to the same object in memory: is and is not.

x=[1,2,3]
y=[1,2,3]
print(x is y)       # False, different objects
z=x
print(x is z)       # True, same object
print(x is not y)   # True
35Explain membership operators with examples.
Answer

Membership operators check whether a value or variable is found in a sequence: in and not in.

a=[10,20,30]
print(10 in a)         # True
print(50 in a)         # False
text='Python'
print('P' not in text) # False
print('k' not in text) # True
36What is an expression? What is operator precedence?
Answer

An expression is a combination of values, variables and operators that can be evaluated to produce another value. Operator precedence decides which operation is performed first when an expression has more than one operator.

37Write the precedence of operators in Python (highest to lowest).
Answer
LevelOperator(s)Description
1( )Parentheses
2**Exponentiation
3+, -Unary plus, unary minus
4*, /, //, %Multiplication, division, floor division, modulus
5+, -Addition, subtraction
6==, !=, >, <, >=, <=, is, is not, in, not inRelational, identity and membership
7notLogical NOT
8andLogical AND
9orLogical OR
38Evaluate: 40 + 50 * 3, (30 - 20) * 5 and 60 / 5 - (6 + 2).
Answer
40 + 50 * 3          # * before +
= 40 + 150 = 190

(30 - 20) * 5        # parentheses first
= 10 * 5 = 50

60 / 5 - (6 + 2)     # parentheses first, then /, then -
= 60 / 5 - 8 = 12.0 - 8 = 4.0
39Explain the input() function with syntax and an example.
Answer

input() receives data from the keyboard and always returns a string value. Syntax: variable=input("Prompt message").

name=input("Enter your name : ")
print("Entered Name : " + name)

Output

Enter your name : Akhil
Entered Name : Akhil
40Explain the print() function with syntax and an example.
Answer

print() displays strings, numbers or values of variables on the screen. Syntax: print("Display message").

print("Welcome to Python")
x=10
print("Value of x is", x)
41Why must int() be used with input() when adding two numbers?
Answer

input() always returns a string, so '10' + '20' would join the strings to give '1020'. int() converts the input to an integer so that the numbers are added: int('10') + int('20') = 30.

Part EPrograms and Output Questions

1Write a Python program to find the sum of two numbers.
Answer
num1=int(input("Enter first number : "))
num2=int(input("Enter second number : "))
total=num1 + num2
print("Total :",total)

Output

Enter first number : 10
Enter second number : 20
Total : 30
2Write a Python program to calculate the average of three numbers.
Answer
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
c=int(input("Enter third number : "))
average=(a + b + c) / 3
print("Average :",average)

Output

Enter first number : 60
Enter second number : 70
Enter third number : 80
Average : 70.0
3Write a Python program to demonstrate arithmetic operators.
Answer
a=10
b=3
print("Addition       :", a + b)
print("Subtraction    :", a - b)
print("Multiplication :", a * b)
print("Division       :", a / b)
print("Floor division :", a // b)
print("Modulus        :", a % b)
print("Exponent       :", a ** b)

Output

Addition       : 13
Subtraction    : 7
Multiplication : 30
Division       : 3.3333333333333335
Floor division : 3
Modulus        : 1
Exponent       : 1000
4Write a Python program to find the area and perimeter of a rectangle.
Answer
length=float(input("Enter length : "))
breadth=float(input("Enter breadth : "))
area=length * breadth
perimeter=2 * (length + breadth)
print("Area :",area)
print("Perimeter :",perimeter)

Output

Enter length : 5
Enter breadth : 3
Area : 15.0
Perimeter : 16.0
5Write a Python program to calculate simple interest.
Answer
p=float(input("Enter principal : "))
r=float(input("Enter rate : "))
t=float(input("Enter time in years : "))
si=p * r * t / 100
print("Simple interest :",si)

Output

Enter principal : 1000
Enter rate : 5
Enter time in years : 2
Simple interest : 100.0
6Write a Python program to swap two numbers.
Answer
a=int(input("Enter a : "))
b=int(input("Enter b : "))
temp=a
a=b
b=temp
print("After swapping: a =",a,", b =",b)

Output

Enter a : 4
Enter b : 9
After swapping: a = 9 , b = 4
7Write a Python program to read a name and mark and display them using a dictionary.
Answer
name=input("Enter name : ")
mark=int(input("Enter mark : "))
student={name: mark}
print(student)
student["Biju"]=65
print(student)

Output

Enter name : Diya
Enter mark : 70
{'Diya': 70}
{'Diya': 70, 'Biju': 65}
8Write the output of the following code: a=5, b=2, print(a % b).
Answer
a=5
b=2
print(a % b)

Output

1

5 divided by 2 leaves remainder 1.

9Write the output of the following code: x="Hello", print(x * 3).
Answer
x="Hello"
print(x * 3)

Output

HelloHelloHello

A string multiplied by an integer is repeated that many times.

10Write the output of the following code: print(10 > 5 and 5 < 3).
Answer
print(10 > 5 and 5 < 3)

Output

False

10 > 5 is True and 5 < 3 is False. 'and' gives True only if both are True, so the result is False. (In the textbook it is printed without spaces as 10>5and5<3; write spaces in a real program.)

11Write the output of the following code: fruits=["apple","banana","cherry"], print("banana" in fruits).
Answer
fruits=["apple","banana","cherry"]
print("banana" in fruits)

Output

True

'banana' is found in the list, so the membership operator 'in' gives True.

12Write the output of the following code: a=10, b=a, print(a is b).
Answer
a=10
b=a
print(a is b)

Output

True

b=a makes both names refer to the same object, so 'is' gives True.

Part FIdentify the Errors

1Identify the errors in the following code:
name=input(Enter your name)
print("Hello" name)
Answer
  • Prompt message in input() is not in quotes. It must be a string: input("Enter your name").
  • print("Hello" name) has no operator between the two items. Use + or a comma: print("Hello" + name) or print("Hello", name).
name=input("Enter your name : ")
print("Hello", name)
2Identify the errors in the following code:
x=10
y="20"
total= x + y
Answer

y="20" is a string, so x + y tries to add an integer and a string, which gives a TypeError. Convert the string to an integer, or store y as a number.

x=10
y=int("20")      # or y=20
total=x + y
print(total)       # 30
3Identify the errors in the following code:
1stNumber=50
second number=60
print(1stNumber + second number)
Answer
  • 1stNumber is invalid because an identifier must not start with a digit.
  • second number is invalid because identifiers cannot contain whitespace.
firstnumber=50
second_number=60
print(firstnumber + second_number)   # 110
4Identify the errors in the following code:
list=(10,20,30)
list[1]=50
print(list)
Answer
  • (10,20,30) with parentheses is a tuple, not a list. Tuples are immutable, so list[1]=50 gives a TypeError.
  • list is also the name of a built-in type; avoid using it as a variable name. Use square brackets to make a mutable list.
numbers=[10,20,30]
numbers[1]=50
print(numbers)   # [10, 50, 30]
5Identify the errors in the following code:
a=5
b=2
result=a** b
print("Result is "+result)
Answer

result is an integer (25) and "Result is " is a string; the + operator cannot join a string and an integer, so there is a TypeError. Use a comma or convert with str().

a=5
b=2
result=a ** b
print("Result is", result)        # Result is 25
print("Result is " + str(result)) # Result is 25

Part GLong Answer Questions

1Explain the three ways of writing and running Python programs.
Answer
  • Interactive mode: the Python shell (prompt >>>, REPL) executes each statement immediately and shows the output. Statements cannot be saved; used for testing single-line statements.
  • Scripting mode: multiple statements are written as a program and saved as a .py file (e.g. in IDLE: File > New File, then Run > Run Module / F5). The output appears in the shell.
  • Online platform mode: code is written and run in a web browser on platforms like Google Colab, Replit, Kaggle Notebooks, Deepnote and Binder. No installation needed, but internet is required, file handling is limited and it is not suitable for large projects.
2Explain the classification of Python data types with suitable examples.
Answer
CategoryTypesExample
Numericint, float, complex27, 35.5, complex(2,5) = (2+5j)
BooleanboolTrue, False
Sequencestr, list, tuple"Delhi", [10, 'A2', 40], (40, 'Phone')
NoneNoneTypex=None
Setset{10, 20, 30}
Mappingdict{'Diya': 70, 'Biju': 65}

Mutable types: list, set, dictionary. Immutable types: numeric, string, Boolean, tuple.

mark=60
print(type(mark))     # <class 'int'>
price=35.5
print(type(price))    # <class 'float'>
x=complex(2,5)
print(x)              # (2+5j)
3Explain Python identifiers and the rules for naming them.
Answer

An identifier is a name used to define a variable, function, class or module. It helps the programmer identify and differentiate entities, and should be short and meaningful.

  • Only letters (A-Z, a-z), digits (0-9) or underscore are allowed.
  • Must not start with a digit.
  • Python keywords cannot be used.
  • Whitespaces and special characters are not allowed.
  • Identifiers are case-sensitive.
ValidInvalidReason
totalamountuser@namespecial character @
score1returnPython keyword
valuetotal valuewhitespace
basic_pay2Astarts with a digit
4Explain arithmetic and assignment operators with examples.
Answer

Arithmetic operators perform basic mathematical operations; assignment operators assign or update the value of a variable.

OperatorNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division5 / 22.5
//Floor division5 // 22
%Modulus5 % 21
**Exponentiation5 ** 225
Assignment operatorMeaninga=10, then result
=assigna=10
+=a=a+515
-=a=a-55
*=a=a*550
/=a=a/52.0
//=a=a//52
%=a=a%50
**=a=a**5100000
5Describe logical operators in detail with examples.
Answer

Logical operators combine one or more conditions and return True or False. 'and' is True only if both conditions are True; 'or' is True if at least one is True; 'not' reverses the result. With a=20 and b=10:

ExpressionResult
a > b and b < aTrue
a < b and b < aFalse
a > b or b > aTrue
a < b or b > aFalse
not (a < b)True
not (b < a)False
6Explain sets and dictionary in Python with examples.
Answer
  • Set: unordered collection of unique elements in { }; mutable; no indexing; removes duplicates; supports union, intersection and difference.
  • Dictionary: key-value pairs in { }; values accessed by key; mutable; keys can be added or removed.
x={10,20,30,20}
print(x)              # {10, 20, 30}

mark={'Diya': 70, 'Biju': 65, 'Thomas': 58}
print(mark['Biju'])   # 65
mark['Fathima']=75    # add
del mark['Diya']      # remove
print(mark)           # {'Biju': 65, 'Thomas': 58, 'Fathima': 75}
7Explain the precedence of operators in Python with examples.
Answer

When an expression has more than one operator, precedence decides which is performed first. Level 1 is the highest priority: ( ), then **, unary +/-, then * / // %, then + -, then relational/identity/membership operators, then not, and, or.

40 + 50 * 3       # 190  (* before +)
(30 - 20) * 5     # 50   (parentheses first)
60 / 5 - (6 + 2)  # 4.0  (parentheses, then /, then -)
8Explain the input and output statements in Python with examples.
Answer
  • input(): receives data from the keyboard and always returns a string. Syntax: variable=input("Prompt message").
  • print(): displays strings, numbers or variable values. Syntax: print("Display message").

Example: program to add two integers (int() converts the strings to integers).

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

Output

Enter first number : 10
Enter second number : 20
Total : 30
9Explain comments, keywords and variables in Python.
Answer
  • Comments: notes ignored by the interpreter, used for internal documentation. # for single-line; triple quotes for multi-line.
  • Keywords: reserved words with special meaning (if, else, while, for, def, class, import...). All lowercase except None, True and False.
  • Variables: symbolic names that store data that may change. Created by assignment; dynamically typed, so the type changes when a new value is assigned.
# Simple program
n=10        # n is an integer
n="Hello"   # now n is a string
n=True      # now n is Boolean
print(n)