1 .
Explain user-defined functions in Python with
suitable examples ?
A user-defined function in Python is a function created by the
programmer to perform a specific task. Instead of writing the same code
multiple times, functions help in reusing code, making programs easier
to understand and maintain.
Python provides built-in functions like print() and len(), but programmers
can also create their own functions using the def keyword.
Syntax of a User-Defined Function
def function_name(parameters):
# Function body
statements
return value
Components of a Function
1. def keyword – Used to define a function.
2. Function name – Name given to the function.
3. Parameters – Inputs passed to the function (optional).
4. Function body – Code to be executed.
5. Return statement – Returns a value (optional).
Types of User-Defined Functions
1. Function Without Arguments and Without Return Value
This type of function neither accepts arguments nor returns a value.
Example:
def display():
print("Welcome to Python Programming")
display()
Output:
Welcome to Python Programming
Explanation:
The function display() only prints a message and does not take any input
or return any output.
2. Function With Arguments and Without Return Value
This type accepts values as arguments but does not return anything.
Example:
def add(a, b):
sum = a + b
print("Sum =", sum)
add(10, 20)
Output:
Sum = 30
Explanation:
The values 10 and 20 are passed as arguments to the function.
3. Function Without Arguments and With Return Value
This type does not take input but returns a value.
Example:
def message():
return "Hello Python"
print(message())
Output:
Hello Python
Explanation:
The function returns a string value.
4. Function With Arguments and With Return Value
This type takes arguments and returns a value.
Example:
def multiply(x, y):
return x * y
result = multiply(5, 4)
print("Multiplication =", result)
Output:
Multiplication = 20
Explanation:
The function takes two values, multiplies them, and returns the result.
Advantages of User-Defined Functions
1. Code Reusability: Same function can be called many times.
2. Modularity: Large programs are divided into smaller functions.
3. Easy Maintenance: Changes can be made easily.
4. Reduces Complexity: Makes programs simpler.
5. Improves Readability: Code becomes well-structured.
6. Easy Testing and Debugging: Errors are easier to locate.
Disadvantages of User-Defined Functions
1. Too many functions may make the program complex.
2. Improper use of functions may reduce readability.
3. Slight increase in execution time due to function calls.
2 . Describe recursion function in Python with an
example program ?
A recursive function is a function that calls itself in order to solve a
problem. Recursion is useful when a problem can be divided into smaller
subproblems of the same type.
A recursive function contains:
1. Base Case – The condition that stops the function from calling itself
repeatedly.
2. Recursive Case – The part where the function calls itself.
Syntax:
def function_name():
if condition: # Base case
return value
else:
return function_name() # Recursive call
Example Program: Factorial of a Number using Recursion
The factorial of a number is calculated as:
n! = n × (n-1) × (n-2) × ... × 1
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Program:
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
num = int(input("Enter a number: "))
result = factorial(num)
print("Factorial =", result)
Output:
Enter a number: 5
Factorial = 120
3 . Write a Python program to demonstrate different
types of arguments ?
Arguments are the values passed to a function when it is called. Python
supports different types of arguments to make functions more flexible and
reusable. The different types of arguments in Python are:
1. Positional Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable-Length Arguments (*args)
1. Positional Arguments
In positional arguments, the values are passed to the function in the same
order as the parameters defined in the function.
Example Program
def student(name, age):
print("Name:", name)
print("Age:", age)
student("Maria", 18)
Output
Name: Maria
Age: 18
Explanation
Here, "Maria" is assigned to name and 18 is assigned to age according to
their position.
2. Keyword Arguments
In keyword arguments, values are passed using parameter names. The
order of arguments does not matter.
Example Program
def employee(name, salary):
print("Name:", name)
print("Salary:", salary)
employee(salary=25000, name="John")
Output
Name: John
Salary: 25000
Explanation
Here, arguments are passed using keywords (salary= and name=), so the
order can be changed.
3. Default Arguments
Default arguments are used when a parameter has a default value. If no
value is given during function call, the default value is used.
Example Program
def greet(name, message="Welcome"):
print(message, name)
greet("Maria")
greet("John", "Good Morning")
Output
Welcome Maria
Good Morning John
Explanation
In the first function call, "Welcome" is used as the default message. In the
second call, "Good Morning" replaces the default value.
4. Variable-Length Arguments
Variable-length arguments allow passing multiple values to a function
using *args.
Example Program
def total_marks(*marks):
total = sum(marks)
print("Total Marks:", total)
total_marks(80, 85, 90, 95)
Output
Total Marks: 350
Explanation
*marks allows multiple arguments to be passed, and sum() calculates the
total.
5 . Define variables. What are its naming rules and
scope and explain it with an example ?
Definition of Variable
A variable is a name given to a memory location used to store values.
The value stored in a variable can be changed during program execution.
In Python, variables are created automatically when a value is assigned.
Syntax:
variable_name = value
Example:
name = "Maria"
age = 18
percentage = 92.5
print(name)
print(age)
print(percentage)
Output:
Maria
18
92.5
Here:
name stores a string value.
age stores an integer value.
percentage stores a float value.
Naming Rules of Variables in Python
Python follows certain rules for naming variables. Proper variable naming
improves readability and avoids errors.
1. Variable Name Must Begin with a Letter or Underscore (_)
A variable name should start with:
An alphabet (A-Z, a-z)
An underscore (_)
Correct Example:
name = "John"
_age = 20
Incorrect Example:
1name = "John"
Reason: Variable names cannot begin with numbers.
2. Variable Names Can Contain Letters, Numbers and Underscores
After the first character, variable names may include:
Alphabets
Numbers
Underscore (_)
Correct Example:
student1 = "Maria"
total_marks = 450
Incorrect Example:
student-name = "Maria"
Reason: Special symbols like -, @, %, # are not allowed.
3. Spaces Are Not Allowed in Variable Names
Variables should not contain spaces.
Incorrect Example:
student name = "Maria"
Correct Example:
student_name = "Maria"
4. Python Keywords Cannot Be Used as Variable Names
Reserved words or keywords in Python cannot be used as variable names.
Examples of keywords:
if, for, while, class, True, False
Incorrect Example:
class = 10
Correct Example:
class_name = "AI & DS"
5. Variable Names Are Case Sensitive
Python treats uppercase and lowercase letters differently.
Example:
name = "Maria"
Name = "Gladwin"
print(name)
print(Name)
Output:
Maria
Gladwin
Thus, name and Name are treated as two different variables.
6. Meaningful Variable Names Should Be Used
Variables should have meaningful names for better understanding of the
program.
Poor Example:
a = 500
Better Example:
salary = 500
Meaningful variable names make programs easier to read and debug.
Scope of Variables in Python
The scope of a variable refers to the region of the program where the
variable can be accessed.
There are mainly two types of variable scope in Python:
1. Local Scope
2. Global Scope
1. Local Scope (Local Variable)
A variable declared inside a function is called a local variable. It can be
used only within that function.
Example Program:
def student():
name = "Maria" # Local variable
age = 18
print("Name:", name)
print("Age:", age)
student()
Output:
Name: Maria
Age: 18
Explanation:
Here, name and age are local variables because they are created inside
the function student(). These variables cannot be accessed outside the
function.
Example:
def demo():
x = 10
demo()
print(x)
Output:
NameError: name 'x' is not defined
This error occurs because x is a local variable.
2. Global Scope (Global Variable)
A variable declared outside a function is called a global variable. It can
be accessed throughout the program.
Example Program:
college = "ABC Engineering College"
def student():
print("College Name:", college)
student()
Output:
College Name: ABC Engineering College
Explanation:
Here, college is a global variable because it is declared outside the
function and can be accessed inside the function.
Program Demonstrating Both Local and Global Variables
x = 100 # Global variable
def display():
y = 50 # Local variable
print("Global Variable:", x)
print("Local Variable:", y)
display()
Output:
Global Variable: 100
Local Variable: 50
Explain Data Wrangling and Handling
Missing Data
. Data Wrangling
Definition
Data Wrangling (or Data Munging) is the process of collecting,
cleaning, transforming, and organizing raw data into a
structured format suitable for analysis and machine learning.
Steps in Data Wrangling
1. Data Collection
Data is gathered from various sources such as:
Databases
CSV files
Websites
Sensors
APIs
2. Data Cleaning
Errors and inconsistencies are removed.
Remove duplicate records
Correct invalid values
Handle missing data
Standardize formats
3. Data Transformation
Data is converted into a suitable format.
Normalization
Scaling
Encoding categorical values
Aggregation
4. Data Integration
Data from multiple sources is combined into a single dataset.
5. Data Reduction
Reduces data size while preserving important information.
Sampling
Feature selection
Dimensionality reduction
6. Data Validation
Ensures data quality and correctness before analysis.
Methods for Handling Missing Data
1. Deleting Missing Values
a) Row Deletion
Remove records containing missing values.
Example:
Na Ag
me e
Ravi 20
Priy Na
a N
After deletion:
Na Ag
me e
Ravi 20
b) Column Deletion
Remove an entire column if most values are missing.
2. Mean Imputation
Replace missing numerical values with the mean of the column.
Formula:
∑X
Mean=
N
Example:
Age = 20, 25, NaN, 35
Mean = (20+25+35)/3 = 26.67
Missing value → 26.67
3. Median Imputation
Replace missing values with the median value.
Suitable when data contains outliers.
Example:
10, 15, NaN, 20, 100
Median = 20
Missing value → 20
4. Mode Imputation
Replace missing values with the most frequently occurring
value.
Example:
Red, Blue, Red, NaN
Mode = Red
Missing value → Red
5. Forward Fill Method
The previous valid value is used to fill missing entries.
Example:
Da Sal
y es
1 100
Da Sal
y es
2 NaN
3 120
After filling:
Da Sal
y es
1 100
2 100
3 120
6. Backward Fill Method
Uses the next valid value to fill missing entries.
7. Predictive Imputation
Machine learning algorithms predict missing values using
existing data.
Methods:
Regression
Decision Trees
K-Nearest Neighbors (KNN)
Explain the Different Types of Plots in Matplotlib (12
Marks)
Introduction
Matplotlib is a popular Python library used for data
visualization. It provides various types of plots to represent
data graphically, making analysis and interpretation easier.
1. Line Plot
A line plot is used to display data points connected by straight
lines. It is mainly used to show trends over time.
Syntax:
[Link](x, y)
Example:
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
[Link](x, y)
[Link]("Line Plot")
[Link]()
Applications: Stock market trends, temperature variations,
sales growth.
2. Bar Plot
A bar plot represents data using rectangular bars. It is used to
compare quantities among different categories.
Syntax:
[Link](x, y)
Example:
import [Link] as plt
students = ['A', 'B', 'C', 'D']
marks = [80, 75, 90, 85]
[Link](students, marks)
[Link]("Bar Plot")
[Link]()
Applications: Comparing sales, marks, population, etc.
3. Histogram
A histogram shows the frequency distribution of continuous
data by dividing it into intervals called bins.
Syntax:
[Link](data, bins)
Example:
import [Link] as plt
data = [10, 20, 20, 30, 40, 40, 40, 50]
[Link](data, bins=5)
[Link]("Histogram")
[Link]()
Applications: Statistical analysis and data distribution.
4. Scatter Plot
A scatter plot displays individual data points and helps
identify relationships between two variables.
Syntax:
[Link](x, y)
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 5]
[Link](x, y)
[Link]("Scatter Plot")
[Link]()
Applications: Correlation analysis and pattern identification.
5. Pie Chart
A pie chart represents data as sectors of a circle, showing the
proportion of each category.
Syntax:
[Link](data, labels=labels)
Example:
import [Link] as plt
marks = [40, 30, 20, 10]
subjects = ['Maths', 'Physics', 'Chemistry', 'English']
[Link](marks, labels=subjects, autopct='%1.1f%%')
[Link]("Pie Chart")
[Link]()
Applications: Market share analysis, budget allocation.
6. Box Plot
A box plot summarizes data distribution using quartiles and
helps detect outliers.
Syntax:
[Link](data)
Example:
import [Link] as plt
data = [10, 15, 20, 25, 30, 35, 40]
[Link](data)
[Link]("Box Plot")
[Link]()
Describe How Exceptions are Handled in Python with
Necessary Examples (12 Marks)
Introduction
An exception is an error that occurs during the execution of a
program. When an exception occurs, Python stops the normal
flow of the program and generates an error message. Exception
handling allows programmers to manage errors gracefully using
try, except, else, and finally blocks.
Exception Handling in Python
1. try Block
The code that may generate an exception is placed inside the
try block.
Example
try:
num = 10 / 0
Here, division by zero raises a ZeroDivisionError.
2. except Block
The except block handles the exception and prevents the
program from crashing.
Example
try:
num = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output
Cannot divide by zero
3. else Block
The else block executes only if no exception occurs in the try
block.
Example
try:
num = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Result =", num)
Output
Result = 5.0
4. finally Block
The finally block executes whether an exception occurs or not.
It is generally used for cleanup operations.
Example
try:
num = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Execution completed")
Output
Division by zero
Execution completed
Complete Exception Handling Structure
Syntax
try:
# Code that may cause exception
except ExceptionType:
# Handle exception
else:
# Executes if no exception
finally:
# Executes always
Start
|
try Block
|
Exception?
/ \
Yes No
| |
except else
\ /
finally
|
End
Exception Handling with All Blocks (try, except, else,
finally)
try:
a = 10
b=2
c=a/b
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result =", c)
finally:
print("Program Ended")
Output
Result = 5.0
Program Ended
2 . Explain Different Types of Variables with Suitable
Example (12 Marks)
Introduction
A variable is a named memory location used to store data
values in a program. In Python, variables are created
automatically when a value is assigned to them. Variables help
in storing and manipulating data during program execution.
Types of Variables in Python
1. Local Variable
A variable declared inside a function is called a local variable.
It can be accessed only within that function.
Example
def display():
x = 10 # Local variable
print(x)
display()
Output:
10
2. Global Variable
A variable declared outside all functions is called a global
variable. It can be accessed throughout the program.
Example
x = 20 # Global variable
def display():
print(x)
display()
Output:
20
3. Instance Variable
An instance variable belongs to an object of a class. Each
object has its own copy of the variable.
Example
class Student:
def __init__(self):
[Link] = "John"
s = Student()
print([Link])
Output:
John
4. Class Variable
A class variable is shared by all objects of a class.
Example
class Student:
college = "ABC College"
print([Link])
Output:
ABC College
Simple Program Showing Local and Global Variables
x = 100 # Global variable
def test():
y = 50 # Local variable
print("Local Variable =", y)
print("Global Variable =", x)
test()
Output:
Local Variable = 50
Global Variable = 100
3 . Define Correlation and Explain its Types (12 Marks)
Introduction
Correlation is a statistical measure that indicates the degree
and direction of relationship between two variables. It shows
how one variable changes with respect to another variable.
Definition:
Correlation is the measure of the strength and direction of
association between two variables.
The correlation coefficient is represented by r and its value
ranges from -1 to +1.
r = +1 → Perfect positive correlation
r = -1 → Perfect negative correlation
r = 0 → No correlation
Types of Correlation
1. Positive Correlation
When both variables move in the same direction, it is called
positive correlation.
Increase in one variable leads to increase in another.
Decrease in one variable leads to decrease in another.
Example:
Study time and examination marks.
Advertising expenditure and sales.
Study Time ↑ → Marks ↑
Study Time ↓ → Marks ↓
2. Negative Correlation
When one variable increases and the other decreases, it is
called negative correlation.
Example:
Price of a product and demand.
Speed and time taken to travel a fixed distance.
Price ↑ → Demand ↓
Price ↓ → Demand ↑
3. Zero Correlation
When there is no relationship between two variables, it is called
zero correlation.
Example:
Shoe size and intelligence.
Height and examination marks.
Change in one variable does not affect the other.
4. Perfect Correlation
A correlation is said to be perfect when the relationship
between variables is exact.
Perfect Positive Correlation
Correlation coefficient r = +1
Example:
Distance travelled and distance measured in another unit.
Perfect Negative Correlation
Correlation coefficient r = -1
Example:
Increase in one variable exactly decreases the other.
Diagrammatic Representation
Correlation
Type
Coefficient
Perfect
+1
Positive
Positive 0 to +1
Zero 0
Negative -1 to 0
Correlation
Type
Coefficient
Perfect
-1
Negative
Explain About Tuples, Tuple Operations and
Its Functions (12 Marks)
Introduction
A Tuple is an ordered collection of elements in Python. It is
similar to a list, but tuples are immutable, meaning their
elements cannot be modified after creation. Tuples are
enclosed within parentheses ().
Example
t = (10, 20, 30, 40)
print(t)
Output:
(10, 20, 30, 40)
Characteristics of Tuples
1. Ordered collection of elements.
2. Immutable (cannot be changed).
3. Allows duplicate values.
4. Can store different data types.
5. Faster than lists.
Tuple Operations
1. Accessing Elements
Elements can be accessed using indexing.
t = (10, 20, 30, 40)
print(t[1])
Output:
20
2. Concatenation
Two tuples can be combined using +.
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2)
Output:
(1, 2, 3, 4)
3. Repetition
Tuple elements can be repeated using *.
t = (1, 2)
print(t * 3)
Output:
(1, 2, 1, 2, 1, 2)
4. Membership Operation
Checks whether an element exists in a tuple.
t = (10, 20, 30)
print(20 in t)
Output:
True
5. Slicing
Extracts a portion of a tuple.
t = (10, 20, 30, 40, 50)
print(t[1:4])
Output:
(20, 30, 40)
Tuple Functions
1. len()
Returns the number of elements.
t = (10, 20, 30)
print(len(t))
Output:
3
2. max()
Returns the largest element.
t = (10, 50, 20)
print(max(t))
Output:
50
3. min()
Returns the smallest element.
t = (10, 50, 20)
print(min(t))
Output:
10
4. sum()
Returns the sum of elements.
t = (10, 20, 30)
print(sum(t))
Output:
60
5. count()
Returns the number of occurrences of an element.
t = (10, 20, 10, 30)
print([Link](10))
Output:
2
6. index()
Returns the position of an element.
t = (10, 20, 30)
print([Link](20))
Output:
1
Simple Program Using Tuple
t = (10, 20, 30, 40)
print("Tuple:", t)
print("Length:", len(t))
print("Maximum:", max(t))
print("Minimum:", min(t))
print("Sum:", sum(t))
Output:
Tuple: (10, 20, 30, 40)
Length: 4
Maximum: 40
Minimum: 10
Sum: 100
Advantages of Tuples
1. Faster than lists.
2. Protects data from accidental modification.
3. Can be used as dictionary keys.
4. Requires less memory.
Explain Reading from a File and Writing to a
File with Program (12 Marks)
Introduction
A file is a collection of data stored permanently on a storage
device. Python provides file handling operations to create,
read, write, and update files. The open() function is used to
access files.
Syntax
file = open("[Link]", "mode")
File Modes
Mod
Description
e
r Read mode
w Write mode
Mod
Description
e
a Append mode
Read and Write
r+
mode
Writing to a File
Writing means storing data into a file. The write() method is
used for this purpose.
Program
f = open("[Link]", "w")
[Link]("Welcome to Python")
[Link]()
print("Data written successfully")
Output
Data written successfully
The text "Welcome to Python" is stored in [Link].
Reading from a File
Reading means retrieving data from a file. The read() method
is used to read the contents of a file.
Program
f = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()
Output
Welcome to Python
Combined Program (Writing and Reading)
f = open("[Link]", "w")
[Link]("Python File Handling")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]()
Output
Python File Handling
Advantages of File Handling
1. Stores data permanently.
2. Enables easy retrieval of information.
3. Useful for large amounts of data.
4. Supports data sharing between programs.
5 . Explain Various Facets of Data (12
Marks) – AD25201
Introduction
Data is a collection of facts, figures, observations, or
measurements that can be processed to obtain meaningful
information. In Data Science, the characteristics or facets of
data help us understand the nature, quality, and usefulness of
data for analysis and decision-making.
The important facets of data are often represented by the 5 Vs
of Data (Big Data): Volume, Velocity, Variety, Veracity,
and Value.
1. Volume
Volume refers to the amount of data generated and
stored.
Modern organizations collect huge quantities of data from
social media, sensors, transactions, and websites.
Data size may range from Gigabytes (GB) to Terabytes
(TB), Petabytes (PB), and beyond.
Example: E-commerce websites store millions of customer
transaction records.
2. Velocity
Velocity refers to the speed at which data is
generated, collected, and processed.
Many applications require real-time data processing.
Example: Online banking transactions and social media
updates are generated continuously and need immediate
processing.
3. Variety
Variety refers to the different forms and types of data.
Data can be:
o Structured Data (tables, databases)
o Semi-Structured Data (XML, JSON)
o Unstructured Data (images, videos, audio, text)
Example: A social media platform contains text posts,
images, videos, and comments.
4. Veracity
Veracity refers to the accuracy, reliability, and quality
of data.
Data may contain errors, noise, missing values, or
inconsistencies.
High-quality data produces accurate analysis and better
decisions.
Example: Incorrect customer information can lead to
wrong business decisions.
5. Value
Value refers to the usefulness of data in generating
insights and supporting decision-making.
Data has significance only when it can be transformed into
valuable information.
Example: Customer purchase data helps companies
recommend products and improve sales.
Diagram of 5 Vs of Data
DATA
|
--------------------------------
| | | | |
Volume Velocity Variety Veracity Value
Applications of Data Facets
Business analytics
Healthcare systems
Banking and finance
Social media analysis
E-commerce recommendations
Scientific research
6 . Implement Basic Operations (Array Join,
Split, Search, Sort) Using NumPy (12 Marks)
Introduction
NumPy (Numerical Python) is a Python library used for
numerical computations and array operations. It provides
various functions to perform array joining, splitting, searching,
and sorting efficiently.
1. Array Join
Array joining combines two or more arrays into a single array.
Program
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
c = [Link]((a, b))
print("Joined Array:", c)
Output
Joined Array: [1 2 3 4 5 6]
2. Array Split
Array splitting divides an array into multiple sub-arrays.
Program
import numpy as np
a = [Link]([1, 2, 3, 4, 5, 6])
b = np.array_split(a, 3)
print(b)
Output
[array([1, 2]), array([3, 4]), array([5, 6])]
3. Array Search
Searching is used to find the index position of a specified
element.
Program
import numpy as np
a = [Link]([10, 20, 30, 40, 50])
x = [Link](a == 30)
print("Index Position:", x)
Output
Index Position: (array([2]),)
4. Array Sort
Sorting arranges elements in ascending order.
Program
import numpy as np
a = [Link]([40, 10, 30, 50, 20])
b = [Link](a)
print("Sorted Array:", b)
Output
Sorted Array: [10 20 30 40 50]
Combined Program
import numpy as np
# Join
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print("Joined Array:", [Link]((a,b)))
# Split
c = [Link]([1,2,3,4,5,6])
print("Split Array:", np.array_split(c,3))
# Search
d = [Link]([10,20,30,40,50])
print("Search Result:", [Link](d==30))
# Sort
e = [Link]([40,10,30,50,20])
print("Sorted Array:", [Link](e))
Conclusion
NumPy provides efficient functions for performing basic array
operations such as joining (concatenate), splitting
(array_split), searching (where), and sorting (sort). These
operations are widely used in data analysis and scientific
computing.
7 . Explain String Methods in Python (12
Marks)
Introduction
A string is a sequence of characters enclosed within single
quotes (' '), double quotes (" "), or triple quotes (''' '''). Python
provides many built-in string methods to manipulate and
process strings easily.
Example:
s = "Python Programming"
Common String Methods
1. upper()
Converts all characters to uppercase.
s = "python"
print([Link]())
Output:
PYTHON
2. lower()
Converts all characters to lowercase.
s = "PYTHON"
print([Link]())
Output:
python
3. capitalize()
Converts the first character to uppercase.
s = "python"
print([Link]())
Output:
Python
4. title()
Converts the first letter of each word to uppercase.
s = "python programming"
print([Link]())
Output:
Python Programming
5. strip()
Removes spaces from the beginning and end of a string.
s = " Python "
print([Link]())
Output:
Python
6. replace()
Replaces a substring with another substring.
s = "Hello World"
print([Link]("World","Python"))
Output:
Hello Python
7. split()
Splits a string into a list.
s = "Python is easy"
print([Link]())
Output:
['Python', 'is', 'easy']
8. find()
Returns the position of a character or substring.
s = "Python"
print([Link]("t"))
Output:
2
9. startswith()
Checks whether a string starts with a specified value.
s = "Python"
print([Link]("Py"))
Output:
True
10. endswith()
Checks whether a string ends with a specified value.
s = "Python"
print([Link]("on"))
Output:
True
Summary Table
Method Purpose
upper() Converts to uppercase
lower() Converts to lowercase
capitalize
First letter uppercase
()
First letter of every word
title()
uppercase
strip() Removes spaces
replace() Replaces text
split() Splits string into list
Method Purpose
find() Finds position of substring
startswith
Checks starting characters
()
endswith(
Checks ending characters
)