Python-SEM5
Python-SEM5
Versatility: It's used for various applications, from web development to data science.
Disadvantages of Python:
Dynamic Typing: While flexible, can lead to runtime errors if not used carefully.
-->
Memory
Tuples consumes less
Consumptio List consumes more memory.
memory.
n
--> While Python can be used for scripting, it's also a powerful general-purpose language
capable of building large-scale applications. Its interpreted nature and emphasis on
readability make it suitable for scripting tasks, but its versatility extends beyond that.
--> A dictionary is an unordered collection of key-value pairs. Each key is unique, and it's
used to access the corresponding value. Dictionaries are highly efficient for storing and
retrieving data.
-->
# my_module.py
def greet(name):
# main.py
import my_module
A user-defined module is a Python file containing functions, classes, and variables that can
be imported and used in other Python scripts. Modules help organize code and promote
reusability.
--> Yes, Python is a case-sensitive language. This means that variables, function names,
and keywords must be written with consistent capitalization. For example, myVariable is
different from MyVariable.
--> A lambda function is a small, anonymous function defined using the lambda keyword.
It's often used for short, one-time operations. Lambda functions take input arguments,
perform a calculation, and return a result. They are useful for functional programming
paradigms.
EX:
double = lambda x: x * 2
result = double(5)
print(result) # Output: 10
--> Comments are used to explain code and improve readability. Single-line comments
start with #. Multi-line comments are enclosed within triple quotes (""").
print("Hello, world!")
"""
--> The index() method in Python strings is used to find the index of the first occurrence of a
substring within a string. It returns the index of the first character of the substring. If the
substring is not found, it raises a ValueError.
--> The range() function generates a sequence of numbers. It takes three optional
parameters: start, stop, and step.
step (default: 1): The difference between each number in the sequence.
def greet():
print("Hello, world!")
A void function, also known as a procedure, does not return any value. It's defined using the
def keyword followed by the function name and parentheses. The function body contains
the code to be executed when the function is called.
-->
--> clock() returns the processor time used by the Python script since it started. This can be
useful for measuring the performance of different parts of your code.
gmtime() returns a time tuple representing the current time in UTC (GMT). This tuple
contains information about the year, month, day, hour, minute, second, day of the week,
day of the year, and daylight saving time flag.
--> The math module provides various mathematical functions in Python. Here are two
common functions:
--> A dry run is a manual process of executing a program's logic step-by-step without
actually running it on a computer.It involves tracing the code line by line, simulating the
execution flow and keeping track of variable values. This technique helps in identifying
potential errors, understanding code behavior, and debugging issues before running the
program.
--> Selection statements, such as if, elif, and else, allow you to control the flow of execution
in your Python program based on certain conditions. They enable you to make decisions
and execute specific code blocks depending on whether a given condition is true or false.
This helps in creating dynamic and responsive programs.
Implicit Type Conversion: Python automatically converts data types to compatible ones,
like converting an integer to a float in arithmetic operations.
Explicit Type Conversion: You manually convert data types using built-in functions like int(),
float(), str(), etc. For example, converting a string to an integer: int("10").
--> The pass statement is a placeholder that does nothing. It's often used to create empty
function bodies or code blocks that will be implemented later. It helps avoid syntax errors
and allows you to maintain the structure of your code.
--> The extend() method adds all elements of one list to the end of another list. It modifies
the original list in-place. This is different from the append() method, which adds a single
element to the end of the list.
g) What are required arguments in function?
--> Required arguments are mandatory parameters that must be passed to a function when
it's called. The number of required arguments must match the number of parameters
defined in the function's definition. If you don't provide the required arguments, Python will
raise a TypeError.
--> The time module in Python provides functions for working with time and dates.
1. time.time(): Returns the current time in seconds since the Unix epoch (January 1,
1970, 00:00:00 UTC).
2. time.sleep(seconds): Pauses the execution of the program for the specified number
of seconds.
Binary Files: Store data in binary format, not directly readable by humans.
--> seek() and tell() functions are used to manipulate the file pointer's position within a
file.
seek(offset, from_where): Moves the file pointer to a specific position. from_where can be 0
(beginning), 1 (current position), or 2 (end of file).
These functions are useful for reading and writing specific parts of a file, especially
when dealing with large files.
pattern = r".at"
Code Python
pattern = r"\d{3}-\d{3}-\d{4}"
Python,
Python,
--> Backward indexing allows you to access characters in a string from the end. The last
character has an index of -1, the second-to-last has -2, and so on. This is useful for
processing characters from the end without knowing the exact length.
e) Define identifiers.
--> Identifiers are names given to variables, functions, classes, and other objects in
Python. They must follow certain rules:
a) Which methods are used to read from a file? Explain any two with example.
The with statement ensures proper file closure, even if an exception occurs.
b) What are the usage of dictionary copy(), gets(), items() and keys()
Methods?
--> copy(): Creates a new dictionary with the same key-value pairs.
get(): Retrieves a value associated with a key, with an optional default value.
Code Python,
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Union
union_set = set1.union(set2)
# Intersection
intersection_set = set1.intersection(set2)
i) if
--> The if statement checks a condition. If the condition is True, the code inside the
indented block is executed.
b) if else
--> The if-else statement provides an alternative block of code to execute when the
condition is False.
c) break
--> The break statement immediately terminates the loop it's inside.
d) continue
--> The continue statement skips the rest of the current iteration and moves to the next
iteration of the loop.
--> Python offers simplicity, versatility, and a strong community. It's easy to learn, has a
clean syntax, and is used for web development, data science, machine learning, and more.
Its extensive libraries and cross-platform compatibility make it a powerful tool for various
applications.
result = x * y
return result
product = calculate_xy(x, y)
b) Write a python program to accept a number and check whether it is perfect number
or not.
-->
def is_perfect_number(number):
sum_of_divisors = 0
if number % i == 0:
sum_of_divisors += i
if is_perfect_number(number):
else:
--> List slicing allows you to extract specific portions of a list using indexing and slicing
syntax. You can specify the start index, end index (exclusive), and optional step size to
create new lists from existing ones.
--> Yes, a tuple is indeed an ordered collection of items. This means that the elements
in a tuple are stored in a specific sequence, and their order is preserved. Unlike lists,
tuples are immutable, which means you cannot change their elements after creation.
--> Python offers a variety of data types to store different kinds of information:
1.Numeric Types:
2.Boolean Type:
3.Sequence Types:
4.Set Type:
5.Mapping Type:
dict: Represents a collection of key-value pairs (e.g., {'name': 'Alice', 'age': 30})
--> Exception handling in Python is used to gracefully handle errors and unexpected events
that may occur during program execution. It helps prevent the program from crashing and
provides a way to recover or take appropriate actions.
The try block contains the code that might raise an exception. If an exception occurs, the
except block is executed. Multiple except blocks can be used to handle different types of
exceptions. The else block is optional and executes only if no exceptions occur within the
try block. The finally block is also optional and always executes, regardless of whether an
exception occurred or not.
c) What is a module?
--> A module is a Python file containing functions, classes, and variables. It's used to
organize code and promote reusability. You can import modules using the import
statement. In the example, my_module.py is a module, and main.py imports and uses
its greet function.
# my_module.py
def greet(name):
# main.py
import my_module
def greet():
# my_package/__init__.py
# main.py
import my_package.module1
a) Write a program to get a single string from two given strings, separated
"""Swaps the first two characters of two strings and concatenates them."""
print(result)
b) Write a program to display power of 2 upto a given number using
anonymous function
Example
N=2
2 raised to 0 is 1
2 raised to 1 is 2
2 raised to 2 is 4
for i in range(N+1):
content = file.read()
return content
content = read_file(filename)
print(content)
num_str = str(number)
num_digits = len(num_str)
sum_of_digits = 0
if is_armstrong_number(number):
else:
function.
for i in range(N+1):
words = string.split()
print(word)
print_even_length_words(string)
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
divide_numbers(num1, num2)
if b == 0:
return a
else:
return gcd_recursive(b, a % b)
dictionary.
if key in dictionary:
else:
check_key_existence(my_dict, key_to_check)
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0
if char in vowels:
vowel_count += 1
elif char.isalpha():
consonant_count += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
b) Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are the square of the
keys.
Sample Dictionary
{1: 1, 2:4, 3:9, 4: 16, 5:25, 6:36, 7:49, 8:64, 9:81, 10: 100, 11: 121, 12: 144,
--> square_dict = {}
print(square_dict)
c) Write a Python function that accepts a string and counts the number of
"""
Args:
Returns:
"""
# Example usage
result = count_case_letters(string)
single digit.
"""
Recursively calculates the sum of digits of a number until it becomes a single digit.
Args:
Returns:
"""
if n < 10:
return n
else:
return sum_to_single_digit(digit_sum)
# Example usage
number = 9876
result = sum_to_single_digit(number)
"""
Accepts 'n' integers from the user, computes, and displays the sum of their squares.
"""
n = int(input("Enter the number of integers: "))
numbers = []
for _ in range(n):
numbers.append(number)
# Example usage
sum_of_squares()
"""
Counts the occurrences of the words "India" and "Country" in a text file.
Args:
Returns:
"""
try:
content = file.read()
india_count = content.lower().count("india")
country_count = content.lower().count("country")
except FileNotFoundError:
return {}
# Example usage
filename = "pledge.txt"
result = count_words_in_file(filename)
if result:
X=5
def f1( ) :
global X
X=4
def f2(a, b) :
global X
return a+b+X
f1( )
total = f2(1, 2)
print (total)
--> Execution:
Output:
def f(X) :
def f1(a, b) :
print ("hello")
if (b==0) :
print ("NO")
return
return f(a, b)
return f1
@f
def f(a, b) :
return a%b
f(4, 0)
Final Output:
hello
NO
a)
a = True
b = False
c = False
if not a or b:
print (1)
print (2)
print (3)
else:
print (4)
1. Variables:
a. a = True
b. b = False
c. c = False
2. First if Condition:
python
Copy code
if not a or b:
python
Copy code
elif not a or not b and c:
python
Copy code
elif not a or b or not b and a:
Final Output:
for i in range(x):
1.append(i*i)
print(1)
f1 (2)
f1 (3,[3,2,1])
f1 (3)
Final Output:
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
sum = 0
for i in range (12, 2, –2) :
sum + = i
print sum
1. range(12, 2, -2):
a. This generates numbers starting at 12, decreasing by 2, and stopping before
2.
b. The sequence is: [12, 10, 8, 6, 4].
2. Loop Iteration:
a. Iteration 1: i = 12, sum = 0 + 12 = 12.
b. Iteration 2: i = 10, sum = 12 + 10 = 22.
c. Iteration 3: i = 8, sum = 22 + 8 = 30.
d. Iteration 4: i = 6, sum = 30 + 6 = 36.
e. Iteration 5: i = 4, sum = 36 + 4 = 40.
3. Final Output: After the loop completes, sum = 40.
Output:
40
count = 1
def doThis ( ) :
global count
for i in (1, 2, 3) :
count + = 1
doThis( )
---> Execution:
Final Output: