Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Module 3 Python Tutorial - CIE2

The document provides a comprehensive overview of various Python programming concepts, including string manipulation methods, the shelve module for persistent storage, and user input validation. It includes code examples for operations such as accessing string characters, counting alphabets, checking for palindromes, and handling file I/O. Additionally, it explains methods like join(), split(), and various string handling functions with practical examples.

Uploaded by

chethanal279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 3 Python Tutorial - CIE2

The document provides a comprehensive overview of various Python programming concepts, including string manipulation methods, the shelve module for persistent storage, and user input validation. It includes code examples for operations such as accessing string characters, counting alphabets, checking for palindromes, and handling file I/O. Additionally, it explains methods like join(), split(), and various string handling functions with practical examples.

Uploaded by

chethanal279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Module 3

1. Write the output of the following python code


>>>spam=’Hello,World!’
i) >>>spam[0] ii) >>>spam[4] iii) >>>spam[-1]
iv) >>>spam[0:5] v)>>>spam[:5] vi)>>>spam[7:1]

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)

2.Write a program to accept string and display total number of


alphabets.

Soln.

# Program to count total number of alphabets in a string

# Accept input from the user


user_input = input("Enter a string: ")

# Initialize a counter for alphabets


alphabet_count = 0

# Iterate through each character in the string


for char in user_input:
# Check if the character is an alphabet
if char.isalpha():
alphabet_count += 1

# Display the total count of alphabets


print(f"Total number of alphabets in the string: {alphabet_count}")

O/p:

Enter a string: Hello, World! 123 Total number of alphabets in the string:
10

3. Explain how to save variables with the shelve method.

Soln.

The shelve module in Python provides a simple way to persistently store


Python objects (such as variables) in a file on disk. It works like a
dictionary, allowing you to store key-value pairs, where the keys are
strings, and the values can be any Python object that can be pickled.
Steps to Save Variables Using shelve
1.Import the shelve module.\
2.Open a shelve file using shelve.open(). The file acts like a dictionary.
3. Assign variables to keys in the shelve, similar to storing values in a
dictionary.
4. Close the shelve file after saving to ensure data is properly written

4.Explain the following string methods with examples:


i) isalpha() ii) isalnum() iii) isdecimal() iv) isspace() v)
istitle().

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)

5.Explain join() and split() method with examples.

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:

words = ["Hello", "World", "Python"]


result = " ".join(words) # Using a space as the separator
print(result)

Output: "Hello World Python"

Joining with a Hyphen:

numbers = ["1", "2", "3"]


result = "-".join(numbers) # Using a hyphen as the separator
print(result)

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():

Splitting a Sentence into Words:

sentence = "Hello World Python"


result = sentence.split() # Default separator (whitespace)
print(result)

Output: ['Hello', 'World', 'Python']

Splitting Using a Specific Delimiter:

data = "apple,banana,cherry"
result = data.split(",") # Using a comma as the separator
print(result) # Output: ['apple', 'banana', 'cherry']

6.Develop a python code to determine whether the given string is a


palindrome or not a palindrome.

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())

# Check if the cleaned string is equal to its reverse


if cleaned_string == cleaned_string[::-1]:
return True
return False

# Accept input from the user


user_input = input("Enter a string: ")

# Check if it's a palindrome


if is_palindrome(user_input):
print("The given string is a palindrome.")
else:
print("The given string is not a palindrome.")

Output:
Enter a string: Madam
The given string is a palindrome.

7.Explain Python string handling methods with examples:


split(),endswith(), ljust(), center(), lstrip()

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.

# Example 1: Split by default (whitespace)


text = "Hello World Python"
print(text.split()) # Output: ['Hello', 'World', 'Python']

# Example 2: Split by a specific delimiter


data = "apple,banana,cherry"
print(data.split(",")) # Output: ['apple', 'banana', 'cherry']
# Example 3: Split with a maxsplit
text = "one two three four"
print(text.split(" ", 2)) # Output: ['one', 'two', 'three four']

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

# Example 2: Using start and end parameters


text = "Hello World"
print(text.endswith("World", 6)) # Output: True (checks from index 6)
print(text.endswith("Hello", 0, 5)) # Output: True (checks from index 0
to 5)

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.

# Example 1: Left justify with spaces


text = "Python"
print(text.ljust(10)) # Output: "Python " (4 spaces added)

# Example 2: Left justify with a custom fill character


print(text.ljust(10, '-')) # Output: "Python----"

4.center()
• Definition: Centers the string, padding it with spaces (or a
specified character) to make it the desired width.

# Example 1: Center with spaces


text = "Python"
print(text.center(12)) # Output: " Python " (3 spaces on each side)

# Example 2: Center with a custom fill character


print(text.center(12, '*')) # Output: "***Python***"

5.lstrip()
• Definition: Removes leading whitespace (or specified
characters) from the string.

# Example 1: Remove leading whitespace


text = " Python"
print(text.lstrip()) # Output: "Python"

# Example 2: Remove specific characters


text = "###Python##"
print(text.lstrip("#")) # Output: "Python##"

8.Explain reading and saving python program variables using shelve


module with suitable Python program

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

# Part 1: Saving variables


def save_variables():
# Open a shelve file (creates a file called 'mydata.db')
with shelve.open('mydata') as shelf:
# Storing variables
shelf['name'] = "John Doe"
shelf['age'] = 30
shelf['scores'] = [85, 90, 78]
shelf['is_student'] = True
print("Variables saved successfully.")

# Part 2: Reading variables


def read_variables():
# Open the shelve file to retrieve data
with shelve.open('mydata') as shelf:
name = shelf['name']
age = shelf['age']
scores = shelf['scores']
is_student = shelf['is_student']

# Display the retrieved variables


