0% found this document useful (0 votes)
7 views9 pages

Python notes

The document provides a comprehensive overview of programming fundamentals using Python, covering topics like strings, functions, object-oriented programming, and libraries such as NumPy and Pandas. It includes various types of questions categorized by marks, with detailed answers explaining concepts like string methods, function arguments, and OOP principles. Additionally, it discusses the use of libraries for data manipulation and visualization, emphasizing their features and operations.

Uploaded by

satvirnatt19
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)
7 views9 pages

Python notes

The document provides a comprehensive overview of programming fundamentals using Python, covering topics like strings, functions, object-oriented programming, and libraries such as NumPy and Pandas. It includes various types of questions categorized by marks, with detailed answers explaining concepts like string methods, function arguments, and OOP principles. Additionally, it discusses the use of libraries for data manipulation and visualization, emphasizing their features and operations.

Uploaded by

satvirnatt19
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/ 9

pfp_theory_ques_3736.

md 2025-05-11

Subject: Programming Fundamentals Using Python


Content

Strings questions

Functions questions

Object oriented Prog. & Classes questions

Topic: Strings and Regular Expressions

✦ 2 Marks Questions (Answer limit: 40–50 words)

1. What is a string in Python?


A string is an ordered sequence of characters enclosed in single, double, or triple quotes. It is
immutable in Python.

2. Mention any two string operations in Python.


Two basic string operations are concatenation (joining strings using +) and repetition (using * to repeat
a string multiple times).

3. What is the use of the re module?


The re module is used in Python for working with Regular Expressions. It helps perform pattern
matching and text manipulation.

4. Define meta characters in regular expressions.


Meta characters are special symbols like ., *, +, ?, [], ^, and $ used to define string patterns in regular
expressions.

5. What does the strip() method do?


The strip() method removes leading and trailing whitespaces from a string.

✦ 4 Marks Questions (Answer limit: 80–90 words)

1. Differentiate between isalpha() and isdigit() methods.


isalpha() checks if all characters in the string are alphabetic. isdigit() checks whether all characters
are digits. Both return False if the string contains spaces, symbols, or mixed characters.

2. Explain string slicing in Python.


Slicing allows extraction of substrings using string[start:end] syntax. Start index is inclusive, end is
exclusive. Negative indices are used to slice from the end of the string.

3. Write a short note on string immutability.


In Python, strings are immutable. Once created, the characters within a string cannot be changed. Any
modification results in a new string object.

4. What is the purpose of the find() and index() methods?


Both methods return the index of the first occurrence of a substring. The difference is find() returns -1
1/9
pfp_theory_ques_3736.md 2025-05-11

if not found, whereas index() raises a ValueError.

5. Write a short note on the split() and join() methods.


split() breaks a string into a list using a separator. join() combines list elements into a single string
using a separator.

✦ 6 Marks Questions (Answer limit: 120–150 words)

1. Explain any four string methods with examples.\

lower(): Converts to lowercase: 'Hello'.lower() → 'hello'


upper(): Converts to uppercase: 'hello'.upper() → 'HELLO'
replace(): Replaces substrings: 'apple'.replace('p','b') → 'abble'
count(): Counts occurrences: 'banana'.count('a') → 3

2. What are pattern matching methods in the re module?\

re.match(): Matches pattern at string start


re.search(): Searches for first match
re.findall(): Returns list of all matches
re.finditer(): Returns an iterator of match objects

3. Write a short note on string formatting in Python.


Python supports format() and f-strings for formatting. Example: "Name: {}, Age:
{}".format("Alice", 21) or f"Name: {name}, Age: {age}".

4. Differentiate between raw strings and normal strings.


Normal strings treat backslashes as escape characters. Raw strings (prefix r) ignore escape sequences,
making them ideal for regex. Example: r"\n" is a literal backslash and n.

5. Explain string comparison with examples.


String comparison uses relational operators (==, !=, <, >, etc.). It is case-sensitive and follows Unicode
order. 'apple' < 'banana' → True.

✦ 12 Marks Questions (Answer limit: 200–250 words)

1. Explain regular expressions in Python with meta characters and their usage.
Regular expressions (regex) allow complex pattern matching in strings. Python uses the re module for
regex operations. Common meta characters include:

.: Matches any character except newline


^ / $: Match start/end of string
[]: Matches character class
*, +, ?: Match 0+ / 1+ / 0-1 times
{m,n}: Match between m and n times
\: Escapes special characters
|: OR operator Example:

2/9
pfp_theory_ques_3736.md 2025-05-11

re.search(r"\d{3}-\d{2}-\d{4}", "My SSN is 123-45-6789")

This matches a U.S. SSN format.

2. What are compilation flags in the re module? Explain with examples.


