0% found this document useful (0 votes)
3 views21 pages

Python Question Bank

Python has three main numeric data types: integers (int), floating-point numbers (float), and complex numbers (complex), each serving different numerical purposes. Control flow statements, including conditional statements (if, if-else), looping statements (for, while), and jump statements (break, continue, pass), manage the execution order of code. Additionally, Python allows importing modules in various ways, and provides methods for adding, updating, and deleting elements in lists, as well as utilizing data types like sets, tuples, and dictionaries for efficient data management.

Uploaded by

swanandi005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Python Question Bank

Python has three main numeric data types: integers (int), floating-point numbers (float), and complex numbers (complex), each serving different numerical purposes. Control flow statements, including conditional statements (if, if-else), looping statements (for, while), and jump statements (break, continue, pass), manage the execution order of code. Additionally, Python allows importing modules in various ways, and provides methods for adding, updating, and deleting elements in lists, as well as utilizing data types like sets, tuples, and dictionaries for efficient data management.

Uploaded by

swanandi005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

explain numeric data type in python with

example
Numeric Data Types in Python
In Python, numeric data types represent different types of numbers and are mainly
classified into three categories:
1. Integer (int)
2. Floating-Point (float)
3. Complex Numbers (complex)

1. Integer (int)
 Represents whole numbers (both positive and negative) without decimals.
 Can be of arbitrary length in Python.
Example:
x = 10 # Positive integer
y = -25 # Negative integer
z = 1000000000 # Large integer

print(type(x)) # Output: <class 'int'>

2. Floating-Point (float)
 Represents real numbers with decimal points.
 Can also represent scientific notation.
Example:
a = 10.5 # Floating point number
b = -2.75 # Negative float
c = 1.2e3 # Scientific notation (1.2 × 10³ = 1200.0)

print(type(a)) # Output: <class 'float'>


3. Complex Numbers (complex)
 Represented as a + bj, where a is the real part and b is the imaginary part (j is the
imaginary unit).
 Used in advanced mathematical computations.
Example:
p = 3 + 4j # Complex number
q = -2 - 5j # Another complex number

print(type(p)) # Output: <class 'complex'>

Type Conversion Between Numeric Types


Python allows conversion between different numeric types using int(), float(), and
complex() functions.
Example:
x = 10 # Integer
y = float(x) # Convert to float
z = complex(x) # Convert to complex

print(y) # Output: 10.0


print(z) # Output: (10+0j)

Arithmetic Operations on Numeric Types


Python supports arithmetic operations like addition (+), subtraction (-), multiplication (*),
division (/), and modulus (%) on numeric types.
Example:
a = 15
b=4

