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

Python Theory Question and Answer 1

The document provides a comprehensive overview of Python concepts, including multiline statements, functions, modules, operators, and data types. It covers various programming constructs such as algorithms, file handling, and recursion, along with practical examples and code snippets. Additionally, it explains the differences between data structures like lists and tuples, and outlines the features and functionalities of Python programming.

Uploaded by

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

Python Theory Question and Answer 1

The document provides a comprehensive overview of Python concepts, including multiline statements, functions, modules, operators, and data types. It covers various programming constructs such as algorithms, file handling, and recursion, along with practical examples and code snippets. Additionally, it explains the differences between data structures like lists and tuples, and outlines the features and functionalities of Python programming.

Uploaded by

john28223672
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

PYTHON THEORY QUESTION AND ANSWER

2 Mark question:-
a) What is a multiline statement?
A multiline statement in Python is a statement that spans multiple
lines. You can create one using the backslash (\) at the end of a line
or by enclosing the statement in parentheses (), brackets [], or braces
{}.

b) What is a function? Mention the type of function and use.


A function is a block of reusable code that performs a specific task.
Types of functions:
 Built-in functions: e.g., len(), print()
 User-defined functions: Created using the def keyword
Use: Functions improve code reuse, readability, and modularity.

c) What is meant by module in Python?


A module is a file containing Python code (functions, classes,
variables) that can be imported and reused in other programs.
Example: math, random.

d) What is the use of dir() function?


The dir() function returns a list of valid attributes (variables, methods,
etc.) for an object or module.

e) Which operators does Python support?


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

f) What is an Arithmetic operator?


Arithmetic operators perform mathematical operations like addition
(+), subtraction (-), multiplication (*), division (/), modulus (%),
exponentiation (**), and floor division (//).

g) How to open a new file in Python?


Use the open() function:
python
CopyEdit
file = open("filename.txt", "w") # "w" for write, "r" for read, "a" for
append

h) Define Algorithm.
An algorithm is a step-by-step procedure or set of rules designed to
solve a specific problem or perform a task.

i) What is meant by value in Python?


A value is the data assigned to a variable or constant. It can be of
types like integers, strings, floats, etc. Example: x = 5 (value is 5).

j) What is meant by array?


An array is a collection of items stored at contiguous memory
locations, typically of the same data type. In Python, arrays can be
created using the array module or more commonly with list or
NumPy arrays.

k) Define anonymous function.


An anonymous function in Python is a function defined without a
name using the lambda keyword. Example:
python
CopyEdit
square = lambda x: x * x

l) What do you mean by indentation in Python?


Indentation refers to the spaces at the beginning of a code line. In
Python, indentation determines the block of code and is critical for
defining loops, functions, conditionals, etc.
m) Define Python.
Python is a high-level, interpreted, general-purpose programming
language known for its simplicity and readability. It supports multiple
programming paradigms including object-oriented, procedural, and
functional programming.

n) What are keywords?


Keywords are reserved words in Python that have special meaning
and cannot be used as identifiers (variable names). Examples: if, else,
while, def, return.

o) What is meant by Python numbers?


Python numbers refer to numeric data types used in Python:
 int (integers): Whole numbers (e.g., 5, -2)
 float (floating-point): Decimal numbers (e.g., 3.14)
 complex: Numbers with a real and imaginary part (e.g., 2 + 3j)

p) List some built-in modules in Python.


Some commonly used built-in modules include:
 math – for mathematical functions
 random – for generating random numbers
 datetime – for working with dates and times
 os – for interacting with the operating system
 sys – for system-specific parameters and functions

q) What is meant by recursion?


Recursion is a programming technique where a function calls itself to
solve a problem. It typically includes a base case and a recursive case
to avoid infinite loops.
Example: Calculating factorial using recursion.

r) Define MATPLOTLIB library.


Matplotlib is a Python library used for data visualization. It allows the
creation of static, animated, and interactive plots in Python. The
most commonly used module in it is pyplot, used to plot graphs like
line charts, bar charts, histograms, etc.

s) difference between if else conditions?


if Condition:
 Executes a block of code only if the condition is true.
 If the condition is false, nothing happens.
if-else Condition:
 Executes one block of code if the condition is true,
 and another block if the condition is false.
t) what is python keyword?
Some common keywords include:
 if, else, elif – for conditional statements
 for, while – for loops
 def, return – for defining and returning from functions
 class – for defining a class
 True, False, None – special constant values
 import, from, as – for importing modules
 try, except, finally – for exception handling

U) what is tuple in python?


 Ordered: Items have a defined order
 Immutable: Once created, you cannot change, add, or remove
items
 Allow duplicates: You can have repeated values

V) what is lambda function in pyhton?


A lambda function in Python is an anonymous (nameless), one-line
function defined using the lambda keyword.
It is used when you need a simple function for a short period of
time.
W) define file handling and its importance in python?
File handling in Python refers to the process of reading from and
writing to files on your computer. Python provides a set of built-in
functions and methods for interacting with files.
Mode in file:-
 "r": Read (default mode). Opens the file for reading.
 "w": Write. Opens the file for writing (creates a new file if it
doesn't exist or truncates it if it does).
 "a": Append. Opens the file for appending (creates a new file if
it doesn't exist).
 "b": Binary. Used for binary files.
 "x": Exclusive creation. Creates a new file but fails if the file
already exists.

4 or 5 mark question:-
a) Explain the operators in Python:
Bitwise Operators
These operators work on the binary representation of integers:
 & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
Example:
python
a=5 # 0101
b=3 # 0011
print(a & b) # Output: 1
Logical Operators
Used to combine conditional statements:
 and, or, not
Example:
python
x = True
y = False
print(x and y) # Output: False
Membership Operators
Used to check if a value is a member of a sequence (like list, string,
etc.):
 in, not in
Example:
python
x = [1, 2, 3]
print(2 in x) # Output: True
Identity Operators
Used to compare the memory location of two objects:
 is, is not
Example:
python
a = [1, 2]
b=a
print(a is b) # Output: True
b) What is the difference between list and tuple in Python (with
example)?
Feature List Tuple
Mutable (can be Immutable (cannot be
Mutability
changed) changed)
Syntax [] ()
Performance Slightly slower Faster than lists
When items need to
Use case When fixed data is needed
change
Example:
python
my_list = [1, 2, 3]
my_list[0] = 10 # Allowed

