0% found this document useful (0 votes)
2 views30 pages

Python QB (1)

The document provides a comprehensive overview of various Python programming concepts, including keywords, functions, data types, and control structures. It includes examples for each concept, such as the format function, count method, and the use of loops and conditionals. Additionally, it discusses practical programming tasks like checking odd/even numbers, calculating simple interest, and understanding local and global variables.

Uploaded by

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

Python QB (1)

The document provides a comprehensive overview of various Python programming concepts, including keywords, functions, data types, and control structures. It includes examples for each concept, such as the format function, count method, and the use of loops and conditionals. Additionally, it discusses practical programming tasks like checking odd/even numbers, calculating simple interest, and understanding local and global variables.

Uploaded by

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

Short question

1. List any two keywords of Python:

• if
• return

2. State the format function in Python Programming:


The format() function allows for formatting strings. It inserts specified values into
placeholders {} within a string.

Example:

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

3. Discuss indentations in Python:

• Indentation is used to define the structure and flow of a Python program.


• Blocks of code such as loops, conditionals, and function definitions are indicated
by the same level of indentation.
• Example: if True:
print("This is indented properly.")

4. Explain count() function with example:


The count() function counts the number of occurrences of a specified value in a
sequence like a string, list, or tuple.

Example:

text = "hello world"


print(text.count("o")) # Output: 2
5. List any two Python data types:

• int (Integer)
• list

6. Discuss how to import module with example:


Modules can be imported using the import keyword.

Example:

import math
print(math.sqrt(16)) # Output: 4.0

7. Explain comments in Python:

• Comments in Python are used to describe the code and are ignored during
execution.
• Single-line comments start with #, and multi-line comments can be enclosed within
triple quotes (''' or """).

Example:

# This is a single-line comment


'''
This is a multi-line comment
spanning multiple lines.
'''

8. State Documentation strings:

• Docstrings are a special kind of comment enclosed in triple quotes, used to


describe the purpose of functions, classes, or modules.
• Example: def add(a, b):
"""This function adds two numbers."""
return a + b

9. Explain get() method with example:


The get() method retrieves the value for a specified key in a dictionary. It avoids errors if
the key does not exist by returning None (or a specified default value).

Example:

data = {"name": "Alice", "age": 25}


print(data.get("name")) # Output: Alice
print(data.get("gender", "Not specified")) # Output: Not specified

10. Discuss indentations in Python:


Python relies on proper indentation to determine the scope of blocks like loops, functions,
and conditionals. Indentation errors can cause IndentationError.

11. Discuss comments in Python:


Comments make the code more readable and explain the logic. They are ignored by the
Python interpreter.

12. Explain count() function:


The count() function counts occurrences of a specific element in a sequence.

Example:

numbers = [1, 2, 2, 3, 4, 2]
print(numbers.count(2)) # Output: 3

13. List any two Python Bitwise Operators:

• & (Bitwise AND)


• | (Bitwise OR)
14. List any two datetime functions in Python:

• datetime.now() (Returns the current date and time)


• datetime.strftime() (Formats a date object to a string)

15. Define tuple:


A tuple is an immutable sequence of elements in Python. It is similar to a list but cannot be
modified after creation.

Example:

my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)

16. Explain recursive function:


• A recursive function is a function that calls itself to solve
smaller instances of a problem.
• It must have a base case to stop recursion; otherwise, it will
result in infinite recursion.

Example:

def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

17. Discuss use of shuffle() with example:


• The shuffle() function in the random module randomly rearranges
the elements of a list.

Example:
import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers) # Output: [3, 1, 4, 5, 2] (varies)

18. State the use of difference() in set:


• The difference() method returns a new set containing elements
present in the first set but not in the second.

Example:

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.difference(set2)) # Output: {1, 2}

19. Discuss Python sys Module:


• The sys module provides access to system-specific parameters and
functions.
• Common uses include accessing command-line arguments and
controlling the interpreter.

Example:

import sys
print(sys.version) # Output: Python version details

20. Define update() in Python:


• The update() method in sets and dictionaries adds multiple
elements to a set or updates a dictionary with key-value pairs.

Example for set:


my_set = {1, 2}
my_set.update([3, 4])
print(my_set) # Output: {1, 2, 3, 4}

Example for dictionary:

my_dict = {"a": 1}
my_dict.update({"b": 2})
print(my_dict) # Output: {'a': 1, 'b': 2}

21. List any Escape Characters in Python Programming:


• \n (Newline)
• \t (Tab)

22. Discuss the use of sort():


• The sort() method sorts a list in ascending or descending order
in-place.

Example:

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]

23. List any two file open modes:


• 'r' (Read mode)
• 'w' (Write mode)

24. State bool in Python Programming:


• bool is a data type that represents True or False.
• It is used in logical operations.

Example:
print(bool(1)) # Output: True
print(bool(0)) # Output: False

25. Define print function:


• The print() function outputs data to the console.

Example:

print("Hello, World!") # Output: Hello, World!

26. State shorthand Assignment Operator in Python:


• Shorthand assignment operators combine arithmetic and assignment.
• Examples:
o += (Add and assign)
o *= (Multiply and assign)

Example:

x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8

27. Define if Statement:


• The if statement is used for conditional execution of code.

Example:

x = 10
if x > 5:
print("x is greater than 5")
28. Define strings:
• A string is a sequence of characters enclosed in quotes (', ", or
""").
• Strings are immutable in Python.

Example:

text = "Hello, World!"

29. Define function:


• A function is a reusable block of code that performs a specific
task.
• Defined using the def keyword.

Example:

def greet(name):
return f"Hello, {name}!"

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

Long type Answer

1. Python Program to Check if a Number is Odd or Even


In Python, we can check if a number is odd or even using the modulus
operator (%).

# Program to check if the number is odd or even


number = int(input("Enter a number: ")) # Accepting input from the
user
if number % 2 == 0: # Condition to check if divisible by 2
print(f"{number} is even.") # Output if condition is True
else:
print(f"{number} is odd.") # Output if condition is False

Detailed Explanation:

• input() function is used to take a number as input from the user.


• The int() function converts the input string into an integer.
• The if statement checks if the number is divisible by 2 using
number % 2 == 0.
• If True, it prints the number is even. Otherwise, it prints the
number is odd.

2. Python Program to Check if a Number is Positive,


Negative, or Zero
This program categorizes a number based on its sign.

# Program to check if the number is positive, negative, or zero


number = float(input("Enter a number: ")) # Accepting floating-point
input
if number > 0: # Condition for a positive number
print("The number is positive.")
elif number < 0: # Condition for a negative number
print("The number is negative.")
else: # If not positive or negative, it must be zero
print("The number is zero.")

Detailed Explanation:

• float(input()) allows for decimal numbers.


• The if-elif-else ladder is used for multiple conditions:
o if number > 0: Positive number.
o elif number < 0: Negative number.
o else: Zero.

3. Python Program to Describe Arithmetic Operations


This program performs and displays basic arithmetic operations.

# Program to perform arithmetic operations


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Addition: {a + b}") # Adding numbers
print(f"Subtraction: {a - b}") # Subtracting numbers
print(f"Multiplication: {a * b}") # Multiplying numbers
print(f"Division: {a / b}") # Dividing numbers
print(f"Modulus: {a % b}") # Finding the remainder

Detailed Explanation:

• Takes two inputs, a and b, as floating-point numbers.


• Performs addition (+), subtraction (-), multiplication (*),
division (/), and modulus (%) operations.
• Displays the results using formatted strings (f"...").

4. Python Program to Swap Values of Two Variables


This program swaps the values of two variables without using a third
variable.

# Program to swap two variables


x = input("Enter first value: ")
y = input("Enter second value: ")
x, y = y, x # Swapping values using tuple unpacking
print(f"After swapping: x = {x}, y = {y}")

Detailed Explanation:

• x, y = y, x swaps values directly using Python's tuple unpacking.


• This is a more Pythonic way compared to using temporary
variables.

5. Python Program to Calculate Simple Interest


Simple interest is calculated using the formula:

SI=P×R×T100\text{SI} = \frac{\text{P} \times \text{R} \times \text{T}}{100}.


# Program to calculate simple interest
P = float(input("Enter principal amount: ")) # Principal
R = float(input("Enter rate of interest: ")) # Rate of interest
T = float(input("Enter time in years: ")) # Time in years
SI = (P * R * T) / 100 # Formula for simple interest
print(f"Simple Interest is: {SI}")

Detailed Explanation:

• Inputs for P (Principal), R (Rate), and T (Time) are taken.


• Formula is applied to compute the simple interest.
• The result is displayed using a formatted string.

6. Python Program to Find the Factorial of a Number


The factorial of a number is the product of all positive integers less
than or equal to that number.

# Program to find factorial using recursion


def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call

num = int(input("Enter a number: "))


print(f"Factorial of {num} is {factorial(num)}")

Detailed Explanation:

• A recursive function factorial() is defined.


• Base case: If the number is 0 or 1, the factorial is 1.
• Recursive case: Multiplies the number by factorial(n - 1).

7. Python Program to Demonstrate Type Casting


Type casting is converting one data type to another.

# Program to demonstrate type casting


x = "123" # String
y = int(x) # String to integer
z = float(x) # String to float
print(f"Original string: {x}, Integer: {y}, Float: {z}")

Detailed Explanation:

• Converts a string "123" to integer and float.


• Demonstrates how data types can be dynamically changed in Python.

8. Python Logical Operators with Example


Logical operators are used to combine multiple conditions.

• and: Both conditions must be True.


• or: At least one condition must be True.
• not: Negates the condition.

# Example of logical operators


x = 10
y = 20
print(x > 5 and y > 15) # True (both conditions are true)
print(x > 15 or y > 15) # True (second condition is true)
print(not (x > 15)) # True (negates the condition)

9. Python Program to Find the Largest Among Three Numbers


# Program to find the largest among three numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
print(f"The largest number is {a}")
elif b >= c:
print(f"The largest number is {b}")
else:
print(f"The largest number is {c}")

Detailed Explanation:

• Uses if-elif-else ladder to compare the three numbers.


10. Explain Local & Global Variables in Python with Example
Local Variables:

• These variables are defined inside a function and are accessible


only within that function.
• Their scope is limited to the block in which they are declared.

Global Variables:

• These variables are defined outside any function or block and can
be accessed throughout the program, including inside functions.
• They can be modified inside a function using the global keyword.

Example:

# Global variable
x = 10

def demo_function():
# Local variable
y = 20
print(f"Global variable inside function: {x}") # Accessing global
variable
print(f"Local variable: {y}") # Accessing local variable

demo_function()
print(f"Global variable outside function: {x}")
# print(y) # This will give an error as y is local to the function

11. Explain the Input() Function in Detail with an Example


• The input() function allows the user to enter data at runtime.
• By default, it takes input as a string. You can convert it to
other data types using casting.

Example:

# Input function example


name = input("Enter your name: ") # Takes user input as a string
age = int(input("Enter your age: ")) # Converts input to integer
print(f"Hello {name}, you are {age} years old.")

Detailed Explanation:

• The input() function prompts the user with the provided message.
• Use type conversion functions like int(), float() if numeric
input is required.

12. Describe While Loop with Syntax & Example


A while loop is used to execute a block of code as long as a given
condition is true.

Syntax:

while condition:
# code block

Example:

# Example of while loop


count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Incrementing count to avoid infinite loop
13. Explain If-Else Statement with Syntax & Example
Syntax:

if condition:
# code block for True condition
else:
# code block for False condition

Example:

# If-else statement example


number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")

14. Describe Tuples in Detail


• Definition: Tuples are immutable, ordered collections of items.
• Characteristics:
o Defined using parentheses ().
o Elements can be of mixed data types.
o Once defined, their values cannot be changed.

Example:

# Tuple example
my_tuple = (1, 2, 3, "Hello")
print(my_tuple) # Accessing tuple elements
15. Differentiate Between Lists and Tuples
Feature List Tuple

Definition Mutable collection of items. Immutable collection of


items.

Syntax [] ()

Performanc Slower due to mutability. Faster due to immutability.


e

Use Case When frequent modifications When data integrity is


needed. priority.

16. Describe File Operations in Detail


Python provides built-in functions to work with files. Common
operations include reading, writing, and appending.

File Modes:

• "r": Read (default mode).


• "w": Write (overwrites the file).
• "a": Append.

Example:

# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")

# Reading from a file


with open("example.txt", "r") as file:
content = file.read()
print(content)
17. Explain the Term Read Input from the Console
• Definition: Reading input from the console means taking user
input during the program execution using the input() function.

Example:

name = input("Enter your name: ")


print(f"Welcome, {name}!")

18. Describe the Use of Indentation and White Space with an


Example
• Indentation defines the block of code in Python.
• Proper indentation is mandatory and ensures program readability.

Example:

# Example of proper indentation


if True:
print("Indented block") # Correct

19. Explain Functions with a Suitable Example


Definition:

Functions are reusable blocks of code that perform a specific task.

Syntax:

def function_name(parameters):
# code block
return value
Example:

def greet(name):
return f"Hello, {name}!"

print(greet("Alice"))

20. Discuss Python Modules


• Definition: A module is a file containing Python code that can be
imported into other programs.
• Use: To reuse code, organize functionality, and improve
maintainability.

Example:

# Importing math module


import math
print(math.sqrt(16)) # Using sqrt function from math module

21. Explain the break and continue with an Example


• break Statement: Exits the loop immediately, regardless of the
loop's condition.
• continue Statement: Skips the current iteration and moves to the
next iteration of the loop.

Example:

# Example of break
for i in range(1, 6):
if i == 3:
break # Exits the loop when i is 3
print(f"Break Example - Value: {i}")
# Example of continue
for i in range(1, 6):
if i == 3:
continue # Skips the iteration when i is 3
print(f"Continue Example - Value: {i}")

22. Explain Variables in Python with an Example


• Definition: Variables are named storage locations used to hold
data.
• Characteristics:
o No explicit type declaration is needed.
o Dynamically typed.

Example:

x = 10 # Integer variable
y = 3.14 # Float variable
name = "Alice" # String variable
print(x, y, name)

23. Explain in and not in in Python with an Example


• in: Checks if a value is present in a collection.
• not in: Checks if a value is not present in a collection.

Example:

my_list = [1, 2, 3, 4]
print(2 in my_list) # True
print(5 not in my_list) # True

24. Describe the Use of Type Casting in Python with an


Example
• Definition: Converting one data type to another is called type
casting.
• Explicit Casting:
o Use functions like int(), float(), str().

Example:

# Type Casting Example


x = "10" # String
y = int(x) # Converting string to integer
print(type(y), y)

25. Describe the pass in Python with an Example


• Definition: The pass statement is a placeholder for future code.
• Use Case: To write empty blocks without causing syntax errors.

Example:

if True:
pass # Placeholder for future implementation

26. Explain the Branching Statement with an Example


• Definition: Branching statements like if, if-else, and if-elif-
else control program flow based on conditions.
Example:

# Branching Example
num = 5
if num > 0:
print("Positive")
else:
print("Non-positive")

27. Discuss Sets in Python


• Definition: Sets are unordered collections of unique items.
• Characteristics:
o Defined using {}.
o No duplicate elements.
o Supports mathematical operations like union and
intersection.

Example:

my_set = {1, 2, 3, 3}
print(my_set) # {1, 2, 3}

28. Describe the for Loop in Detail with Example


• Definition: The for loop iterates over a sequence.

Syntax:

for variable in sequence:


# code block
Example:

# For loop example


for i in range(5):
print(i)

29. Explain the Term Read Input from the Console and Output
Operations
Input:

• Reading data using input().

Output:

• Displaying data using print().

Example:

# Input and Output example


name = input("Enter your name: ")
print(f"Hello, {name}")

30. Discuss the Following Math Module Functions


i. math.sqrt()

• Returns the square root of a number.


• Example:

import math
print(math.sqrt(16)) # Output: 4.0

ii. math.tan()

• Returns the tangent of an angle (in radians).


• Example:

import math
print(math.tan(math.pi/4)) # Output: 1.0

iii. math.sin()

• Returns the sine of an angle (in radians).


• Example:

import math
print(math.sin(math.pi/2)) # Output: 1.0

iv. math.prod()

• Returns the product of an iterable.


• Example:

import math
nums = [1, 2, 3, 4]
print(math.prod(nums)) # Output: 24
31. Explain Exception Handling Using Python

• Definition: Exception handling is a mechanism to handle runtime errors gracefully


without crashing the program.
• Key Keywords:
o try: Defines a block of code to test for errors.
o except: Handles the exception.
o finally: Executes code, regardless of exceptions.
o raise: Manually triggers an exception.

Example:

try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
finally:
print("Execution completed.")

32. Explain Dictionaries in Python with a Suitable Example

• Definition: A dictionary is a collection of key-value pairs. Keys must be unique.


• Syntax: {key: value}.

Example:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


print(my_dict["name"]) # Accessing value by key
my_dict["age"] = 26 # Updating value
print(my_dict)

33. Discuss str, int, float, complex

• str: Represents a sequence of characters.


o Example: s = "Hello"
• int: Represents whole numbers.
o Example: x = 10
• float: Represents decimal numbers.
o Example: y = 3.14
• complex: Represents complex numbers with real and imaginary parts.
o Example: z = 2 + 3j
34. Datatypes in Python with Example

• Common Data Types:


o Numeric: int, float, complex.
o Sequence: str, list, tuple.
o Mapping: dict.
o Set Types: set, frozenset.
o Boolean: bool.

Example:

x = 10 # int
y = 3.14 # float
z = "Hello" # str
lst = [1, 2, 3] # list
tpl = (1, 2, 3) # tuple
dct = {"key": "value"} # dict

35. Explain the Comparison Operator with an Example

• Definition: Used to compare values. Returns True or False.

Operators:

• ==, !=, <, >, <=, >=.

Example:

x = 5
y = 10
print(x == y) # False
print(x < y) # True
36. Discuss Conditional Control Structures in Detail

• Definition: These control the flow of execution based on conditions.

Types:

• if: if x > 0:
print("Positive")

• if-else: if x > 0:
print("Positive")
else:
print("Non-positive")

• if-elif-else: if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

37. Discuss Lists in Python with Example

• Definition: Lists are ordered, mutable collections.

Example:

my_list = [1, 2, 3, 4]
my_list.append(5) # Adding an element
print(my_list)
38. Implement a Python Program to Demonstrate File Operations
Example:

# File operations
with open("example.txt", "w") as file:
file.write("Hello, world!")

with open("example.txt", "r") as file:


content = file.read()
print(content)

39. Discuss Strings in Detail

• Definition: Strings are immutable sequences of characters.


• Features:
o Support indexing and slicing.
o Methods like upper(), lower(), strip(), split().

Example:

s = "Hello, Python!"
print(s.upper()) # HELLO, PYTHON!
print(s[0:5]) # Hello

40. Implement Python Program to Check Whether a String is Palindrome


or Not
Example:

# Palindrome check
string = input("Enter a string: ")
if string == string[::-1]:
print("Palindrome")
else:
print("Not a palindrome")

41. Explain Built-in Modules with Suitable Example

• Definition: Predefined modules with reusable code.

Example:

import math
print(math.sqrt(16)) # 4.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10

42. Explain try, catch, finally, and raise with Implementation

• try: Contains the code to test.


• except (catch): Handles exceptions.
• finally: Executes regardless of exceptions.
• raise: Triggers an exception.

Example:

try:
x = int(input("Enter a number: "))
if x < 0:
raise ValueError("Negative numbers are not allowed")
except ValueError as e:
print(f"Error: {e}")
finally:
print("Program ended.")

You might also like