0% found this document useful (0 votes)
10 views

python programming question bank unit wise by Rupesh ✓

The document provides an introduction to Python, covering its definition, history, features, and various programming concepts. It explains key topics such as data types, functions, control flow statements, and string formatting methods. Additionally, it discusses the importance of indentation, variable declaration, and the differences between mutable and immutable types.

Uploaded by

Prince Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

python programming question bank unit wise by Rupesh ✓

The document provides an introduction to Python, covering its definition, history, features, and various programming concepts. It explains key topics such as data types, functions, control flow statements, and string formatting methods. Additionally, it discusses the importance of indentation, variable declaration, and the differences between mutable and immutable types.

Uploaded by

Prince Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Unit 1 introduction (python)

2 marks question with answer : ✓


1. Define Python: Python is a high-level, interpreted, and general-
purpose programming language known for its readability and
simplicity. It supports multiple programming paradigms like
procedural, object-oriented, and functional programming.

2. Who developed Python? Python was developed by Guido van


Rossum and first released in 1991.

3. What are the benefits of using Python? The benefits of Python


include simplicity and readability, large standard library, cross-
platform compatibility, strong community support, and suitability
for rapid development of applications.

4. What is Python interpreter? The Python interpreter is a program


that reads and executes Python code. It converts Python code into
machine language so that the computer can execute it.

5. What are the main features of Python? The main features of


Python include its simplicity, readability, dynamic typing, high-level
data structures, extensive standard library, and support for
multiple programming paradigms.

6. What is the use of indentation feature in Python? Indentation in


Python is used to define the block of code. Unlike other
programming languages that use braces {}, Python uses indentation
to indicate code blocks, making it more readable.

7. Why Python is called an interpreted language? Python is called


an interpreted language because its code is executed line by line by
the Python interpreter, rather than being compiled into machine
code beforehand.

8. What is the process of executing a Python code? The Python code


is first read by the Python interpreter. It is then translated into
intermediate bytecode and executed by the Python Virtual Machine
(PVM).

9. List out the applications of Python: Python is used in web


development, data analysis, artificial intelligence, machine
learning, automation, game development, scientific computing, and
software development.

10. What is the purpose of type() function in Python? The type()


function in Python is used to determine the type of an object. It
returns the class type of the given object.

11. Explain the difference between set and frozenset data types in
Python.
Set: A set is a mutable collection that contains unique elements. It
allows modifications like adding or removing elements.
Frozenset: A frozenset is an immutable version of a set. Once
created, elements cannot be added or removed from it.

12. What are mutable and immutable data types in Python?


Mutable data types: These can be changed after creation, like lists,
sets, and dictionaries.
Immutable data types: These cannot be changed after creation, like
strings, tuples, and frozensets.

13. What is type conversion in Python?


Type conversion is the process of converting one data type into
another. This can be done explicitly using functions like int(),
float(), str(), etc.

14. What is the function used to print output in Python?


The print() function is used to display output to the console in
Python.

15. What is % operator in string formatting in Python? The %


operator is used in Python for string formatting. It allows
embedding values into a string by replacing placeholders with
values. For example:
name = "Alice"
print
("Hello, %s!" % name)Here are the answers to the next set of 2-
mark questions related to Python:

16. Give the difference between break and continue statement in


Python:
Break statement: It is used to terminate the current loop and exit
from it completely.
Continue statement: It is used to skip the current iteration of the
loop and proceed to the next iteration.

17. Define function. List the types of functions in Python:


A function is a block of code that performs a specific task and can
be reused throughout the program.
Types of functions in Python:
Built-in functions: Functions that are predefined in Python (e.g.,
print(), len(), type()).
User-defined functions: Functions defined by the user using the def
keyword.
Lambda functions: Small anonymous functions defined using the
lambda keyword.

18. List out the advantages of functions:


Code reusability
Better organization and modularization
Easier debugging and testing
Helps in reducing code duplication
Improves readability and maintainability of code

19. What are built-in functions and user-defined functions?