print(a + b) # Output: 19
print(a - b) # Output: 11
print(a * b) # Output: 60
print(a / b) # Output: 3.75
print(a // b) # Output: 3 (floor division)
print(a % b) # Output: 3 (modulus)

Conclusion
Python provides three main numeric data types: int, float, and complex. These types
support mathematical operations and can be converted into one another as needed.
Understanding these data types is crucial for performing numerical computations efficiently
in Python.

explain control flow statements in python


Control Flow Statements in Python
Control flow statements in Python determine the execution order of instructions based on
conditions and loops. These statements allow decision-making and iteration within a
program.
Python has three main types of control flow statements:
1. Conditional Statements (if, if-else, if-elif-else)
2. Looping Statements (for, while)
3. Jump Statements (break, continue, pass)

1. Conditional Statements
Conditional statements allow decision-making based on conditions using if, if-else, and if-
elif-else.
1.1 if Statement
Executes a block of code only if a condition is True.
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.

1.2 if-else Statement


Executes one block if the condition is True, otherwise executes another block.
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Output:
You are not eligible to vote.

1.3 if-elif-else Statement


Checks multiple conditions sequentially.
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
2. Looping Statements
Looping statements allow repeated execution of a block of code.
2.1 for Loop
Used for iterating over a sequence (list, tuple, string, etc.).
Example:
for i in range(1, 6): # Iterates from 1 to 5
print(i)
Output:
1
2
3
4
5

2.2 while Loop


Executes as long as a condition is True.
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
3. Jump Statements
Jump statements modify the normal flow of loops.
3.1 break Statement
Terminates the loop prematurely.
Example:
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2

3.2 continue Statement


Skips the current iteration and moves to the next.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5

3.3 pass Statement


Used as a placeholder for code that is yet to be implemented.
Example:
for i in range(5):
pass # Placeholder statement, does nothing

Conclusion
Control flow statements (if, loops, break, continue, pass) help in decision-making and
looping, making programs more efficient. Mastering these statements is crucial for writing
structured Python programs.

how to import modules in python


Importing Modules in Python
Introduction
Modules in Python are files containing Python code (functions, classes, or variables) that
can be reused in different programs. Python provides built-in modules and allows users to
create their own. To use a module, it must be imported into the script using the import
statement.
There are several ways to import modules in Python:
1. Importing the entire module (import module_name)
2. Importing a specific function or variable (from module_name import
function_name)
3. Importing all functions and variables (from module_name import *)
4. Using an alias (import module_name as alias)
5. Importing from a custom module

1. Importing the Entire Module


The import statement loads an entire module, and functions/variables must be accessed
using module_name.function_name.
Example: Importing the math Module
import math
print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
2. Importing a Specific Function or Variable
Instead of importing the entire module, specific functions or variables can be imported
using from module_name import function_name.
Example: Importing sqrt and pi from math Module
from math import sqrt, pi

print(sqrt(36)) # Output: 6.0


print(pi) # Output: 3.141592653589793

3. Importing All Functions and Variables


Using from module_name import *, all functions and variables of the module are imported.
However, this is not recommended as it can cause naming conflicts.
Example: Importing Everything from math Module
from math import *

print(sin(0)) # Output: 0.0


print(factorial(5)) # Output: 120
🔴 Warning: Avoid using import * as it makes debugging difficult.

4. Using an Alias (as)


Modules can be imported with an alias using as, making it easier to reference.
Example: Importing math as m
import math as m

print(m.sqrt(49)) # Output: 7.0


print(m.e) # Output: 2.718281828459045

5. Importing from a Custom Module


Python allows users to create their own modules and import them.
Step 1: Create a custom module (my_module.pfy)
def greet(name):
return f"Hello, {name}!"

pi_value = 3.14159
Step 2: Import and use it in another Python script
import my_module

print(my_module.greet("Alice")) # Output: Hello, Alice!


print(my_module.pi_value) # Output: 3.14159

Conclusion
Python provides different ways to import modules, allowing code reuse and better
organization. Choosing the right import method depends on the situation.

how to add, update and delete elements in list


Adding, Updating, and Deleting Elements in a List in Python
A list in Python is a mutable, ordered collection that allows elements to be added, updated,
and deleted. Python provides various built-in methods for modifying lists.

1. Adding Elements to a List


Elements can be added using the following methods:
 append() – Adds an element to the end of the list.
 insert() – Adds an element at a specific position.
 extend() – Adds multiple elements from another list or iterable.
Example:
# Creating a list
fruits = ["apple", "banana"]
# Using append() to add an element at the end
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']

# Using insert() to add an element at a specific index


fruits.insert(1, "mango")
print(fruits) # Output: ['apple', 'mango', 'banana', 'cherry']

# Using extend() to add multiple elements


fruits.extend(["grape", "orange"])
print(fruits) # Output: ['apple', 'mango', 'banana', 'cherry', 'grape', 'orange']

2. Updating Elements in a List


Elements in a list can be updated using indexing.
Example:
numbers = [10, 20, 30, 40]

# Updating an element at index 1


numbers[1] = 25
print(numbers) # Output: [10, 25, 30, 40]

# Updating multiple elements using slicing


numbers[2:4] = [35, 45]
print(numbers) # Output: [10, 25, 35, 45]

3. Deleting Elements from a List


Elements can be removed using the following methods:
 remove() – Removes the first occurrence of a value.
 pop() – Removes an element by index (default: last element).
 del – Deletes an element or a slice.
 clear() – Removes all elements from the list.
Example:
colors = ["red", "blue", "green", "yellow"]

# Using remove() to delete a specific value


colors.remove("blue")
print(colors) # Output: ['red', 'green', 'yellow']

# Using pop() to remove an element by index


removed_color = colors.pop(1)
print(colors) # Output: ['red', 'yellow']
print("Removed:", removed_color) # Output: Removed: green

# Using del to remove an element


del colors[0]
print(colors) # Output: ['yellow']

# Using clear() to remove all elements


colors.clear()
print(colors) # Output: []

Conclusion
Python provides multiple ways to add, update, and delete elements in a list efficiently.
Mastering these methods helps in handling lists effectively in programming.
explain pass, break, continue and else
statements write answer
Pass, Break, Continue, and Else Statements in Python
Python provides control flow statements to manage loops and conditional execution
efficiently. These include pass, break, continue, and else (with loops). Each serves a distinct
purpose in controlling program execution.

1. pass Statement
The pass statement is a placeholder that does nothing and is used when a block of code is
required syntactically but has no execution.
Example: Using pass in a Loop
for i in range(5):
if i == 2:
pass # Placeholder for future code
print(i)
Output:
0
1
2
3
4
📌 Here, pass does nothing, allowing the program to continue execution normally.

2. break Statement
The break statement terminates the loop prematurely when a condition is met.
Example: Using break in a Loop
for i in range(5):
if i == 3:
break # Loop stops when i == 3
print(i)
Output:
0
1
2
📌 The loop stops execution when i == 3.

3. continue Statement
The continue statement skips the current iteration and moves to the next iteration of the
loop.
Example: Using continue in a Loop
for i in range(5):
if i == 2:
continue # Skips when i == 2
print(i)
Output:
0
1
3
4
📌 When i == 2, continue skips that iteration, and the loop moves to i == 3.

4. else with Loops


The else block in a loop executes only if the loop completes normally (without break).
Example: Using else in a Loop
for i in range(3):
print(i)
else:
print("Loop completed successfully!")
Output:
0
1
2
Loop completed successfully!
📌 Since there is no break, the else block executes.
Example: else Not Executing Due to break
for i in range(3):
if i == 1:
break
print(i)
else:
print("Loop completed successfully!")
Output:
0
📌 The else block does not execute because the loop is terminated by break.

Conclusion
 pass: Placeholder that does nothing.
 break: Exits the loop immediately.
 continue: Skips the current iteration and moves to the next.
 else (with loops): Executes only if the loop completes without break.

explain set, tuple, dict data type with example


Set, Tuple, and Dictionary Data Types in Python
Python provides different data types for storing collections of values efficiently. The three
key types are:
1. Set (set) – Unordered, unique collection of elements.
2. Tuple (tuple) – Ordered, immutable sequence of elements.
3. Dictionary (dict) – Key-value pairs for fast lookups.

1. Set (set)
A set is an unordered collection of unique elements. It does not allow duplicate values and
is defined using curly braces {} or the set() function.
Key Features of a Set:
✔️Unordered – No specific sequence of elements.
✔️Mutable – Can add/remove elements, but elements must be immutable.
✔️No Duplicates – Duplicate values are automatically removed.
Example: Creating and Using a Set
# Creating a set
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits) # Output: {'banana', 'cherry', 'apple'} (duplicates removed)