Compilation flags modify regex behavior:

re.IGNORECASE (re.I): Case-insensitive matching


re.MULTILINE (re.M): ^ and $ match start/end of each line
re.DOTALL (re.S): . matches newline as well Example:

pattern = re.compile("hello", re.IGNORECASE)


pattern.search("HELLO world") # Match found

These flags enhance regex flexibility, especially in text data parsing.

3. Discuss various string operations in Python with examples.


Python supports many operations:

Concatenation: 'Hello' + 'World' → 'HelloWorld'


Repetition: 'Hi'*3 → 'HiHiHi'
Membership: 'a' in 'apple' → True
Length: len('Python') → 6
Slicing: 'Python'[1:4] → 'yth'
Comparison: 'abc' > 'Abc' → True These operations make string manipulation flexible and
powerful in Python.

Topic: Unit 4 - Functions and Modular Programming

✦ 2 Marks Questions (Answer limit: 40–50 words)

1. What is a function in Python?


A function is a block of reusable code that performs a specific task. It helps in breaking programs into
modular chunks.

2. What is the purpose of the return statement in a function?


The return statement ends the function execution and optionally sends back a value to the caller.

3. Define docstring in Python functions.


A docstring is a string literal specified in a function to describe its purpose. It is defined using triple
quotes at the beginning of the function body.

4. What is a lambda function?


A lambda function is an anonymous, single-expression function defined using the lambda keyword.

5. What are global variables?


Global variables are defined outside any function and can be accessed and modified within functions
3/9
pfp_theory_ques_3736.md 2025-05-11

using the global keyword.

✦ 4 Marks Questions (Answer limit: 80–90 words)

1. Differentiate between parameters and arguments.


Parameters are variables listed in the function definition, while arguments are the actual values passed
to the function during a call. For example:

def add(x, y): # x and y are parameters


return x + y
add(2, 3) # 2 and 3 are arguments

2. Explain keyword and default arguments with examples.


Keyword arguments specify parameter names during a call: func(x=10). Default arguments provide
default values in the definition: def func(x=5).

3. What are variable-length arguments?


Functions can accept varying numbers of arguments using *args for non-keyword and **kwargs for
keyword arguments.

def f(*args): print(args)


def f2(**kwargs): print(kwargs)

4. What is function composition?


Function composition is applying one function to the result of another. Example: f(g(x)). It allows
chaining functions for complex operations.

5. Explain fruitful and non-fruitful functions.


Fruitful functions return a value using return. Non-fruitful (void) functions do not return anything.

✦ 6 Marks Questions (Answer limit: 120–150 words)

1. Describe the syntax of defining and calling a function with an example.


A function is defined using the def keyword:

def greet(name):
return "Hello, " + name
print(greet("Alice"))

Here, greet is called with the argument "Alice".

2. Explain lambda functions and their use with map() and filter().
Lambda functions are anonymous and used for simple tasks. map() applies a function to all elements of

4/9
pfp_theory_ques_3736.md 2025-05-11

an iterable, while filter() selects elements based on a condition.

nums = [1, 2, 3]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x%2 == 0, nums))

3. What is recursion? Explain with an example.


Recursion is when a function calls itself to solve a smaller problem. Example:

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

It’s useful in tasks that can be broken down into similar subtasks.

4. Differentiate between local and global variables.


Local variables exist within a function. Global variables exist throughout the program. To modify a
global variable inside a function, use the global keyword.

5. Explain how modules are created and imported.


A module is a .py file containing Python code. It can be imported using import module_name or from
module_name import item. This supports code reuse.

✦ 12 Marks Questions (Answer limit: 200–250 words)

1. Explain all types of function arguments in Python with examples.


Python supports:

Required arguments: Must be provided.

def add(a, b): return a + b


add(2, 3)

Keyword arguments: Passed by name.

add(b=3, a=2)

Default arguments: Defaults used when not provided.

def greet(name="Guest"):
return "Hello, " + name

5/9
pfp_theory_ques_3736.md 2025-05-11

Variable-length arguments:

*args for non-keyword


**kwargs for keyword

def f(*args, **kwargs): print(args, kwargs)

These argument types allow flexibility and control in function calls.

2. Discuss the use of lambda functions, map(), and filter() with examples.\

Lambda creates anonymous functions.


map() applies a function to each element.
filter() filters elements meeting a condition. Example:

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

These tools are concise and efficient for functional programming in Python.

3. Explain the concept of modules in Python. How are built-in modules like datetime used?
A module is a file containing Python definitions and functions. Built-in modules provide essential tools.
The datetime module handles dates and times.

import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

You can also use from datetime import datetime. Custom modules are created by saving functions
in a .py file and importing them in other scripts. Modules promote reusability and modularity.