Built-in functions: These are functions that are available in Python
by default, without needing to define them (e.g., abs(), sum(),
input()).
User-defined functions: These are functions that are created by the
user using the def keyword to perform specific tasks.

20. Give the syntax for defining a function:


def function_name(parameters):
# function body
return value
21. What are void functions?
Void functions are functions that do not return any value. They
perform a task but do not return any result to the caller.

22. What are local and global variables?


Local variables: Variables declared inside a function. They are
accessible only within that function.
Global variables: Variables declared outside any function. They can
be accessed from any part of the program.

23. Define module: A module is a file containing Python definitions


and statements. It allows organizing code logically into separate
files, and it can be imported to be reused in other Python programs.

24. Give the difference between actual and formal parameters:


Actual parameters (arguments): These are the values or variables
passed to a function when it is called.
Formal parameters: These are the variables listed in the function
definition that accept the values passed

25. Define string: A string is a sequence of characters enclosed


within single, double, or triple quotes. It is used to represent textual
data in Python.

26. What is slicing?


Slicing in Python is a way to extract a portion (substring) from a
string, list, or tuple. It is done using the colon : operator. For
example:
s = "Hello"
print(s[1:4]) # Outputs "ell"
27. What is the purpose of the join method?
The join() method in Python is used to concatenate elements of an
iterable (like a list or tuple) into a single string, with a specified
separator. For example:
words = ["Python", "is", "awesome"]
result = " ".join(words) # Outputs "Python is awesome"
through the actual parameters.

5/8 marks question ✓:

1. Write the history of Python:


Python was created by Guido van Rossum in 1980 at the Centrum
Wiskunde & Informatica (CWI) in the Netherlands. The first
version, Python 0.9.0, was released in February 1991. Python's
design philosophy emphasizes code readability and simplicity. It
was influenced by languages like ABC, C, and Unix shell scripting.
Python's development continued steadily, and it became one of the
most popular programming languages, with major releases such as
Python 2.0 in 2000 and Python 3.0 in 2008, which introduced many
backward-incompatible changes.

2. Explain the concept of tokens in Python:


Tokens are the smallest units of a program in Python. They are the
building blocks of the Python language and include:
Keywords: Reserved words in Python like if, else, while.
Identifiers: Names used to identify variables, functions, classes, etc.
Literals: Constant values like 5, "hello", etc.
Operators: Symbols like +, -, *, etc., that perform operations.
Punctuation: Symbols like (), {}, [], used for grouping or defining
structure.

3. What are the rules for naming an identifier?


The rules for naming an identifier in Python are:
It can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
It must begin with a letter or an underscore.
It cannot start with a digit.
Python identifiers are case-sensitive (e.g., var and Var are
different).
It cannot be a Python keyword (e.g., if, while, return).

4. What are keywords? Explain with examples. Keywords are


reserved words in Python that have special meanings and cannot
be used as identifiers (variable names). They define the structure of
the Python language. Examples of keywords include:
if, else, elif (conditional statements)
for, while (loops)
def (function definition)
return (returning a value)
class (class definition)

5. What is a literal? Explain the different types of literals in Python


with examples.
A literal is a fixed value in Python code, directly represented in the
source code. The different types of literals are:
String literals: Represent a sequence of characters. Example:
"Hello", 'Python'.
Integer literals: Represent integer values. Example: 5, -3, 0.
Floating-point literals: Represent decimal numbers. Example: 3.14,
-2.5.
Boolean literals: Represent the two boolean values. Example: True,
False.
None literal: Represents the absence of a value. Example: None.

6. Explain Python variables in detail:


A variable in Python is a name associated with a value. It is used to
store data that can be accessed and modified throughout the
program. Variables do not need explicit declaration; they are
created when a value is assigned to them. Python variables are
dynamically typed, meaning the type of the variable is determined
at runtime. Example:
x = 10 # integer variable
name = "Alice" # string variable

7. Explain the concept of declaring and assigning a variable in


