RemoveWatermark PYTHON+MID2
RemoveWatermark PYTHON+MID2
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.
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.
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()).
import math
print(math.sqrt(16)) # Output: 4.0
2. math.pow(x, y): Returns x raised to the power of y.
A string is a sequence of characters enclosed within single, double, or triple quotes. Strings are
used to represent text data.
4) What is a Package?
Example Structure:
mypackage/
__init__.py
module1.py
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:
Bar Chart:
Histogram:
Scatter Plot:
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
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]
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
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
OUTPUT
Enter the number of terms: 5
[1, 1, 2, 3, 5]
# Opening a file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close() # Closing the file
OUTPUT
Hello, World!