my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Not allowed (will raise an error)

c) Explain Features of Python:


1. Easy to learn and read
2. Interpreted language – no need for compilation
3. High-level language
4. Dynamically typed – no need to declare variable types
5. Object-oriented
6. Extensive standard libraries
7. Cross-platform compatibility
8. Supports multiple programming paradigms – procedural,
functional, OOP

d) Describe the Input, Output and Import Functions


 Input Function:
Used to take input from the user.
python
name = input("Enter your name: ")
 Output Function:
Used to display output to the user.
python
print("Hello", name)
 Import Function:
Used to import modules or libraries into the program.
python
import math
print(math.sqrt(16))

e) Explain the mutable data types in Python:


Mutable data types are those that can be changed after creation.
 List:
python
a = [1, 2, 3]
a[0] = 10 # List modified
 Dictionary:
python
d = {"name": "Alice"}
d["name"] = "Bob" # Dictionary modified
 Set:
python
s = {1, 2, 3}
s.add(4) # Set modified
Immutable types include int, float, str, and tuple.
f) Explain Directories in Python (mkdir(), chdir(), getcwd(), rmdir())
These functions are part of Python’s os module, used for directory
operations:
 mkdir(path): Creates a new directory at the given path.
python
import os
os.mkdir("new_folder")
 chdir(path): Changes the current working directory to the
specified path.
python
os.chdir("new_folder")
 getcwd(): Returns the current working directory.
print(os.getcwd())
 rmdir(path): Removes (deletes) the specified empty directory.
os.rmdir("new_folder")

g) Python Program to Find Area and Perimeter of a Triangle


a = float(input("Enter side A: "))
b = float(input("Enter side B: "))
c = float(input("Enter side C: "))

# Perimeter
perimeter = a + b + c

# Semi-perimeter
s = perimeter / 2

# Area using Heron's formula


area = (s * (s - a) * (s - b) * (s - c)) ** 0.5

print("Perimeter of Triangle:", perimeter)


print("Area of Triangle:", area)

g) Program to Find the Sum of Square Roots of Any Three Number


import math

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

sum_sqrt = math.sqrt(a) + math.sqrt(b) + math.sqrt(c)


print("Sum of square roots:", sum_sqrt)

h) Difference Between Intermediate Mode and Script Mode


Feature Intermediate Mode Script Mode
For quick testing and For writing and saving long
Use
interactive execution programs
How it Line by line in the Python shell Full script is executed at
runs or terminal once
File No – runs commands
Yes – saved as a .py file
saved? temporarily
Ideal for Testing small snippets of code Writing full programs

i) Python Program to Print the Pattern


for i in range(1, 6):
print("* " * i)
Output:
*
**
***
****
*****

10 mark question:-

a) i) Explain briefly constant, variables, expression, keywords and


statements available in python.
i) Explanation of Python Concepts [5 Marks]
 Constant: A constant is a value that does not change during the
execution of a program. Python does not have built-in constant
types, but by convention, constants are written in uppercase
(e.g., PI = 3.14).
 Variable: A variable is a named location in memory used to
store data. Example
age = 25
 Expression: An expression is a combination of variables,
constants, operators, and functions that are evaluated to
produce a result. Example:
result = a + b * c
 Keywords: These are reserved words in Python used for special
purposes. They cannot be used as variable names. Examples: if,
for, while, def, class, etc.
 Statement: A statement is a complete line of code that
performs some action. Example:
print("Hello") # print statement

ii) Python Program for Fibonacci Series


n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
iii) What is Tuple?
A tuple is an immutable, ordered collection of items in Python.
Tuples are defined using parentheses ().
Example:
my_tuple = (1, 2, 3)
Tuples cannot be modified after creation, unlike lists.

OR
b)
i) Python Programs
a) Program to Find the Sum of n Natural Numbers
n = int(input("Enter a number: "))
sum_n = n * (n + 1) // 2
print("Sum of first", n, "natural numbers is:", sum_n)
b) Program to Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)

ii) What is a Flowchart? Basic Design Structures


A flowchart is a graphical representation of an algorithm or process.
It uses various symbols to represent different actions or steps.
Basic Flowchart Design Structures:
1. Sequence – Straightforward execution of steps in order.
2. Decision (Selection) – A decision point (like if-else) represented
by a diamond.
3. Loop (Iteration) – Repeated execution using loops (while, for)
represented with arrows looping back.
Symbols:
 Oval – Start/End
 Rectangle – Process
 Diamond – Decision
 Arrow – Flow of control

iii) What is Meant by Python String?


A string in Python is a sequence of characters enclosed in single (') or
double (") quotes.
Example:
text = "Hello, World!"
Strings are immutable, and Python provides many built-in methods
to work with them, such as upper(), lower(), replace(), etc.

You might also like