Python:
In Python, variables are declared and assigned values in one step.
There is no need to explicitly declare the type of a variable. The
value is assigned using the = operator. Example:
x = 10 # Variable 'x' is declared and assigned the value 10
y = "Hello" # Variable 'y' is assigned the string value "Hello"

8. Explain the operators in Python: Python supports various types


of operators:
Arithmetic operators: +, -, *, /, // (floor division), % (modulus), **
(exponentiation).
Comparison operators: ==, !=, >, <, >=, <=.
Logical operators: and, or, not.
Assignment operators: =, +=, -=, *=, /=, etc.
Membership operators: in, not in.
Identity operators: is, is not.
Bitwise operators: &, |, ^, ~, <<, >>.

9. Explain the use of statements and expressions in Python:


Expression: A combination of values, variables, and operators that
can be evaluated to produce a result. Example: 3 + 4.
Statement: A complete instruction that performs an action. It can
contain expressions. Example: x = 3 + 4 is a statement that assigns
the result of the expression 3 + 4 to variable x.

10. What is the difference between "in" and "not in" membership
operators in Python?
in: Returns True if the value is found in the specified iterable (like a
list, tuple, string). Example:
"a" in "apple" # Returns True
not in: Returns True if the value is not found in the specified
iterable. Example:
"z" not in "apple" # Returns True

11. What is the difference between "in" and "is" operators in


Python?
in: Checks if a value is present in an iterable (e.g., list, string).
is: Checks if two variables refer to the same object in memory
(identity comparison). Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # Returns False because they refer to different objects

12. Explain different types of data types in Python: Python has


several built-in data types:
Numeric types: int, float, complex.
Sequence types: list, tuple, range.
Text type: str.
Set types: set, frozenset.
Mapping type: dict.
Boolean type: bool.
Binary types: bytes, bytearray, memoryview.
None type: None.

13. How can you convert a string to integer in Python? You can use
the int() function to convert a string to an integer. Example:
s = "123"
n = int(s) # n will be 123 (integer)

14. Explain comments in Python and its purpose:


