1. What is Python?
o Python is a high-level, interpreted programming language known for its
readability and simplicity.
2. What are the key features of Python?
o Easy to learn and use
o Interpreted language
o Dynamically typed
o Object-oriented
o Extensive standard libraries
3. What is a variable in Python?
o A variable is a name that refers to a value stored in memory.
4. How do you declare a variable in Python?
o Simply assign a value to a variable name, e.g., x = 10.
5. What are Python data types?
o Common data types include int, float, str, list, tuple, dict, set, bool.
6. What is a list?
o A list is an ordered, mutable collection of elements.
7. What is a tuple?
o A tuple is an ordered, immutable collection of elements.
8. What is a dictionary?
o A dictionary is an unordered collection of key-value pairs.
9. What are functions in Python?
o Functions are blocks of reusable code that perform a specific task.
10. How do you define a function?
o Using the def keyword, e.g.,
o def add(a, b):
o return a + b
11. What is a loop? Name types of loops in Python.
o A loop is used to execute a block of code repeatedly.
o Types: for loop and while loop.
12. What is an if statement?
o It is used for conditional execution of code.
13. What is indentation in Python?
o Indentation is used to define blocks of code. Python uses indentation
instead of braces.
14. What is a module?
o A module is a file containing Python definitions and statements.
15. How do you import a module?
o Using the import statement, e.g., import math.
16. What is exception handling?
o It is a way to handle errors using try, except blocks.
17. What is a class in Python?
o A class is a blueprint for creating objects.
18. What is an object?
o An object is an instance of a class.
19. What is inheritance?
o Inheritance allows a class to inherit attributes and methods from
another class.
20. What is the difference between list and tuple?
o Lists are mutable; tuples are immutable.
o
21. Is Indentation Required in Python?
Yes, indentation is required in Python. A Python interpreter can be
informed that a group of statements belongs to a specific block of
code by using Python indentation. Indentations make the code easy
to read for developers in all programming languages but in Python,
it is very important to indent the code in a specific order.
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single
line, which can be useful for initializing variables with the same value.
a = b = c = 100
print(a, b, c)
Output:
100 100 100
Assigning Different Values
We can assign different values to multiple variables simultaneously,
making the code concise and easier to read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output:
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type
into another. Python provides several built-in functions to facilitate casting,
including int(), float() and str() among others.
Basic Casting Functions
int(): Converts compatible values to an integer.
float(): Transforms values into floating-point numbers.
str(): Converts any data type into a string.
s = "10"
n = int(s)
cnt = 5
f = float(cnt)
age = 25
s2 = str(age)
print(n)
print(f)
print(s2)
Output:
10
5.0
25
Getting the Type of Variable
In Python, we can determine the type of a variable using the type()
function. This built-in function returns the type of the object passed to it.
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Object Reference in Python
Let us assign a variable x to value 5.
x=5
When x = 5 is executed, Python creates an object to represent the
value 5 and makes x reference this object.
Can we Pass a function as an argument in Python?
Yes, Several arguments can be passed to a function, including objects,
variables (of the same or distinct data types) and functions. Functions can
be passed as parameters to other functions because they are objects.
Higher-order functions are functions that can take other functions as
arguments.
What are Built-in data types in Python?
The following are the standard or built-in data types in Python:
Numeric: The numeric data type in Python represents the data that
has a numeric value. A numeric value can be an integer, a floating
number, a Boolean, or even a complex number.
Sequence Type: The sequence Data Type in Python is the ordered
collection of similar or different data types. There are several sequence
types in Python:
o Python String
o Python List
o Python Tuple
o Python range
Mapping Types: In Python, hashable data can be mapped to random
objects using a mapping object. There is currently only one common
mapping type, the dictionary and mapping objects are mutable.
o Python Dictionary
Set Types: In Python, a Set is an unordered collection of data types
that is iterable, mutable and has no duplicate elements. The order of
elements in a set is undefined though it may consist of various
elements.
17. What is the difference between a Mutable datatype and an
Immutable data type?
Mutable data types can be edited i.e., they can change at
runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at
runtime. Eg – String, Tuple, etc.
18. What is a Variable Scope in Python?
The location where we can find a variable and also access it if required is
called the scope of a variable.
Python Local variable: Local variables are those that are initialized
within a function and are unique to that function. A local variable
cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are
defined and declared outside any function and are not specified to any
function.
Module-level scope: It refers to the global objects of the current
module accessible in the program.
Outermost scope: It refers to any built-in names that the program can
call. The name referenced is located last among the objects in this scope.
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
Variable names can only contain letters, digits and underscores ( _).
A variable name cannot start with a digit.
Variable names are case-sensitive like myVar and myvar are different.
Avoid using Python keywords like if, else, for as variable names.
Input fn()
Understanding input and output operations is fundamental to Python
programming. With the print() function, we can display output in
various formats, while the input() function enables interaction with
users by gathering input during program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it
returns the user input in form of a string.
Printing Output using print() in Python
At its core, printing output in Python is straightforward, thanks to the print()
function. This function allows us to display text, variables and expressions on the
console. Let's begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double quotes.
When executed, this statement will output the text to the console.
print("Hello, World!")
In Python programming, Operators in general are used to perform
operations on values and variables.
Operators: Special symbols like -, + , * , /, etc.
Operands: Value on which the operator is applied.
Types of Operators in Python
a = 15
b=4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Comparison Operators
In Python, Comparison (or Relational) operators compares values. It
either returns True or False according to the condition.
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output
False
True
False
Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations.
These are used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40
Assignment Operators
Python Assignment operators are used to assign values to the variables.
This operator is used to assign the value of the right side of the
expression to the left side operand.
Example
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Identity Operators
In Python, is and is not are the identity operators both are used to check
if two values are located on the same part of the memory. Two variables
that are equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators
In Python, in and not in are the membership operators that are used to
test whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
19. How is a dictionary different from a list?
A list is an ordered collection of items accessed by their index, while a
dictionary is an unordered collection of key-value pairs accessed using
unique keys. Lists are ideal for sequential data, whereas dictionaries are
better for associative data. For example, a list can store [10, 20, 30],
whereas a dictionary can store {"a": 10, "b": 20, "c": 30}.
Differentiate between List and Tuple?
Let’s analyze the differences between List and Tuple :
List
Lists are Mutable datatype.
Lists consume more memory
The list is better for performing operations, such as insertion and
deletion.
The implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consumes less memory as compared to the list
A Tuple data type is appropriate for accessing the elements
The implication of iterations is comparatively Faster
What is PIP?
PIP is an acronym for Python Installer Package which provides a
seamless interface to install various Python modules. It is a command-line
tool that can search for packages over the internet and install them
without any user interaction.
How can you concatenate two lists in Python?
We can concatenate two lists in Python using the +operator or the
extend() method.
Using the + operator:
This creates a new list by joining two lists together.
a = [1, 2, 3]
b = [4, 5, 6]
res = a + b
print(res)
Output
[1, 2, 3, 4, 5, 6]
What is the difference between a Mutable datatype and an Immutable
data type?
Mutable data types can be edited i.e., they can change at runtime. Eg: List,
Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg:
String, Tuple, etc.
How is a dictionary different from a list?
A list is a collection of elements accessed by their numeric index, while a
dictionary is a collection of key-value pairs accessed by keys.
List: Maintains order, allows duplicate values, and is indexed by
position.
Dictionary: Maintains insertion order (since Python 3.7+), requires
unique keys, and provides fast lookups based on keys instead of index.
# List: Accessed by index
a = ["apple", "banana", "cherry"]
print(a[1])
# Dictionary: Accessed by key
d = {"Alice": 25, "Bob": 30}
print(d["Bob"])
6. What is the difference between Python Arrays and Lists?
Lists can hold elements of different data types and are more flexible, while
arrays (from the array module) can only store elements of the same type,
making them more memory-efficient and faster for numerical data. Lists
are commonly used for general-purpose collections, whereas arrays are
preferred when type consistency and performance matter.
Example:
from array import array
arr = array('i', [1, 2, 3, 4]) # Array of integers
for x in arr:
print(x)
Example:
a = [1, 'hello', 3.14, [1, 2, 3]]
for x in a:
print(x)
Differentiate between List and Tuple?
Feature List (list) Tuple (tuple)
Immutable (cannot be
Mutability Mutable (can be changed)
changed)
Syntax Square brackets: [1, 2, 3] Parentheses: (1, 2, 3)
Suitable for fixed or constant
Use Case Suitable for dynamic data
data
Not hashable (unusable as Hashable if elements are
Hashable
dict key) immutable
Describe Python Strings, their immutability and common
operations.
A string in Python is a sequence of characters enclosed in single (' '),
double (" "), or triple quotes (''' ''' or """ """).
Immutability: Strings are immutable, meaning once created, their
contents cannot be changed. Any operation that modifies a string
actually creates a new string object.
Immutability:
Once a string is created, its contents cannot be changed. Operations that
modify a string return a new string.
s = "abc"
s[0] = "z" # This give TypeError
Common Operations:
Concatenation: "Hello" + " World" → "Hello World"
Repetition: "Hi" * 3 → "HiHiHi"
Indexing & Slicing: "Python"[0] → 'P', "Python"[1:4] → 'yth'
Membership: "Py" in "Python" → True
Built-in Methods:
.upper() → "hello".upper() → "HELLO"
.lower() → "HELLO".lower() → "hello"
.strip() → " hi ".strip() → "hi"
.replace("a","b") → "data".replace("a","o") → "doto"
.split() → "a,b,c".split(",") → ['a','b','c']
.join() → " ".join(['a','b']) → "a b"
print("GFG")
s = "hello world"
# Common Operations
s[0] # 'h' (indexing)
s[0:5] # 'hello' (slicing)
# Built-in Functions
[Link]() # 'HELLO WORLD'
[Link]() # ['hello', 'world']
"-".join(["a", "b"]) # 'a-b'
[Link]("world", "Python") # 'hello Python'
[Link]("o") # returns index of first 'o'
f-Strings (formatted strings):
name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}") # 'Name: Bob, Age: 25'
Counting Characters in a String
Assign the results of multiple operations on a string to variables in one
line.
word = "Python"
length = len(word)
print("Length of the word:", length)
Output:
Length of the word: 6
Keywords in Python are special reserved words that are part of the
language itself. They define the rules and structure of Python programs
which means you cannot use them as names for your variables, functions,
classes or any other identifiers.
Getting List of all Python keywords
We can also get all the keyword names using the below code.
import keyword
print("The list of keywords are : ")
print([Link])
Output
The list of keywords are:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
Keywords as Variable Names
If we attempt to use a keyword as a variable, Python will raise
a SyntaxError. Let's look at an example:
for = 10
print(for)
Output
Hangup (SIGHUP)
File "/home/guest/sandbox/[Link]", line 1
for = 10
^
SyntaxError: invalid syntax
Keywords vs Identifiers
Keywords Identifiers
Reserved words in Python that have a Names given to variables,
specific meaning. functions, classes, etc.
Cannot be used as variable names. Can be used as variable names if
Keywords Identifiers
not a keyword.
Examples: if, else, for, while Examples: x, number, sum, result
User-defined, meaningful names in
Part of the Python syntax.
the code.
Can be defined and redefined by
They cannot be redefined or changed.
the programmer.
Variables vs Keywords
Variables Keywords
Reserved words with predefined
Used to store data.
meanings in Python.
Can be created, modified, and deleted Cannot be modified or used as
by the programmer. variable names.
Examples: x, age, name Examples: if, while, for
Hold values that are manipulated in the Used to define the structure of
program. Python code.
Variable names must follow naming rules Fixed by Python language and
but are otherwise flexible. cannot be altered.
Data types in Python are a way to classify data items. They represent the
kind of value, which determines what operations can be performed on that
data. Since everything is an object in Python programming, Python data
types are classes and variables are instances (objects) of these classes.
The following are standard or built-in data types in Python:
Numeric: int, float, complex
Sequence Type: string, list, tuple
Mapping Type: dict
Boolean: bool
Set Type: set, frozenset
Binary Types: bytes, bytearray, memoryview