# Adding an element
fruits.add("orange")
print(fruits) # Output: {'banana', 'cherry', 'apple', 'orange'}

# Removing an element
fruits.remove("banana")
print(fruits) # Output: {'cherry', 'apple', 'orange'}
Set Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union: {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection: {3, 4}
print(A - B) # Difference: {1, 2}

2. Tuple (tuple)
A tuple is an ordered, immutable sequence of elements. It is defined using parentheses ().
Key Features of a Tuple:
✔️Ordered – Maintains insertion order.
✔️Immutable – Cannot be modified after creation.
✔️Can Contain Duplicates – Unlike sets, tuples allow repeated values.
Example: Creating and Using a Tuple
# Creating a tuple
numbers = (10, 20, 30, 40)
print(numbers) # Output: (10, 20, 30, 40)

# Accessing elements
print(numbers[1]) # Output: 20

# Slicing a tuple
print(numbers[1:3]) # Output: (20, 30)

# Nested tuple
nested_tuple = (1, 2, (3, 4), 5)
print(nested_tuple[2]) # Output: (3, 4)
Tuple Packing and Unpacking
# Tuple Packing
person = ("Alice", 25, "Engineer")

# Tuple Unpacking
name, age, profession = person
print(name) # Output: Alice
print(age) # Output: 25
print(profession) # Output: Engineer

3. Dictionary (dict)
A dictionary is a collection of key-value pairs, where each key is unique, and values can be
accessed using keys instead of indexes.
Key Features of a Dictionary:
✔️Unordered – Elements have no fixed order (before Python 3.7).
✔️Mutable – Can modify, add, or delete key-value pairs.
✔️Unique Keys – Duplicate keys are not allowed.
Example: Creating and Using a Dictionary
# Creating a dictionary
student = {
"name": "John",
"age": 21,
"course": "Computer Science"
}

# Accessing values
print(student["name"]) # Output: John

# Adding a new key-value pair


student["grade"] = "A"
print(student) # Output: {'name': 'John', 'age': 21, 'course': 'Computer Science', 'grade': 'A'}

# Updating a value
student["age"] = 22
print(student["age"]) # Output: 22
# Removing a key-value pair
del student["course"]
print(student) # Output: {'name': 'John', 'age': 22, 'grade': 'A'}
Dictionary Methods
print(student.keys()) # Output: dict_keys(['name', 'age', 'grade'])
print(student.values()) # Output: dict_values(['John', 22, 'A'])
print(student.items()) # Output: dict_items([('name', 'John'), ('age', 22), ('grade', 'A')])

Conclusion
Data Type Ordered? Mutable? Duplicates Allowed? Syntax
Set ❌ No ✅ Yes ❌ No {} or set()
Tuple ✅ Yes ❌ No ✅ Yes ()
Dict ✅ Yes ✅ Yes ❌ No (Keys) {key: value}
Understanding sets, tuples, and dictionaries is essential for handling data efficiently in
Python.

discuss range() with syntax and example


range() Function in Python
Introduction
The range() function in Python is used to generate a sequence of numbers. It is commonly
used in loops to iterate over a specific range of values. The function returns a range object,
which is an immutable sequence of numbers.

Syntax of range()
The range() function has three different forms:
1. range(stop) → Generates numbers from 0 to stop - 1.
2. range(start, stop) → Generates numbers from start to stop - 1.
3. range(start, stop, step) → Generates numbers from start to stop - 1 with a given step
size.
General Syntax
range(start, stop, step)
 start (optional) → The starting value (default is 0).
 stop (required) → The ending value (exclusive).
 step (optional) → The difference between consecutive values (default is 1).

1. Using range(stop)
Generates numbers from 0 to stop - 1.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
📌 Since start is not given, it defaults to 0. The sequence stops at 4 (5 - 1).

2. Using range(start, stop)


Generates numbers from start to stop - 1.
Example:
for i in range(2, 7):
print(i)

Output:
2
3
4
5
6
📌 The sequence starts at 2 and stops at 6 (7 - 1).

3. Using range(start, stop, step)


Generates numbers with a specified step size.
Example:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
📌 The sequence starts at 1, increments by 2, and stops before 10.

4. Using Negative step


If step is negative, the sequence is generated in reverse order.
Example:
for i in range(10, 0, -2):
print(i)

Output:
10
8
6
4
2
📌 The sequence starts at 10, decreases by 2, and stops before 0.

5. Using range() with list()


A range object can be converted into a list.
Example:
numbers = list(range(5))
print(numbers)
Output:
[0, 1, 2, 3, 4]
📌 The range(5) object is converted into a list of numbers from 0 to 4.

Conclusion
 range() generates a sequence of numbers.
 It can be used in loops for iteration.
 Supports three parameters: start, stop, and step.
 Can generate sequences in both forward and reverse order.

You might also like