Comments in Python are used to add explanatory notes to the code
and make it more understandable. They are ignored by the
interpreter. Python supports single-line comments (using #) and
multi-line comments (using triple quotes ''' or """). Example:
# This is a single-line comment
'''
This is a multi-line comment
explaining the code.
'''

15. Discuss the importance of proper indentation in Python and


how it affects the code functionality:
Indentation in Python is crucial as it defines the block of code, such
as loops, functions, and conditionals. Python uses indentation
(whitespace) to group statements, and improper indentation will
result in a syntax error. Example:
if True:
print("Hello") # Correct indentation

16. Explain the different methods to accept input from the user in
Python:
The input() function is used to accept user input. It returns the
input as a string. To get other data typ
es, you can convert the input using functions like int(), float(), etc.
Example:
name = input("Enter your name: ")
age = int(input("Enter your age: "))

Here are the answers to the remaining questions:


17. What is the format() method and f-string in string formatting in
Python?
format() method: The format() method allows you to insert
variables into a string. It provides more flexibility than traditional
string concatenation. Example:
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
f-string (formatted string literals): Introduced in Python 3.6, f-
strings allow you to embed expressions inside string literals using
curly braces {} and prefix the string with f. Example:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)

18. Explain the various ways of string formatting in Python:


Using the % operator: A traditional method where placeholders are
used in a string and values are inserted using the % operator.
Example:
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)
Using str.format(): Provides more control over formatting, such as
specifying the order or naming placeholders. Example:
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
Using f-strings (formatted string literals): A concise and modern
way to format strings in Python. Example:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)

19. Why Python is called a dynamically typed language?


Python is called a dynamically typed language because the type of a
variable is determined at runtime, not at compile-time. You don't
need to declare the type of a variable explicitly. The interpreter
infers the type based on the assigned value. Example:
x = 10 # x is an integer
x = "Hello" # x is now a string

20. Explain the different types of control flow statements in Python


with examples:
Control flow statements in Python are used to control the execution
flow of a program.
Conditional statements (if, elif, else): Used to make decisions based
on conditions. Example:
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
Looping statements (for, while): Used to repeat a block of code.
Example (using for):
for i in range(5):
print(i)
Control statements (break, continue, pass): Used to alter the flow
inside loops. Example:
for i in range(5):
if i == 3:
break # Exits the loop when i is 3
print(i)

21. Explain the different types of decision-making control flow


statements in Python:
if statement: Used to check if a condition is true and execute the
corresponding block of code. Example:
if x > 0:
print("Positive number")
if-else statement: Checks a condition, and if it's true, it executes one
block of code; otherwise, it executes another block. Example:
if x > 0:
print("Positive number")
else:
print("Non-positive number")
if-elif-else statement: Checks multiple conditions. Example:
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

22. What is the use of nested if statements in Python?


Explain with examples. Nested if statements are used when you
need to check multiple conditions within a single if block. The
inner if statement is executed only if the outer if condition is true.
Example:
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")

23. What is the difference between for loop and while loop?
for loop: Iterates over a sequence (such as a list, tuple, or range)
and executes the block of code for each item in the sequence.
Example:
for i in range(5):
print(i)
while loop: Continues to execute the block of code as long as a
condition remains true. Example:
i=0
while i < 5:
print(i)
i += 1

24. Explain the types of if statements with suitable examples.


Simple if statement:
if x > 0:
print("Positive number")
if-else statement:
if x > 0:
print("Positive")
else:
print("Non-positive")
if-elif-else statement:
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

25. Explain the need for functions. Functions in Python are needed
for:
Code reusability: You can define a function once and reuse it
multiple times.
Modularization: Functions break down large programs into
smaller, manageable parts.
Organization: Functions improve code organization, making it
more readable and maintainable.
Avoiding code repetition: Functions allow you to write reusable
code blocks, reducing duplication.

26. Explain the types of functions in Python with suitable examples:


Built-in functions: Predefined functions in Python, like print(), len(),
abs(). Example:
print("Hello")
print(len([1, 2, 3]))
User-defined functions: Functions created by the user with the def
keyword. Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")

27. Explain max(), min(), len(), abs(), round(), pow(), sum(), eval(),
and exec() functions with an example:
max(): Returns the largest item in an iterable or the largest of two
or more arguments. Example: max(3, 5, 2) returns 5.
min(): Returns the smallest item in an iterable or the smallest of
two or more arguments. Example: min(3, 5, 2) returns 2.
len(): Returns the length of an object (e.g., list, string). Example:
len("Hello") returns 5.
abs(): Returns the absolute value of a number. Example: abs(-7)
returns 7.
round(): Rounds a floating-point number to the nearest integer or
to the specified number of decimal places. Example: round(3.14159,
2) returns 3.14.
pow(): Returns the power of a number. Example: pow(2, 3) returns
8.
sum(): Returns the sum of all items in an iterable. Example: sum([1,
2, 3]) returns 6.
eval(): Executes a string as a Python expression and returns the
result. Example: eval("3 + 5") returns 8.
exec(): Executes a dynamically created Python program (multi-line
strings). Example:
exec("x = 5\nprint(x)")

28. Explain the syntax of defining a function, function definition,


and calling a function with a suitable example:
Defining a function:
def function_name(parameters):
# function body
return result
Calling a function:
function_name(arguments)
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")

29. Explain passing arguments to functions with an example:


Arguments are passed to functions to provide input for the
function's operations. They can be passed as positional or keyword
arguments. Example:
def add(x, y):
return x + y
print(add(5, 3)) # Positional arguments
print(add(x=5, y=3)) # Keyword arguments

30. Explain void functions:


A void function is a function that does not return any value. It
performs an action but does not produce a result. Example:
def greet(name):
print(f"Hello, {name}!")

31. Explain keyword arguments and default arguments:


Keyword arguments: Arguments passed to a function by explicitly
specifying the parameter name. Example:
def greet(name, age):
print(f"Name: {name}, Age: {age}")
greet(name="
Alice", age=25)
Default arguments: Arguments that have a default value if not
provided by the caller. Example:
def greet(name, age=30):
print(f"Name: {name}, Age: {age}")
greet("Alice") # Age defaults to 30
greet("Bob", 35) # Age is set to 35

32. Write a note on lambda function.


A lambda function is a small anonymous function defined using the
lambda keyword. It can have any number of arguments, but only
one expression. The expression is evaluated and returned. Lambda
functions are often used for short, throwaway functions where
using a full def function would be unnecessarily verbose.
Example:
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8

33. Give the differences between modules, packages, and library in


Python.
Module: A module is a single Python file that contains functions,
variables, and classes. It is used to organize related code into
separate files. For example, math is a module.
Package: A package is a collection of modules stored in a directory.
It contains multiple modules and sub-packages, and is identified by
a special __init__.py file. A package helps in organizing the modules
into namespaces.
Library: A library is a collection of modules and packages that
provide functionality to perform a specific task. It can be as simple
as a module or as complex as a set of packages. For example, the
numpy library is a collection of modules for numerical operations.

34. Discuss about command line arguments.


Command-line arguments allow users to pass arguments to a
Python script when executing it from the terminal or command
prompt. These arguments can be accessed using the sys.argv list
from the sys module. The first item in sys.argv is the script name,
and the rest are the arguments passed.
Example:
import sys
print("Script name:", sys.argv[0])
print("Arguments passed:", sys.argv[1:])
To run this script:
python script.py arg1 arg2 arg3

35. How strings are created and stored in Python?


In Python, strings are created by enclosing characters in single
quotes (') or double quotes ("). Internally, Python stores strings as
sequences of characters, typically in memory using a data structure
called a string object. Strings are immutable, meaning their content
cannot be changed after they are created.
Example:
string1 = "Hello"
string2 = 'World'

36. Strings are immutable. Explain with an example?


Strings in Python are immutable, meaning their values cannot be
changed once they are created. If you try to modify a string directly,
it will result in an error or create a new string.
Example:
s = "Hello"
# Trying to change a character will raise an error
# s[0] = 'h' # Error: 'str' object does not support item assignment
# Instead, create a new string
s = "h" + s[1:]
print(s) # Output: "hello"

37. How to access characters in a string by index numbers?


In Python, you can access individual characters in a string using
indexing. The index starts from 0 for the first character, and
negative indices can be used to access characters from the end.
Example:
s = "Hello"
print(s[0]) # Output: H
print(s[-1]) # Output: o

38. Explain the traversing of a string with a suitable example.


Traversing a string means iterating over each character in the
string, usually using a loop. You can use a for loop to traverse
through a string.
Example:
s = "Hello"
for char in s:
print(char)
Output:
H
e
l
l
o

39. Explain basic string operations with an example.


Basic string operations in Python include concatenation, repetition,
slicing, and membership checking.
Example:
s1 = "Hello"
s2 = "World"
# Concatenation
s3 = s1 + " " + s2 # "Hello World"
print(s3)
# Repetition
s4 = s1 * 3 # "HelloHelloHello"
print(s4)
# Slicing
s5 = s1[1:4] # "ell"
print(s5)
# Membership checking
print("H" in s1) # True
print("z" not in s1) # True

40. Write a Python program to find the length of a string.


To find the length of a string, you can use the built-in len() function.
Example:
s = "Hello"
length = len(s)
print(f"Length of the string is: {length}")
Output:
Length of the string is: 5

41. What is recursion? Explain with a suitable example.


Recursion is a programming technique where a function calls itself
to solve a problem. A recursive function must have a base case that
terminates the recursion to prevent infinite calls.
Example:
def factorial(n):
if n == 0:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # Output: 120
Explanation:
factor
ial(5) calls factorial(4), which calls factorial(3), and so on, until it
reaches the base case factorial(0), which returns 1.

You might also like