Topic: Object-Oriented Programming, NumPy, Matplotlib, Pandas

✦ 2 Marks Questions (Answer limit: 40–50 words)

1. What is object-oriented programming?


Object-oriented programming (OOP) is a programming paradigm based on the concept of objects that
contain both data and methods.

2. Define a class in Python.


A class is a blueprint for creating objects, defined using the class keyword.

3. What is the purpose of the self variable in Python classes?


self refers to the current instance of the class and is used to access instance variables and methods.

6/9
pfp_theory_ques_3736.md 2025-05-11

4. What is NumPy?
NumPy is a Python library used for numerical computations, providing support for arrays and matrices.

5. Name any two plots available in Matplotlib.


Line Plot and Bar Plot are two types of plots available in Matplotlib.

✦ 4 Marks Questions (Answer limit: 80–90 words)

1. Differentiate between procedural programming and object-oriented programming.


Procedural programming focuses on functions and the sequence of actions, while OOP focuses on
objects and encapsulates data and behavior. OOP supports inheritance, encapsulation, and
polymorphism, unlike procedural programming.

2. Explain the use of constructors in Python classes.


A constructor initializes object attributes during object creation. The __init__() method is a special
constructor method automatically called when an object is instantiated.

3. What is data hiding in OOP?


Data hiding restricts direct access to object data using private variables (prefix _ or __). This enhances
security and encapsulation.

4. What are NumPy arrays?


NumPy arrays are homogeneous, multi-dimensional data structures used for fast mathematical
computations.

5. Explain the use of scatter plots.


A scatter plot displays data points on a 2D plane, showing relationships or correlations between two
variables.

✦ 6 Marks Questions (Answer limit: 120–150 words)

1. Explain the concept of classes and objects with an example.


A class is a blueprint, and an object is an instance of that class.

class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "Hello, " + self.name

p1 = Person("Alice")
print(p1.greet())

Here, Person is the class, and p1 is an object.

2. Discuss the __init__() method and the role of self.


__init__() is the constructor that initializes object data. self represents the instance calling the

7/9
pfp_theory_ques_3736.md 2025-05-11

method, enabling access to attributes and other methods.

3. Describe line plot and bar plot in Matplotlib.


Line plot connects data points with lines, useful for trends over intervals. Bar plot represents data with
rectangular bars. Example:

plt.plot(x, y) # line
plt.bar(x, y) # bar

4. Explain how to create NumPy arrays and perform operations.


NumPy arrays can be created using np.array(). Operations include addition, multiplication, slicing,
and reshaping.

import numpy as np
arr = np.array([1, 2, 3])
arr2 = arr * 2

5. Write a note on Pandas in Python.


Pandas is a data manipulation and analysis library. It provides two key structures: Series and DataFrame.
It supports operations like filtering, grouping, and aggregating.

✦ 12 Marks Questions (Answer limit: 200–250 words)

1. Explain OOP concepts with examples: encapsulation, inheritance, polymorphism.\

Encapsulation: Bundles data and methods. Uses private variables.

Inheritance: Child class inherits from parent class.

class Animal: pass


class Dog(Animal): pass

Polymorphism: Same method behaves differently for different classes.

def area(shape): return shape.area()

These features enhance modularity, code reuse, and flexibility.

2. Describe the features and operations of NumPy arrays with examples.


NumPy arrays are fast, memory-efficient containers for large datasets. Key features:

Multi-dimensional arrays
Vectorized operations

8/9
pfp_theory_ques_3736.md 2025-05-11

Broadcasting
Array slicing

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a.shape, a[0, 1])

Operations include arithmetic, statistical functions (np.mean, np.sum), reshaping, and matrix
multiplication.

3. Explain different types of plots in Matplotlib with syntax and examples.\

Line Plot: plt.plot(x, y)


Scatter Plot: plt.scatter(x, y)
Bar Plot: plt.bar(x, y)
Histogram: plt.hist(data)
Pie Chart: plt.pie(sizes, labels=labels) These visualizations are used for trends,
comparisons, distributions, and proportions. Example:

import matplotlib.pyplot as plt


plt.plot([1, 2], [3, 4])
plt.show()

Matplotlib helps in analyzing and presenting data effectively.

4. What is Pandas? Explain Series and DataFrame with examples.


Pandas is a Python library for data analysis.

Series: One-dimensional labeled array.

import pandas as pd
s = pd.Series([10, 20, 30])

DataFrame: Two-dimensional table with rows and columns.

data = {'A': [1, 2], 'B': [3, 4]}


df = pd.DataFrame(data)

Pandas supports reading from files, filtering, aggregation, and more for data wrangling.

9/9

You might also like