Python Placement Questions and Answers
Python Placement Questions for B.Tech Students
Python is a high-level, general-purpose programming language widely used in software development, automation, web development, data science, artificial intelligence, machine learning and scripting. For placement examinations and technical interviews, students should understand Python concepts as well as the logic behind common Python programs.
This tutorial covers important Python theoretical, conceptual, output-based and programming questions. The questions are useful for B.Tech examinations, practical examinations, viva preparation and Python placement interviews.
Each question is explained with suitable definitions, concepts, examples, Python programs, outputs and comparison tables wherever required.
Python Placement Questions – Index
| No. | Question |
|---|---|
| 1 | Explain the concept of OOPS. |
| 2 | Point out the difference between C and Python. |
| 3 | Explain the features of OOPS. |
| 4 | Differentiate between POP and OOPS. |
| 5 | Highlight the features of Python which make it special and different from other programming languages. |
| 6 | What will happen if we end our Python statement with a semicolon (;)? |
| 7 | Define Python variables. Give examples of int, float and string data types. |
| 8 |
What will be the output of the given Python program using
range() and string multiplication?
|
| 9 |
What will be the output of int = 7 and
print(int)? Explain the error, if any, and correct it if
necessary.
|
| 10 | Explain operator precedence and associativity and evaluate the given logical expression step by step. |
| 11 | Explain Python's built-in data structures with examples. |
| 12 | Differentiate between break, continue and pass with examples. Write a program to print prime numbers from 1 to 50. |
| 13 | Describe Python blocks and conditional statements. Write a program to grade students using elif. |
| 14 | Classify the different types of operators in Python and explain each with an example. |
| 15 | Elaborate type conversion and indentation with examples. |
| 16 | Discuss for loop with range, strings and lists. Write a program to sum the elements of a list having 10 elements. |
| 17 | Write a program to swap two numbers without using a temporary variable and find the first even number in a list. |
| 18 | Differentiate between keywords and identifiers and state the rules for naming variables. |
| 19 | Write programs to check whether a year is a leap year and to calculate the factorial of a number. |
Question 1: Explain the Concept of OOPS
Answer
OOPS stands for Object-Oriented Programming System. Object-Oriented Programming (OOP) is a programming approach in which a program is designed using classes and objects.
A class is a blueprint or template used to create objects. It defines the data and behaviour that objects created from the class can have.
An object is an instance of a class. It represents a particular entity and contains data and behaviour associated with that entity.
Basic OOP Structure
Blueprint
Instance
Data
Behaviour
Example of OOPS in Python
The following program creates a Student class containing
student information and a method for displaying that information.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print("Name:", self.name)
print("Marks:", self.marks)
student1 = Student("Rahul", 85)
student1.display()
Output
Name: Rahul Marks: 85
In this example, Student is the class and
student1 is an object of that class. The attributes
name and marks store information about the
student, while display() is a method that performs an
operation on that information.
Object-oriented programming helps divide a large program into manageable components. It also provides important concepts such as encapsulation, abstraction, inheritance and polymorphism.
Question 2: Point Out the Difference Between C and Python
Answer
C and Python are both general-purpose programming languages, but they differ considerably in syntax, typing, memory management, execution and their common areas of use.
C is widely used for system programming, embedded systems and applications requiring low-level control. Python is a high-level language commonly used for application development, automation, data science, artificial intelligence, machine learning and scripting.
Difference Between C and Python
| Feature | C | Python |
|---|---|---|
| Programming Level | Generally lower-level and systems-oriented. | High-level programming language. |
| Typing | Statically typed. | Dynamically typed. |
| Syntax | Uses braces and semicolons commonly. | Uses indentation to define blocks. |
| Memory Management | Dynamic memory can be explicitly allocated and released by the programmer. | Memory management is handled automatically by the Python runtime. |
| Pointers | Supports pointers and pointer arithmetic. | Does not provide C-style pointer arithmetic. |
| Execution | Usually compiled into native machine code. | Executed through a Python runtime. |
| Programming Approach | Primarily procedural. | Supports procedural, object-oriented and functional programming. |
| Applications | System software, embedded systems and operating-system components. | Web development, automation, AI/ML, data science and scripting. |
Example in C
#include <stdio.h>
int main()
{
int a = 10;
printf("%d", a);
return 0;
}
Equivalent Example in Python
a = 10 print(a)
Output
10
The Python program is shorter because Python provides a higher level of abstraction and does not require the additional syntax shown in the C program.
Question 3: Explain the Features of OOPS
Answer
Object-Oriented Programming provides concepts that help programmers organize data and behaviour into reusable software components. The four major features of OOP are encapsulation, abstraction, inheritance and polymorphism.
1. Encapsulation
Encapsulation means combining data and the methods that operate on that data within a class. It helps organize the internal state and behaviour of an object in one unit.
class Student:
def __init__(self, name):
self.name = name
def display(self):
print(self.name)
student = Student("Rahul")
student.display()
Output
Rahul
Here, the student's data and the method used to display that data are
defined within the Student class.
2. Abstraction
Abstraction means showing the necessary functionality while hiding unnecessary implementation details.
For example, when a programmer uses the print() function,
the programmer does not need to know the internal implementation used
by Python to display text on the screen.
3. Inheritance
Inheritance allows one class to derive functionality from another class. The existing functionality can then be reused or extended.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.sound()
dog.bark()
Output
Animal makes a sound Dog barks
The Dog class inherits the sound() method from
the Animal class.
4. Polymorphism
Polymorphism means "many forms". In object-oriented programming, the same method or interface can produce different behaviour depending on the object on which it is used.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output
Bark Meow
Both classes provide a method named sound(), but each class
implements the method differently. Therefore, the same method call
produces different behaviour for different objects.
Summary of OOP Features
| Feature | Meaning |
|---|---|
| Encapsulation | Combining data and related methods within a class. |
| Abstraction | Hiding unnecessary implementation details and exposing essential functionality. |
| Inheritance | Reusing and extending functionality from another class. |
| Polymorphism | Allowing a common interface to behave differently for different objects. |
Question 4: Differentiate Between POP and OOPS
Answer
POP stands for Procedure-Oriented Programming, whereas OOPS refers to Object-Oriented Programming. Both are approaches used to design computer programs, but they organize the program in different ways.
In procedure-oriented programming, a program is generally divided into functions or procedures. In object-oriented programming, a program is organized around classes and objects that combine data and behaviour.
POP vs OOPS
| Basis | POP | OOPS |
|---|---|---|
| Full Form | Procedure-Oriented Programming | Object-Oriented Programming |
| Main Focus | Functions and procedures | Objects and classes |
| Program Organization | Primarily divided into functions. | Organized using classes and objects. |
| Data and Functions | Data and functions are generally treated separately. | Data and related methods are organized within classes. |
| Reusability | Functions can be reused. | Classes, inheritance and composition support code reuse. |
| Data Organization | Less emphasis on combining data and related operations. | Data and behaviour are grouped into objects. |
| Examples | C | Python, Java, C++ |
Example
Suppose a student management system has to store student information and calculate marks. In a procedure-oriented approach, separate functions may be created for entering data, displaying data and calculating results.
In an object-oriented approach, a Student class can contain
student data along with methods such as display() and
calculate_result(). The related data and behaviour are
therefore organized together.
| POP | OOPS |
|---|---|
| Program is organized mainly around functions. | Program is organized around objects and classes. |
| Focus is on procedures and operations. | Focus is on data and behaviour of objects. |
| Commonly associated with procedural programming. | Supports concepts such as encapsulation, inheritance and polymorphism. |
Question 5: Highlight the Features of Python Which Make It Special and Different from Other Programming Languages
Answer
Python is a high-level, general-purpose programming language known for its simple syntax, readability and wide range of applications. Its features make it suitable for beginners as well as professional software development.
1. Simple and Readable Syntax
Python uses a simple and relatively concise syntax. Its syntax is designed to make programs easier to read and understand.
name = "Rahul"
if name == "Rahul":
print("Welcome Rahul")
The program can be understood easily because Python does not require large amounts of additional syntax for a simple operation.
2. High-Level Language
Python is a high-level programming language. Programmers can focus on solving the problem without having to manage many low-level details of the computer system.
3. Dynamically Typed
Python is dynamically typed. A programmer does not have to explicitly declare the data type of a variable before assigning a value to it.
x = 10 x = "Python" print(x)
The same variable name can refer to objects of different types at different points during program execution.
4. Supports Object-Oriented Programming
Python supports object-oriented programming using classes and objects. It provides concepts such as encapsulation, inheritance and polymorphism.
class Student:
def display(self):
print("Python Student")
student = Student()
student.display()
5. Multi-Paradigm Language
Python supports more than one programming style. Programs can be written using procedural programming, object-oriented programming and functional programming techniques.
6. Large Standard Library and Ecosystem
Python provides a large standard library and has a very large ecosystem of third-party packages. These libraries are used for tasks such as web development, data analysis, scientific computing, automation, artificial intelligence and machine learning.
7. Cross-Platform
Python programs can be developed and executed on different operating systems such as Windows, Linux and macOS, provided the required Python environment and dependencies are available.
8. Automatic Memory Management
Python manages memory automatically through its runtime and garbage collection mechanisms. Programmers generally do not need to explicitly release ordinary Python objects in the way manual memory management is handled in languages such as C.
9. Interactive Programming
Python provides an interactive interpreter through which programmers can execute Python statements and immediately observe their results. This is useful for learning, testing and debugging small pieces of code.
10. Wide Range of Applications
Python is used in many areas, including web development, automation, data science, artificial intelligence, machine learning, scientific computing, scripting and educational programming.
Example
numbers = [1, 2, 3, 4, 5] squares = [n * n for n in numbers] print(squares)
Output
[1, 4, 9, 16, 25]
The concise syntax, readability and availability of libraries are some of the important reasons for Python's popularity among students and developers.
Question 6: What Will Happen If We End Our Python Statement with a Semicolon (;)?
Answer
A semicolon ; is a valid character in Python. However,
unlike languages such as C, C++ and Java, Python normally does not
require a semicolon at the end of every statement.
A semicolon can be used to terminate a statement. It can also be used to place more than one simple statement on the same line.
Example 1: Semicolon at the End of a Statement
x = 10; print(x);
Output
10
The program executes normally. The semicolon does not produce an error in this example.
Example 2: Multiple Statements on One Line
a = 10; b = 20 print(a + b)
Output
30
Here, the semicolon separates the two assignment statements.
Is a Semicolon Required in Python?
No. A semicolon is normally unnecessary when each statement is written on its own line.
x = 10 y = 20 print(x + y)
This style is generally preferred because it makes Python programs clearer and easier to read.
Question 7: Define Python Variables. Give Examples of int, float and String Data Types
Answer
A variable is a name that refers to an object or value in a Python program. When a value is assigned to a variable, Python creates the appropriate object and associates the variable name with it.
Unlike statically typed languages where a variable's type is generally specified in its declaration, Python does not require the programmer to declare the type separately.
Creating Variables in Python
age = 20 price = 99.50 name = "Rahul"
In the above example, age refers to an integer,
price refers to a floating-point number, and
name refers to a string.
1. Integer (int)
The int data type represents whole numbers without a
fractional part.
age = 20 print(age) print(type(age))
Output
20 <class 'int'>
2. Floating-Point Number (float)
The float data type represents numbers containing a
fractional or decimal part.
price = 99.50 print(price) print(type(price))
Output
99.5 <class 'float'>
3. String (str)
A string is a sequence of characters enclosed within single quotes, double quotes or triple quotes.
name = "Rahul" print(name) print(type(name))
Output
Rahul <class 'str'>
Example Using All Three Types
student_name = "Rahul"
age = 20
percentage = 85.50
print("Name:", student_name)
print("Age:", age)
print("Percentage:", percentage)
Output
Name: Rahul Age: 20 Percentage: 85.5
Checking the Type of a Variable
The built-in type() function can be used to determine the
type of an object referred to by a variable.
x = 100 y = 25.75 z = "Python" print(type(x)) print(type(y)) print(type(z))
Output
<class 'int'> <class 'float'> <class 'str'>
Question 8: What Will Be the Output of the Following Python Code?
Question
rows = 5
for i in range(rows, 0, -1):
print("*" * i)
Answer
The variable rows is assigned the value 5.
The for loop uses the expression
range(rows, 0, -1).
The range() function has three arguments in this program:
the starting value, the stopping value and the step value.
| Argument | Value | Meaning |
|---|---|---|
| Start | 5 | Loop starts from 5. |
| Stop | 0 | 0 is excluded. |
| Step | -1 | Value decreases by 1 each time. |
Therefore, the values generated by the range are:
5, 4, 3, 2, 1
The expression "*" * i repeats the asterisk character
i times.
For example, when i = 5, the expression produces five
asterisks. When i = 4, it produces four asterisks, and so
on.
Output
***** **** *** ** *
Logic of the Program
| Value of i | "*" * i | Output |
|---|---|---|
| 5 | "*" * 5 | ***** |
| 4 | "*" * 4 | **** |
| 3 | "*" * 3 | *** |
| 2 | "*" * 2 | ** |
| 1 | "*" * 1 | * |
Question 9: What Will Be the Output of the Following Python Code?
Question
int = 7 print(int)
Answer
The given program does not contain a syntax error. It will
successfully print the value 7.
Output
7
However, there is an important issue with this code. int
is already the name of Python's built-in type used for representing
integers.
When we write:
int = 7
the name int is assigned the value 7. This
shadows the built-in int name in the current scope.
Why Is This a Problem?
After assigning a value to int, the built-in
int() function cannot be accessed through the name
int in that scope.
int = 7
print(int)
number = int("25")
The last statement will fail because int now refers to the
integer value 7, not the built-in conversion function.
Corrected Version
A different variable name should be used instead of int.
number = 7
print(number)
value = int("25")
print(value)
Output
7 25
Here, int() continues to refer to Python's built-in
integer conversion function.
Question 10: Explain Operator Precedence and Associativity. Evaluate the Given Expression Step by Step
Answer
When an expression contains more than one operator, Python needs rules to determine the order in which the operators should be evaluated. These rules are called operator precedence and associativity.
Operator Precedence
Operator precedence determines which operator is evaluated first when an expression contains different types of operators.
For example, multiplication has higher precedence than addition.
result = 10 + 5 * 2 print(result)
The multiplication operation is performed first:
5 * 2 = 10 10 + 10 = 20
Output
20
If addition had been evaluated first, the result would have been different. Therefore, understanding precedence is important when evaluating Python expressions.
Operator Precedence – Common Order
| Priority | Operators |
|---|---|
| Highest | () Parentheses |
** Exponentiation |
|
*, /, //, % |
|
+, - |
|
Comparison operators such as >, <,
==, != |
|
not |
|
and |
|
| Lowest among these | or |
Associativity
Associativity determines the direction in which operators having the same precedence are evaluated.
For many Python operators, evaluation is from left to right. Exponentiation is an important exception because it associates from right to left.
Given Expression
a = 10 b = 3 c = 2 result = (a + b * c) ** 2 > 100 and a // b == 3 or not (c % 2 == 0) print(result)
Step 1: Evaluate Multiplication
Inside the parentheses, multiplication has higher precedence than addition.
b * c = 3 * 2 = 6
Therefore:
a + b * c = 10 + 6 = 16
Step 2: Evaluate Exponentiation
16 ** 2 = 256
Step 3: Evaluate the Comparison
256 > 100 True
Step 4: Evaluate Floor Division
a // b 10 // 3 = 3
Therefore:
a // b == 3 3 == 3 True
Step 5: Evaluate the and Expression
True and True True
Step 6: Evaluate the not Expression
First evaluate the expression inside the parentheses:
c % 2 = 2 % 2 = 0
Therefore:
c % 2 == 0 True
The not operator changes True to False.
not True False
Step 7: Evaluate the Final or Expression
True or False True
Final Output
True
Question 11: Explain Python's Built-in Data Structures with Examples
Answer
A data structure is a way of organizing and storing data so that it can be accessed and processed efficiently. Python provides several built-in data structures that are commonly used in programming.
The four important built-in collection data structures are list, tuple, set and dictionary.
1. List
A list is an ordered and mutable collection of elements. Lists can contain elements of different data types, and duplicate values are allowed.
numbers = [10, 20, 30, 20] print(numbers) print(numbers[0])
Output
[10, 20, 30, 20] 10
Lists are mutable, which means their elements can be changed after the list has been created.
numbers = [10, 20, 30] numbers[1] = 50 print(numbers)
Output
[10, 50, 30]
2. Tuple
A tuple is an ordered collection that is generally immutable. Once a tuple has been created, its elements cannot be changed.
point = (10, 20) print(point) print(point[0])
Output
(10, 20) 10
A tuple can be useful when a collection of values should remain unchanged.
3. Set
A set is an unordered collection of unique elements. Duplicate values are automatically removed from a set.
numbers = {10, 20, 10, 30}
print(numbers)
The set contains each value only once. The order in which elements are displayed should not be relied upon.
4. Dictionary
A dictionary stores data in the form of key-value pairs. Each key is used to access its corresponding value.
student = {
"name": "Rahul",
"age": 20,
"marks": 85
}
print(student["name"])
print(student["marks"])
Output
Rahul 85
Comparison of Built-in Data Structures
| Data Structure | Mutable | Important Characteristic | Example |
|---|---|---|---|
| List | Yes | Ordered collection; duplicate values allowed. | [10, 20, 30] |
| Tuple | No | Ordered and immutable collection. | (10, 20, 30) |
| Set | Yes | Collection of unique elements. | {10, 20, 30} |
| Dictionary | Yes | Stores key-value pairs. | {"name": "Rahul"} |
Example Using Different Data Structures
subjects = ["Python", "DBMS", "DAA"]
marks = (80, 85, 90)
unique_marks = {80, 85, 90}
student = {
"name": "Rahul",
"marks": 85
}
print(subjects)
print(marks)
print(unique_marks)
print(student)
The choice of data structure depends on the type of data being stored and the operations that need to be performed on that data.
Question 12: Differentiate Between break, continue and pass. Write a Program to Print Prime Numbers from 1 to 50
Answer
The statements break, continue and
pass are commonly used in Python programs involving loops
and conditional structures. However, they perform different
operations.
1. break Statement
The break statement immediately terminates the nearest
enclosing loop. Program execution continues with the statement
following the loop.
for i in range(1, 6):
if i == 4:
break
print(i)
Output
1 2 3
When i becomes 4, the break statement
terminates the loop.
2. continue Statement
The continue statement skips the remaining statements of
the current iteration and moves to the next iteration of the loop.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1 2 4 5
When i becomes 3, the continue statement skips
the print statement for that iteration.
3. pass Statement
The pass statement performs no operation. It is generally
used as a placeholder when a statement is syntactically required but
no action is currently needed.
for i in range(5):
if i == 2:
pass
print(i)
Output
0 1 2 3 4
The pass statement does not terminate the loop and does
not skip the iteration. It simply does nothing.
Difference Between break, continue and pass
| Statement | Purpose | Effect on Loop |
|---|---|---|
| break | Terminates the loop. | Loop ends immediately. |
| continue | Skips the current iteration. | Loop proceeds to the next iteration. |
| pass | Acts as a placeholder. | Loop continues normally. |
Program to Print Prime Numbers from 1 to 50
A prime number is a number greater than 1 that has exactly two positive factors: 1 and itself.
To check whether a number is prime, the program tests whether the number is divisible by any integer from 2 up to its square root. If a divisor is found, the number is not prime.
for num in range(2, 51):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Logic of the Program
The outer loop selects each number from 2 to 50. For every number, the inner loop checks whether it has a divisor other than 1 and itself.
If a divisor is found, is_prime is changed to
False and break terminates the inner loop.
If no divisor is found, the number is printed as a prime number.
Question 13: Describe Python Blocks and Conditional Statements. Write a Program to Grade Students Using elif
Answer
Python Blocks
A block is a group of statements that belong to the same
compound statement, such as an if statement, loop,
function or class.
Python uses indentation to identify the statements belonging to a block. Unlike languages that commonly use braces to mark blocks, Python uses whitespace indentation as part of its syntax.
age = 20
if age >= 18:
print("Adult")
print("Eligible")
Both print() statements are indented and therefore belong
to the if block.
Conditional Statements
Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.
Python mainly provides the following conditional structures:
- if statement
- if-else statement
- if-elif-else statement
1. if Statement
marks = 80
if marks >= 50:
print("Pass")
2. if-else Statement
marks = 40
if marks >= 50:
print("Pass")
else:
print("Fail")
3. if-elif-else Statement
The elif statement is used when multiple conditions need
to be checked. Python evaluates the conditions from top to bottom.
When a condition becomes true, its corresponding block is executed.
Program to Grade Students Based on Marks
marks = float(input("Enter marks: "))
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Example
Suppose the student enters 85 as the marks. Python first
checks whether the marks are greater than or equal to 90. This
condition is false.
The next condition checks whether the marks are greater than or equal
to 80. Since 85 satisfies this condition, the grade is assigned as
A. The remaining elif conditions are not
executed.
Output
Enter marks: 85 Grade: A
Grade Conditions
| Marks | Grade |
|---|---|
| 90 and above | A+ |
| 80 – 89 | A |
| 70 – 79 | B |
| 60 – 69 | C |
| 50 – 59 | D |
| Below 50 | F |
14. Classify Different Types of Operators in Python
Operators are special symbols or keywords used to perform operations on values and variables. Python provides several types of operators for performing arithmetic calculations, comparisons, logical operations, assignments, bit-level operations, and checking membership or identity.
Operators are an important part of Python programming because they allow a programmer to manipulate data and construct expressions. The major types of operators available in Python are shown below.
Types of Operators in Python
| Operator Type | Purpose | Examples |
|---|---|---|
| Arithmetic | Perform mathematical calculations | +, -, *, /, %, //, ** |
| Comparison | Compare two values | ==, !=, >, <, >=, <= |
| Assignment | Assign or update values | =, +=, -=, *=, /= |
| Logical | Combine or reverse conditions | and, or, not |
| Bitwise | Perform operations on individual bits | &, |, ^, ~, <<, >> |
| Membership | Check whether a value exists in a sequence | in, not in |
| Identity | Check whether two references point to the same object | is, is not |
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations. Python supports addition, subtraction, multiplication, division, modulus, floor division and exponentiation.
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a // b)
print(a ** b)
Output:
13
7
30
3.3333333333333335
1
3
1000
Here, % returns the remainder, // performs floor division, and ** is used for exponentiation.
2. Comparison Operators
Comparison operators compare two values and return either True or False.
a = 10
b = 5
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
Output:
False
True
True
False
True
False
3. Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =. Python also provides compound assignment operators that combine an operation with assignment.
x = 10
x += 5
print(x)
x -= 2
print(x)
x *= 3
print(x)
x /= 13
print(x)
Output:
15
13
39
3.0
4. Logical Operators
Logical operators are used to combine conditions. Python provides three logical operators: and, or and not.
age = 25
print(age > 18 and age < 60)
print(age < 18 or age > 60)
print(not(age > 18))
Output:
True
False
False
The and operator returns true when the required conditions are true, or returns true when at least one condition is true, and not reverses the logical result.
5. Bitwise Operators
Bitwise operators perform operations on the binary representation of integers. They are particularly useful when working with low-level operations, flags and binary data.
a = 5
b = 3
print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 1)
print(a >> 1)
Output:
1
7
6
-6
10
2
For example, 5 is represented in binary as 0101 and 3 as 0011. The bitwise AND operation compares the corresponding bits.
6. Membership Operators
Membership operators are used to check whether a particular value is present in a sequence such as a string, list or tuple.
numbers = [10, 20, 30, 40]
print(20 in numbers)
print(50 in numbers)
print(50 not in numbers)
Output:
True
False
True
7. Identity Operators
Identity operators are used to check whether two variables refer to the same object in memory. Python provides is and is not. Identity operators should not be confused with the equality operator ==. The == operator compares values, whereas is checks object identity.
a = [10, 20]
b = a
c = [10, 20]
print(a == b)
print(a == c)
print(a is b)
print(a is c)
Output:
True
True
True
False
Here, a and b refer to the same list object, while c contains the same values but is a separate list object. Therefore, a == c is True but a is c is False.
Quick Revision
| Operator | Example | Use |
|---|---|---|
| Arithmetic | a + b | Mathematical calculation |
| Comparison | a > b | Compare values |
| Assignment | a += 5 | Assign/update values |
| Logical | a > 5 and b < 10 | Combine conditions |
| Bitwise | a & b | Bit-level operation |
| Membership | x in list | Check membership |
| Identity | a is b | Check object identity |
15. Explain Type Conversion and Indentation in Python
Type Conversion
Type conversion means converting a value from one data type to another. Python provides several built-in functions for converting values between different data types. Type conversion is frequently required when processing user input because the input() function returns data as a string.
For example, if a user enters a number using input(), Python initially treats the entered value as a string. If mathematical calculations are required, the value should be converted to an integer or floating-point number.
Common Type Conversion Functions
| Function | Purpose | Example |
|---|---|---|
| int() | Convert to integer | int("25") |
| float() | Convert to floating-point number | float("25.5") |
| str() | Convert to string | str(25) |
| list() | Convert an iterable into a list | list("ABC") |
| tuple() | Convert an iterable into a tuple | tuple([1, 2, 3]) |
| set() | Convert an iterable into a set | set([1, 2, 2, 3]) |
Example of Type Conversion
num1 = "10"
num2 = "20"
a = int(num1)
b = int(num2)
result = a + b
print(result)
Output:
30
Without converting the strings to integers, the + operator would perform string concatenation rather than numerical addition.
a = "10"
b = "20"
print(a + b)
Output:
1020
Implicit and Explicit Conversion
Python can perform some conversions automatically. This is called implicit type conversion. When the programmer explicitly converts a value using functions such as int(), float() or str(), it is called explicit type conversion.
Implicit Conversion
a = 10
b = 2.5
result = a + b
print(result)
print(type(result))
Output:
12.5
<class 'float'>
Here, the integer value is promoted to a floating-point value during the arithmetic operation.
Explicit Conversion
marks = "85"
marks = int(marks)
print(marks)
print(type(marks))
Output:
85
<class 'int'>
Indentation in Python
Indentation means the spaces at the beginning of a line of Python code. Python uses indentation to define a block of code. Unlike languages that use braces such as { } to group statements, Python uses consistent indentation.
Usually, four spaces are used for one indentation level. The important point is that statements belonging to the same block must have consistent indentation.
age = 20
if age >= 18:
print("Eligible")
print("Adult")
Both print statements belong to the if block because they are indented by the same amount.
Incorrect Indentation
age = 20
if age >= 18:
print("Eligible")
The above program produces an IndentationError because the statement belonging to the if block has not been indented.
Indentation with Nested Blocks
marks = 85
if marks >= 40:
print("Pass")
if marks >= 75:
print("Distinction")
Output:
Pass
Distinction
The second if statement is further indented because it is inside the first if block. Therefore, indentation also allows Python to represent nested program structures clearly.
16. Discuss for Loop with range(), Strings and Lists
The for loop in Python is used to repeatedly execute a block of code for each item in a sequence or iterable. It is commonly used with ranges, strings, lists, tuples and other collections.
Basic for Loop
for i in range(5):
print(i)
Output:
0
1
2
3
4
The range(5) generates values starting from 0 up to, but not including, 5.
Using range(start, stop)
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
The first argument specifies the starting value and the second argument specifies the stopping point. The stop value itself is not included.
Using range(start, stop, step)
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
Here, the loop starts at 2, stops before 11 and increases the value by 2 during every iteration.
for Loop with a String
A string is an iterable object. Therefore, a for loop can process its characters one at a time.
name = "Python"
for ch in name:
print(ch)
Output:
P
y
t
h
o
n
for Loop with a List
A list can also be traversed using a for loop. Each iteration returns the next element of the list.
numbers = [10, 20, 30, 40]
for n in numbers:
print(n)
Output:
10
20
30
40
Program to Find the Sum of 10 Elements of a List
The following program creates a list containing 10 elements and uses a for loop to calculate their sum.
numbers = [10, 20, 30, 40, 50,
60, 70, 80, 90, 100]
total = 0
for n in numbers:
total = total + n
print("Sum =", total)
Output:
Sum = 550
How the Sum Program Works
| Step | Current Element | Total |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 30 | 60 |
| 4 | 40 | 100 |
| 5 | 50 | 150 |
| 6 | 60 | 210 |
| 7 | 70 | 280 |
| 8 | 80 | 360 |
| 9 | 90 | 450 |
| 10 | 100 | 550 |
The variable total initially contains 0. During every iteration, the current list element is added to total. After the tenth iteration, the final value is 550.
Using sum() Function
Python also provides the built-in sum() function for calculating the sum of numeric elements in an iterable.
numbers = [10, 20, 30, 40, 50,
60, 70, 80, 90, 100]
total = sum(numbers)
print("Sum =", total)
Output:
Sum = 550
For learning loops and programming logic, the first approach is useful because it demonstrates how the total is calculated step by step. The sum() approach is shorter when the calculation itself is all that is required.
17. Programs for Swapping Numbers and Finding the First Even Number
Program 1: Swap Two Numbers Without Using a Temporary Variable
Swapping means exchanging the values of two variables. Python allows two variables to be swapped directly using multiple assignment, without creating a separate temporary variable.
a = 10
b = 20
print("Before swapping:")
print("a =", a)
print("b =", b)
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10
How It Works
The statement a, b = b, a simultaneously assigns the old value of b to a and the old value of a to b. Therefore, a temporary variable is not required.
Program 2: Find the First Even Number in a List
An even number is an integer that is completely divisible by 2. The following program checks the elements of a list one by one and stops when it finds the first even number.
numbers = [15, 27, 19, 13, 24, 31, 42]
for n in numbers:
if n % 2 == 0:
print("First even number =", n)
break
Output:
First even number = 24
Explanation
The program starts checking the list from the first element. The values 15, 27, 19 and 13 are not divisible by 2. When the program reaches 24, the condition n % 2 == 0 becomes true.
The program then prints 24 and executes the break statement. The break statement terminates the loop immediately, so the remaining elements are not checked.
Another Example
numbers = [11, 17, 23, 36, 48]
for n in numbers:
if n % 2 == 0:
print("First even number =", n)
break
Output:
First even number = 36
18. Differentiate Between Keywords and Identifiers
In Python programming, keywords and identifiers are two important concepts used while writing programs. Keywords are reserved words that have a predefined meaning in Python, whereas identifiers are names created by the programmer for variables, functions, classes, objects and other program elements.
Keywords
Keywords are reserved words in Python. They have a special meaning defined by the Python language and therefore cannot normally be used as the name of a variable, function or class.
Some commonly used Python keywords are:
if
else
elif
for
while
break
continue
def
class
return
import
from
try
except
finally
True
False
None
and
or
not
in
is
Example of a Keyword
age = 20
if age >= 18:
print("Adult")
Here, if is a Python keyword because it has a predefined purpose in the language. It is used to specify a conditional statement.
Identifiers
An identifier is a name given by the programmer to a program element. Identifiers can be used for variables, functions, classes, objects, modules and other user-defined elements.
student_name = "Rahul"
age = 21
def calculate_total():
return 100
In this example, student_name, age and calculate_total are identifiers.
Rules for Naming Identifiers
Python follows specific rules when identifiers are created. These rules must be followed to avoid syntax errors and to make programs easier to understand.
| Rule | Explanation | Example |
|---|---|---|
| 1 | An identifier can contain letters, digits and underscore. | student_1 |
| 2 | An identifier cannot start with a digit. | 1student is invalid |
| 3 | An identifier can start with a letter or underscore. | student, _student |
| 4 | Spaces are not allowed in identifiers. | student name is invalid |
| 5 | Special symbols such as @, # and $ are not allowed. | student@name is invalid |
| 6 | Python identifiers are case-sensitive. | Age and age are different |
| 7 | Keywords should not be used as identifiers. | class is invalid |
Valid and Invalid Identifiers
| Identifier | Valid / Invalid | Reason |
|---|---|---|
| student_name | Valid | Contains letters and underscore |
| student1 | Valid | Digits can be used after the first character |
| _marks | Valid | Can start with underscore |
| student name | Invalid | Contains a space |
| 1student | Invalid | Starts with a digit |
| student@name | Invalid | Contains a special character |
| class | Invalid | class is a Python keyword |
Keywords vs Identifiers
| Keywords | Identifiers |
|---|---|
| Reserved by Python | Defined by the programmer |
| Have predefined meanings | Used to name program elements |
| Cannot normally be used as variable names | Can be used as variable, function or class names |
| Examples: if, else, for, class | Examples: name, age, total_marks |
Example
student_name = "Amit"
if student_name:
print(student_name)
Here, student_name is an identifier, while if is a keyword. The keyword provides the structure of the statement, whereas the identifier represents a programmer-defined name.
19. Write Programs to Check Leap Year and Find Factorial
Program 1: Check Whether a Year is a Leap Year
A leap year contains 366 days instead of the usual 365 days. A year is a leap year if it is divisible by 400, or if it is divisible by 4 but not divisible by 100.
The condition can therefore be written as:
(year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)
Python Program
year = int(input("Enter a year: "))
if year % 400 == 0:
print("Leap year")
elif year % 100 == 0:
print("Not a leap year")
elif year % 4 == 0:
print("Leap year")
else:
print("Not a leap year")
Example Output
Enter a year: 2024
Leap year
For 2024, the year is divisible by 4 and is not a century year. Therefore, it is a leap year.
Another Example
Enter a year: 1900
Not a leap year
Although 1900 is divisible by 4, it is also divisible by 100 and is not divisible by 400. Therefore, 1900 is not a leap year.
Leap Year Logic
| Condition | Result |
|---|---|
| Divisible by 400 | Leap Year |
| Divisible by 100 but not 400 | Not a Leap Year |
| Divisible by 4 but not 100 | Leap Year |
| Not divisible by 4 | Not a Leap Year |
Program 2: Find the Factorial of a Number
The factorial of a positive integer n is the product of all positive integers from 1 to n. It is represented by n!.
For example:
5! = 5 × 4 × 3 × 2 × 1
= 120
The factorial of zero is also defined as 1.
0! = 1
Python Program Using for Loop
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial = factorial * i
print("Factorial =", factorial)
Example Output
Enter a number: 5
Factorial = 120
Step-by-Step Calculation
| Iteration | i | factorial |
|---|---|---|
| Initial | - | 1 |
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 6 |
| 4 | 4 | 24 |
| 5 | 5 | 120 |
The variable factorial starts with 1. During every iteration, the current value of i is multiplied with the existing factorial value. After the loop completes, the resulting value is the factorial of the given number.
Factorial Using a while Loop
n = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= n:
factorial = factorial * i
i += 1
print("Factorial =", factorial)
Output:
Enter a number: 6
Factorial = 720
Factorial Using a Function
The factorial calculation can also be placed inside a function. This makes the program reusable.
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5))
Output:
120
Python Placement Questions – Quick Revision
The following table provides a quick revision of the major concepts covered in all 19 placement questions.
| Question | Main Topic | Important Concept |
|---|---|---|
| 1 | OOPS | Classes, objects and OOP concepts |
| 2 | C vs Python | Language and programming differences |
| 3 | Features of OOPS | Encapsulation, abstraction, inheritance, polymorphism |
| 4 | POP vs OOPS | Programming paradigms |
| 5 | Features of Python | Readable, high-level, dynamic and multi-paradigm language |
| 6 | Semicolon | Statement termination |
| 7 | Variables | int, float and string |
| 8 | Pattern Program | range() and string multiplication |
| 9 | Built-in Names | Shadowing the int() function |
| 10 | Operators | Precedence and associativity |
| 11 | Data Structures | List, tuple, set and dictionary |
| 12 | Loop Control | break, continue and pass |
| 13 | Conditional Statements | if, elif and else |
| 14 | Operators | Arithmetic, comparison, logical, bitwise, etc. |
| 15 | Type Conversion | int(), float(), str() and indentation |
| 16 | for Loop | range(), strings, lists and summation |
| 17 | Programming Logic | Swapping and finding the first even number |
| 18 | Keywords and Identifiers | Naming rules |
| 19 | Programs | Leap year and factorial |
Download Python Placement Questions & Answers PDF
For offline study and revision, the complete set of 19 Python Placement Questions and Answers is available in PDF format. The PDF contains the questions, detailed explanations, Python programs, outputs, tables and revision material covered in this tutorial.