Module 3 Python Tutorial - CIE2
Module 3 Python Tutorial - CIE2
Soln.
spam = 'Hello,World!'
The string assigned to spam is:
Hello,World!
Now, let's evaluate each expression:
i) spam[0]
This accesses the character at index 0.
The first character of the string is: 'H'.
Output: 'H'
ii) spam[4]
This accesses the character at index 4.
The fifth character (index 4) in the string is: 'o'.
Output: 'o'
iii) spam[-1]
This accesses the character at index -1, which refers to the last character
of the string.
The last character in 'Hello,World!' is: '!'.
Output: '!'
iv) spam[0:5]
This uses slicing to access characters from index 0 (inclusive) to index 5
(exclusive).
The slice spam[0:5] gives: 'Hello'.
Output: 'Hello'
v) spam[:5]
This is equivalent to spam[0:5] because the starting index is omitted,
which defaults to 0.
The result is the same as above: 'Hello'.
Output: 'Hello'
vi) spam[7:1]
This is a slicing operation from index 7 to index 1.
However, slicing works only left-to-right in the string (i.e., the start
index must be less than the stop index).
Since 7 > 1, this slice is empty.
Output: '' (empty string)
Soln.
O/p:
Enter a string: Hello, World! 123 Total number of alphabets in the string:
10
Soln.
Soln.
i) isalpha()
• Definition: This method checks whether all characters in a
string are alphabets (a-z or A-Z). It returns True if all characters are
alphabets and the string is non-empty; otherwise, it returns False.
Examples:
print("Hello".isalpha()) # True (all characters are alphabets)
print("Hello123".isalpha()) # False (contains numbers)
print("".isalpha()) # False (empty string)
print("Hello World".isalpha()) # False (contains a space)
ii) isalnum()
• Definition: This method checks whether all characters in a
string are alphanumeric (alphabets or digits). It returns True if all
characters are alphanumeric and the string is non-empty;
otherwise, it returns False.
Examples:
print("Hello123".isalnum()) # True (contains alphabets and numbers)
print("Hello".isalnum()) # True (only alphabets, no special characters)
print("12345".isalnum()) # True (only numbers)
print("Hello World".isalnum()) # False (contains a space)
print("Hello!".isalnum()) # False (contains a special character)
iii) isdecimal()
• Definition: This method checks whether all characters in a
string are decimal characters (0-9). It returns True if all characters
are decimal digits and the string is non-empty; otherwise, it returns
False.
Examples:
print("12345".isdecimal()) # True (all characters are digits)
print("123.45".isdecimal()) # False (contains a decimal point)
print("Hello123".isdecimal()) # False (contains alphabets)
print("".isdecimal()) # False (empty string)
print("123".isdecimal()) # True (contains Unicode digits like full-
width numbers)
iv) isspace()
• Definition: This method checks whether all characters in a
string are whitespace characters (like space, tab, newline). It
returns True if all characters are whitespace and the string is non-
empty; otherwise, it returns False.
Examples:
print(" ".isspace()) # True (contains only spaces)
print("\t\n".isspace()) # True (contains tab and newline)
print("Hello World".isspace()) # False (contains non-whitespace
characters)
print("".isspace()) # False (empty string)
v) istitle()
• Definition: This method checks whether the string is in title
case, meaning the first letter of each word is uppercase and the rest
are lowercase. It returns True if the string is in title case and non-
empty; otherwise, it returns False.
Examples:
print("Hello World".istitle()) # True (each word starts with uppercase)
print("Hello world".istitle()) # False (second word is not title case)
print("HELLO World".istitle()) # False (first word is in uppercase, not
title case)
print("".istitle()) # False (empty string)
Soln.
1.join() Method
• Definition: The join() method combines the elements of an
iterable (e.g., a list, tuple) into a single string, using a specified
separator.
Examples of join():
Joining a List of Words:
Output: "1-2-3"
2. split() Method
• Definition: The split() method splits a string into a list of
substrings based on a specified delimiter (separator).
Examples of split():
data = "apple,banana,cherry"
result = data.split(",") # Using a comma as the separator
print(result) # Output: ['apple', 'banana', 'cherry']
Palindrome Definition:
A string is a palindrome if it reads the same backward as forward,
ignoring spaces, punctuation, and case differences.
def is_palindrome(string):
# Remove spaces and convert to lowercase for uniformity
cleaned_string = ''.join(char.lower() for char in string if char.isalnum())
Output:
Enter a string: Madam
The given string is a palindrome.
1. split()
• Definition: Splits a string into a list of substrings based on a
specified delimiter. If no delimiter is specified, it splits by
whitespace.
2.endswith()
• Definition: Checks if a string ends with a specified suffix.
Returns True if it does, and False otherwise.
# Example 1: Basic usage
filename = "report.pdf"
print(filename.endswith(".pdf")) # Output: True
3.ljust()
• Definition: Returns a left-justified version of the string,
padding it with spaces (or a specified character) to make it the
desired width.
4.center()
• Definition: Centers the string, padding it with spaces (or a
specified character) to make it the desired width.
5.lstrip()
• Definition: Removes leading whitespace (or specified
characters) from the string.
Soln.
1. Saving Variables (save_variables):
• The program opens a shelve file named mydata.db.
• Variables (name, age, scores, is_student) are stored as
key-value pairs in the shelve file.
• The file is closed after saving.
2. Reading Variables (read_variables):
• The program reopens the same shelve file.
• Variables are retrieved by their keys (e.g.,
shelf['name']) and displayed.
Example Program
Save and Read Variables Using shelve
import shelve
# Save variables
save_variables()
# Read variables
read_variables()
Output :
Soln.
def read_and_print_file(file_name):
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the contents of the file
content = file.read()
# Print the contents of the file
print("File Contents:\n")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Specify the file name (ensure the file exists in the same directory)
file_name = input("Enter the name of the text file to read: ")
read_and_print_file(file_name)
O/p:
Hello, World!
This is a simple text file.
Python is great for handling files.
1. join()
• Purpose: Combines the elements of an iterable (like a list or
tuple) into a single string, using the specified string as a separator.
• Pgm :
words = ['Hello', 'World']
result = ' '.join(words) # Joins the list with a space separator
print(result)
# Output: Hello World
2. startswith()
• Purpose: Checks if the string starts with the specified prefix.
Returns True if it does, otherwise False.
• Pgm :
text = "Python is awesome"
print(text.startswith("Python")) # Checks if the string starts with
"Python"
# Output: True
print(text.startswith("is", 7)) # Checks if substring starting at index 7
starts with "is"
# Output: True
3. rjust()
• Purpose: Returns a new string that is right-aligned in a field
of specified width, padded with spaces (or another character if
specified).
Pgm :
text = "42"
result = text.rjust(5) # Right-aligns the string in a width of 5, padded
with spaces
print(result)
# Output: " 42"
4. strip()
• Purpose: Removes leading and trailing whitespace (or
specified characters) from the string.
Pgm :
text = " Hello World! "
result = text.strip() # Removes leading and trailing whitespace
print(result)
# Output: "Hello World!"
5. rstrip()
• Purpose: Removes trailing whitespace (or specified
characters) from the string.
Pgm :
text = "Hello World! "
result = text.rstrip() # Removes trailing whitespace
print(result)
# Output: "Hello World!"
custom_rstrip = "Python!!!".rstrip("!")
print(custom_rstrip)
# Output: "Python"
11.Write a python program that repeatedly asks user for their age
and a password until they provide valid input. [age is in digit and
password in alphabet an digit only].
Program :
while True:
# Ask for the user's age
age = input("Enter your age (digits only): ")
1. Absolute Path
• Definition: An absolute path specifies the full location of a
file or directory from the root directory. It is independent of the
current working directory.
2. Relative Path
• Definition: A relative path specifies the location of a file or
directory relative to the current working directory.
Program :
import os
# Construct the relative path of the file (relative to the current working
directory)
fi
fi
fi
fi
relative_path = os.path.relpath(absolute_path,
current_working_directory)
Output :
Output:
Output:
Absolute Path: /home/user/projects/data/smart.txt
Relative Path: data/smart.txt
Soln :
Reading Process
To read data from a file, use the open() function with "r" mode.
Python provides the following methods for reading:
• read(): Reads the entire content of the file.
• readline(): Reads one line at a time.
• readlines(): Reads all lines as a list.
Pgm :
O/P:
File Content:
Hello, world!
Welcome to Python file handling.
Writing Process
To write data to a file, use the open() function with "w" or "a" mode:
• "w": Overwrites the file if it already exists, or creates a new
file.
• "a": Appends data to the existing content without
overwriting it.
O/P :
14.Explain the concept of file path. Also discuss absolute and relative
file path.
Sol.
Soln.
1. os.path.basename()
• Definition:
os.path.basename() extracts the base name (file name or the last
part of the path) from a given file path.
• Uses:
When you need only the file name (or the last directory name)
from a complete file path.
Ex Pgm :
import os
# File path
file_path = "/home/user/documents/report.txt"
O/p:
2. os.path.join()
• Definition:
os.path.join() combines multiple path components into a single,
valid file path. It automatically handles directory separators (/ or \)
based on the operating system.
• Uses :
When you need to dynamically construct file paths without
worrying about manually adding slashes.
Ex Pgm :
import os
O/p:
Directory: /home/user/documents
File Name: report.txt
Full Path: /home/user/documents/report.txt
16.Develop a Python program find the total size of all the files in the
given directory.
Soln :
Pgm :
import os
def calculate_total_size(directory):
total_size = 0
O/p :