Scripting Language – Python MID 2
1) Define Function
A function is a block of reusable code that performs a specific task. It helps organize code into
modular segments, making it easier to read, maintain, and debug.
Why We Need Functions:
Code Reusability: Functions allow you to write a piece of code once and reuse it
multiple times.
Modularity: Functions break down complex problems into smaller, manageable parts.
Maintainability: Changes made in a function are automatically reflected wherever it is
called.
Difference between User Defined Function and Built-in Function:
User Defined Function: These are functions created by the user to perform specific
tasks (e.g., def my_function():).
Built-in Function: These are predefined functions provided by the programming
language (e.g., print(), len()).
2) Five Mathematical Functions of Math Module
Here are five common mathematical functions from Python's math module:
1. math.sqrt(x): Returns the square root of x.
import math
print(math.sqrt(16)) # Output: 4.0
2. math.pow(x, y): Returns x raised to the power of y.
print(math.pow(2, 3)) # Output: 8.0
3. math.factorial(x): Returns the factorial of x.
print(math.factorial(5)) # Output: 120
4. math.sin(x): Returns the sine of x (x is in radians).
print(math.sin(math.pi / 2)) # Output: 1.0
5. math.log(x, base): Returns the logarithm of x to the specified base.
print(math.log(100, 10)) # Output: 2.0
3) Define String
A string is a sequence of characters enclosed within single, double, or triple quotes. Strings are
used to represent text data.
How to Create a List of Strings:
string_list = ["apple", "banana", "cherry"]
4) What is a Package?
A package is a way of organizing related modules in Python. It is essentially a directory that
contains a special __init__.py file and can contain multiple modules.
How to Create and Import a Package:
1. Create a directory named mypackage.
2. Inside mypackage, create a file named __init__.py.
3. Create a module file, e.g., module1.py.
Example Structure:
mypackage/
__init__.py
module1.py
Importing the Package:
import mypackage.module1
5) Explain Matplotlib
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension, NumPy. It is used for creating static, animated, and interactive
visualizations.
Types of Matplotlib:
Line Plot:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Bar Chart:
plt.bar(['A', 'B', 'C'], [3, 7, 5])
plt.show()
Histogram:
plt.hist([1, 2, 2, 3, 3, 3, 4], bins=4)
plt.show()
Scatter Plot:
plt.scatter([1, 2, 3], [4, 5, 6])
plt.show()
6) Steps for PIP Installation
1. Ensure Python is Installed: Make sure Python is installed on your system.
2. Open Command Line: Open a terminal or command prompt.
3. Run the Installation Command:
code
python -m ensurepip --upgrade
7) String Functions with Examples
isalnum(): Checks if all characters are alphanumeric.
code
"abc123".isalnum() # Output: True
isalpha(): Checks if all characters are alphabetic.
code
"abc".isalpha() # Output: True
isdigit(): Checks if all characters are digits.
code
"123".isdigit() # Output: True
isidentifier(): Checks if the string is a valid identifier.
code
"myVar".isidentifier() # Output: True
islower(): Checks if all characters are lowercase.
code
"abc".islower() # Output: True
isupper(): Checks if all characters are uppercase.
code
"ABC".isupper() # Output: True
isspace(): Checks if all characters are whitespace.
code
" ".isspace() # Output: True
8) Using Slicing Operator for Strings
Slicing allows you to extract parts of a string using the syntax string[start:end:step].
Example:
s = "Hello, World!"
print(s[0:5]) # Output: Hello
print (s[7:]) # Output: World!
print(s[::2]) # Output: Hlo ol!
9) Program to Check for Palindrome
def is_palindrome(s):
return s == s[::-1]
string = input("Enter a string: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
10) String Functions with Examples
endswith(): Checks if a string ends with a specified suffix.
code
"Hello".endswith("lo") # Output: True
startswith(): Checks if a string starts with a specified prefix.
code
"Hello".startswith("He") # Output: True
find(): Returns the lowest index of a substring, or -1 if not found.
code
"Hello".find("e") # Output: 1
rfind(): Returns the highest index of a substring, or -1 if not found.
code
"Hello".rfind("l") # Output: 3
count(): Returns the number of occurrences of a substring.
code
"Hello".count("l") # Output: 2
11) Program to Read and Convert Date Format
date = input("Enter date in DD/MM/YYYY format: ")
day, month, year = date.split('/')
formatted_date = f"{month}-{day}-{year}"
print("Date in MM-DD-YYYY format:", formatted_date)
OUTPUT
Enter date in DD/MM/YYYY format: 25/12/2024
Date in MM-DD-YYYY format: 12-25-2024
12) Formatting Functions
1. format()
2. f-strings (formatted string literals)
3. % Operator (old-style formatting)
4. str.format_map()
5. str.zfill()
6. str.ljust(), str.rjust(), str.center()
7. str.strip(), str.lstrip(), str.rstrip()
8. str.join()
9. format(): Formats specified values in a string.
10. f-string: A way to embed expressions inside string literals using curly braces.
Example of format():
code
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Example of f-string:
code
print(f"My name is {name} and I am {age} years old.")
13) Program to Print Fibonacci Sequence using Recursion
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
fib_seq = fibonacci(n - 1)
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq
n = int(input("Enter the number of terms: "))
print(fibonacci(n))
OUTPUT
Enter the number of terms: 5
[1, 1, 2, 3, 5]
14) Difference between Text Files and Binary Files in table
Feature Text Files Binary Files
Human-readable characters (e.g., letters, Non-human-readable data (e.g.,
Format
numbers) bytes)
Typically uses ASCII or UTF-8 No specific encoding; data is stored as raw
Encoding
encoding bytes
File Common extensions: .txt, .csv, Common extensions: .exe, .jpg,
Extension .html .bin
Can be opened and read with a text Requires specific software to read or
Readability
editor edit
Line Uses newline characters to separate No line structure; data is
Terminators lines continuous
Generally larger for the same amount of data due to More compact as data is stored in
Size
encoding overhead raw format
Use Storing documents, logs, and simple Storing images, audio, video, and executable
Cases data files
Processing Slower processing due to character Faster processing as data is directly
Speed conversion read
Data Structure Flat structure (lines of text) Hierarchical or structured (depends on format)
15) Explain open() and close() for Files
open(filename, mode): Opens a file and returns a file object. Modes include 'r' (read),
'w' (write), and 'a' (append).
close(): Closes the file, freeing up any resources associated with it.
# Opening a file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close() # Closing the file
OUTPUT
Hello, World!