print("Retrieved Variables:")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Scores: {scores}")
print(f"Is Student: {is_student}")

# Save variables
save_variables()

# Read variables
read_variables()

Output :

Variables saved successfully.


Retrieved Variables:
Name: John Doe
Age: 30
Scores: [85, 90, 78]
Is Student: True

9.Develop a Python program to read and print the contents of a text


file.

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:

Enter the name of the text file to read: example.txt


File Contents:

Hello, World!
This is a simple text file.
Python is great for handling files.

10.Explain Python string handling methods with examples: join(),


startswith(),rjust(),strip(),rstrip()

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"

result_with_char = text.rjust(5, '0') # Pads with '0' instead of spaces


print(result_with_char)
# Output: "00042"

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!"

custom_strip = "###Python###".strip("#") # Removes '#' characters from


both ends
print(custom_strip)
# Output: "Python"

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): ")

# Check if the age is valid (only digits)


if not age.isdigit():
print("Invalid age. Please enter digits only.")
continue # Restart the loop

# Ask for the user's password


password = input("Enter your password (letters and digits only): ")

# Check if the password is valid (alphanumeric only)


if not password.isalnum():
print("Invalid password. Password must contain only letters and
digits.")
continue # Restart the loop

# If both inputs are valid, break the loop


print("Valid inputs received!")
print(f"Your age: {age}, Password: {password}")
break
Output :

Enter your age (digits only): abc


Invalid age. Please enter digits only.
Enter your age (digits only): 25
Enter your password (letters and digits only): pass@word
Invalid password. Password must contain only letters and digits.
Enter your age (digits only): 25
Enter your password (letters and digits only): password123
Valid inputs received!
Your age: 25, Password: password123
12.Differentiate between Absolute and Relative paths

Aspect Absolute Path Relative Path


Starts from Root directory Current working
directory
Dependency Independent of current directory Depends on current
directory
Usage Preferred for global references Preferred for local
references
Example /home/user/documents/ le.txt documents/ le.txt
(Linux)
Example C:\Users\User\Documents\ le.txt Documents\ le.txt
(Windows)

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

# Define the filename


file_name = "smart.txt"

# Get the absolute path of the file


absolute_path = os.path.abspath(file_name)

# Get the current working directory


current_working_directory = os.getcwd()

# 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 the paths


print(f"Absolute Path: {absolute_path}")
print(f"Relative Path: {relative_path}")

Output :

Case 1: If the file smart.txt is in the current working directory

Output:

Absolute Path: /home/user/projects/smart.txt


Relative Path: smart.txt

Case 2: If the file smart.txt is in a subdirectory

Output:
Absolute Path: /home/user/projects/data/smart.txt
Relative Path: data/smart.txt

13.Explain the concept of file handling. Also explain reading and


writing process with suitable example.

Soln :

File handling is the process of creating, reading, writing, and


manipulating files (such as text files or binary files) in Python. It allows
developers to interact with files stored on the system to save data
permanently, process information, or retrieve data for further use.
Python provides built-in functions and methods to handle file operations,
such as opening, closing, reading, and writing files.

File Handling Modes in Python


The open() function is used to open a file. It takes two arguments:
1. File Name: The name of the file to be opened.
2. Mode: Specifies the purpose of opening the file.
Mode Description
"r" Opens a le for reading (default mode).
fi
"w" Opens a le for writing (creates/overwrites).
"a" Opens a le for appending (adds content at the end).
"r+" Opens a le for both reading and writing.
"b" Opens a le in binary mode (e.g., "rb", "wb").

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.

Example: Reading from a File

Pgm :

# Create a file and write some data


with open("example.txt", "w") as file:
file.write("Hello, world!\nWelcome to Python file handling.")

# Reading the file


with open("example.txt", "r") as file:
content = file.read() # Reads the entire file
print("File Content:")
print(content)

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.

Example: Writing to a File


fi
fi
fi
fi
Pgm :
# Writing to a file
with open("example.txt", "w") as file:
file.write("Python file handling is simple.\n")
file.write("This is an example of writing to a file.\n")

# Reading the updated content


with open("example.txt", "r") as file:
content = file.read()
print("Updated File Content:")
print(content)

O/P :

Updated File Content:


Python file handling is simple.
This is an example of writing to a file.

14.Explain the concept of file path. Also discuss absolute and relative
file path.

Sol.

A file path is a string that specifies the location of a file or directory in a


computer's file system. It helps the operating system or a program locate
and access the file or folder.
There are two main types of file paths:
1. Absolute Path
2. Relative Path

Absolute and relative file path is shown in Q.12

15.Explain with suitable Python program segments: (i)


os.path.basename() (ii) os.path.join().

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"

# Get the base name (file name)


base_name = os.path.basename(file_path)

print(f"File Path: {file_path}")


print(f"Base Name: {base_name}")

O/p:

File Path: /home/user/documents/report.txt


Base Name: report.txt

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

# Directory and file names


directory = "/home/user/documents"
file_name = "report.txt"

# Join paths to create a complete file path


full_path = os.path.join(directory, file_name)
print(f"Directory: {directory}")
print(f"File Name: {file_name}")
print(f"Full Path: {full_path}")

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

# Loop through all files in the directory


for file in os.listdir(directory):
file_path = os.path.join(directory, file)

# Add the size if it's a file


if os.path.isfile(file_path):
total_size += os.path.getsize(file_path)
return total_size

# Input: Directory path


directory = input("Enter the directory path: “)

# Check if the directory exists


if os.path.isdir(directory):
total_size = calculate_total_size(directory)
print(f"Total size of all files in '{directory}': {total_size} bytes")
else:
print("Invalid directory path!")

O/p :

Enter the directory path: /Users/suma/Documents


Total size of all files in '/Users/suma/Documents': 36225836 bytes

You might also like