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

Python

Python notes

Uploaded by

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

Python

Python notes

Uploaded by

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

a) What is indentation?

Indentation refers to the spaces or tabs used at the beginning of a line to structure the code.
In Python, indentation is critical because it defines blocks of code (e.g., loops, functions,
conditionals). Unlike some other languages that use curly braces {} to group code, Python
relies on indentation to determine what code belongs to which block.

EX : if x > 5:
print("x is greater than 5") # Indentation here

b) Write code to print the elements of the list 11 = [10, 20, 30, 40, 50]

There's a slight issue with the variable name 11 — variable names cannot start with a
number. I'll assume you meant to name the list numbers. Here's the code to print the
elements:

numbers = [10, 20, 30, 40, 50]


for num in numbers:
print(num) #Output:- 10
20
30
40
50

c) What is a slice operator?

The slice operator in Python allows you to extract a portion (or slice) of a sequence (like a
list, tuple, or string). The syntax for slicing is sequence[start:stop:step], where:

 START is the index to start the slice (inclusive),


 STOP is the index to stop the slice (exclusive),
 STEP is the step size (optional, defaults to 1).

Ex:- my_list = [10, 20, 30, 40, 50]


print(my_list[1:4]) # Output: [20, 30, 40]

d) What is variable-length argument?

A variable-length argument allows a function to accept a variable number of arguments.


This means that the number of arguments you pass to the function does not need to be fixed;
the function can accept any number of arguments. There are two ways to do this in Python:

1. *args: Used to pass a variable number of positional arguments.


2. **kwargs: Used to pass a variable number of keyword arguments (key-value pairs).

Ex: def example(*args, **kwargs):


print(args) # Tuple of positional arguments
print(kwargs) # Dictionary of keyword arguments

example(1, 2, 3, name="Alice", age=25)


e) How to add multiple elements at the end of the list?

Use the extend() method or the += operator to add multiple elements at the end of a list.

EX:- numbers = [1, 2, 3]


numbers.extend([4, 5, 6]) => [1, 2, 3, 4, 5, 6] # Using extend
# OR
numbers += [7, 8, 9] # Using the += operator
print(numbers) =>[1, 2, 3, 7, 8, 9]

f) Explain the remove() method.

The remove() method is used to remove the first occurrence of a specific element from a
list. If the element is not found, it raises a ValueError.

Ex:- numbers = [10, 20, 30, 40, 50]


numbers.remove(30) # Removes the first occurrence of 30
print(numbers) # Output: [10, 20, 40, 50]

g) Write a lambda function to add 10 to a given integer.

A lambda function is an anonymous function defined using the lambda keyword.

add_10 = lambda x: x + 10
print(add_10(5)) # Output: 15

h) How to raise an exception with arguments?

Use the raise keyword followed by the exception type and the arguments (optional).

Example:

raise ValueError("Invalid input") # Raises a ValueError with a message

You can also raise custom exceptions:

class CustomError(Exception):
pass

raise CustomError("Something went wrong!")

i) List the methods of the re package.

The re package in Python is used for working with regular expressions. EX:-

 re.match(): Checks for a match at the beginning of the string.


 re.search(): Searches for the first location where the regular expression pattern
matches.
 re.findall(): Returns all matches of the pattern in a string as a list.
 re.finditer(): Returns an iterator yielding match objects.
 re.sub(): Substitutes occurrences of a pattern in a string.
 re.split(): Splits the string at each match of the pattern.
 re.compile(): Compiles a regular expression pattern into a regex object for reuse.

Example:

import re
pattern = r"\d+" # Matches one or more digits
result = re.findall(pattern, "There are 12 apples and 34 oranges")
print(result) # Output: ['12', '34']

j) What is a wb mode in file?

The wb mode in file operations stands for write binary. It is used to open a file for writing in
binary mode. When you open a file in wb mode, you can write binary data (like images or
non-text files) to the file.

Example: with open("example.bin", "wb") as file:


file.write(b'\x00\x01\x02\x03') # Writing binary data

Q2]

a) What are the usages of zip(), tuple(), count(), and index() functions?
Function Description Example Usage Usage

Combines multiple  To combine data from multiple sequences.


zip([1, 2], ['a', 'b'])
zip() iterables into an  Iterating over multiple sequences in parallel.
→ [(1, 'a'), (2, 'b')]
iterator of tuples.

 To convert an iterable to an immutable


Converts an iterable sequence.
tuple([1, 2, 3]) → (1,
tuple() (e.g., list, string) to a
2, 3)  Useful when you want to ensure the data
tuple.
cannot be modified

Returns the number To count the number of times an element appears in


count() of occurrences of a [1, 2, 1].count(1) → 2 a sequence
value in a list.

 To find the position (index) of an element in a


Returns the index of sequence.
[10, 20, 30].index(20)
index() the first occurrence of
→1  Useful when you need to know where an
a value. element is located

b) What is a package? Explain with example how to create a package.

In Python, a package is a collection of Python modules (files) organized in directories. A


package allows you to organize and structure your Python code in a way that is modular,
reusable, and easy to maintain. A package can contain sub-packages (nested packages),
modules, and other resources like data files.
A Python package is essentially a directory that contains a special file called __init__.py.
This file is executed when the package or any of its modules are imported. Even though in
Python 3.3 and later, __init__.py is no longer strictly necessary for packages, it’s still good
practice to include it to clearly define the directory as a package.

Steps to create a Python package:

1. Create a directory for your package.


2. Create Python modules inside the package directory.
3. Add an __init__.py file (it can be empty or contain package initialization code).
4. Import and use the package.

EX:- Let's create a simple package called mypackage that has two modules module1.py and
module2.py.

1. Create the directory structure:

mypackage/
__init__.py
module1.py
module2.py

2. Content of module1.py:

# mypackage/module1.py
def greet():
return "Hello from module 1!"

3. Content of module2.py:

# mypackage/module2.py
def farewell():
return "Goodbye from module 2!"

4. Content of __init__.py:

# mypackage/__init__.py
# This can be left empty or contain package-level variables or
functions.

5. Using the package:

Now, you can use this package in another Python script by importing it:

# Using the package in another script

# Import the specific modules


from mypackage.module1 import greet
from mypackage.module2 import farewell

print(greet()) # Output: Hello from module 1!


print(farewell()) # Output: Goodbye from module 2!
Alternatively, you can import the entire package:

import mypackage.module1
import mypackage.module2

print(mypackage.module1.greet()) # Output: Hello from module 1!

print(mypackage.module2.farewell()) # Output: Goodbye from module 2!

c) What is an anonymous function? How to create it? Explain with example.

An anonymous function in Python is a function that does not have a name. It's typically
created using the lambda keyword. These functions are used for short, one-time operations
where defining a full function with a name might be overkill. Anonymous functions are often
used in places like map(), filter(), sorted(), etc., where a small function is required
temporarily.

1. Creating an anonymous function: You can create an anonymous function using the
lambda keyword followed by the parameters and the expression. The syntax is:

lambda arguments: expression

 Arguments: The input parameters (can be zero or more).


 Expression: A single expression whose result is returned by the function.

Example 1: Adding two numbers


# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8

o (The lambda function takes two arguments x and y, and returns their sum.)

Example 2: Sorting a list of tuples based on the second value using lambda
# List of tuples
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]

# Sort based on the second element of each tuple (value)


pairs.sort(key=lambda x: x[1])

print(pairs) # Output: [(1, 'one'), (2, 'two'), (3, 'three')]

o (The lambda function is used as the sorting key to sort the list of tuples based on the
second value in each tuple.)

d) Explain the following loops with example:

i) While loop :- A while loop repeatedly executes a block of code as long as a specified
condition evaluates to True. Once the condition becomes False, the loop terminates.

Syntax:
while condition:
# Code block

 The condition is checked before each iteration. If it evaluates to True, the loop body is
executed; otherwise, the loop ends.
 Make sure to include logic inside the loop that eventually makes the condition False, or
you'll get an infinite loop.

Example: Counting from 1 to 5


count = 1 #OUTPUT:
while count <= 5: 1
print(count) 2
count += 1 3
4
5

In this example, the while loop runs as long as count is less than or equal to 5. The count
+= 1 inside the loop ensures that the loop will eventually terminate.

ii)For loop :- A for loop is used to iterate over a sequence (like a list, tuple, string, or range).
The loop executes once for each item in the sequence.

Syntax:

for variable in sequence:


# Code block

 The variable takes the value of each item in the sequence one by one.
 The loop body executes for each item in the sequence until all items are processed.

Example: Iterating over a list of numbers


numbers = [1, 2, 3, 4, 5] #OUTPUT:
for num in numbers: 1
print(num) 2
3
4
5

In this example, the for loop iterates over the list numbers and prints each element.

Example: Using range() with a for loop

The range() function generates a sequence of numbers, which is often used in for loops for
a specific range of iterations.

for i in range(1, 6): # range(start, stop) #OUTPUT:


print(i) 1
2
3
4
5
Here, the for loop iterates over the numbers from 1 to 5 (note that the stop value is
exclusive, so it stops before 6).

e) How to perform input and output operations? Explain with example.

i)Input Operation(input()) :- The input() function is used to take user input from the
console. It always returns the input as a string.

 Syntax: input(prompt)
o prompt is an optional string that is displayed to the user before taking input.

Example: Taking user input


name = input("Enter your name: ")
print("Hello, " + name + "!")

Output: Enter your name: Alice

Hello, Alice!

In this example, input() takes a string input from the user, and print() displays a greeting
message.

ii) Output Operation(print()) :- The print() function is used to display output to the console.
It can take multiple arguments and can automatically handle the conversion of data types to
string.

 Syntax: print(arg1, arg2, ..., sep=' ', end='\n')


o arg1, arg2, ...: Values to be printed.
o sep: A string inserted between arguments (defaults to a space).
o end: A string appended at the end of the printed output (defaults to a newline).

Example: Printing values


name = "Alice"
age = 30
print("Name:", name, "Age:", age)

Output: Name: Alice Age: 30

In this example, print() outputs both the name and age variables.

Example: Using end and sep in print


print("Hello", "World", sep="-", end="!\n")

Output: Hello-World!

 The sep argument is used to specify the separator between the arguments (in this case, a
dash -).
 The end argument specifies the ending character (in this case, an exclamation mark and a
newline \n).
Q3]

a) Program to Accept a String and Display it in Reverse Order Eliminating


the Letter 's'
# Program to reverse the string and eliminate letter 's'
# Accept input from the user
# Remove all occurrences of the letter 's' (both lowercase and uppercase)
# Reverse the string
# Display the reversed string
 input_string = input("Enter a string: ")
 modified_string = input_string.replace('s', '').replace('S', '')
 reversed_string = modified_string[::-1]
 print("Reversed string without 's':", reversed_string)

Example: Enter a string: Success

Reversed string without 's': ecce

b) Program to Raise a User-Defined Exception to Check if Age is Less Than


18

In this program, if the user inputs an age less than 18, an AgeException is raised, and an
error message is printed. The ValueError exception is also handled in case the user does not
input a valid integer.

# User-defined exception for age less than 18

class AgeException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)

# Function to check age


def check_age(age):
if age < 18:
raise AgeException("Age is less than 18, access denied.")
else:
print("Access granted.")

# Accept age from the user


try:
age = int(input("Enter your age: "))
check_age(age)
except AgeException as e:
print(e)
except ValueError:
print("Please enter a valid number for age.")

Example: Enter your age: 16

Age is less than 18, access denied.


c) Program to Check if a String Contains Only a Certain Set of Characters (a-
z, A-Z, and 0-9)
# Program to check if the string contains only a-z, A-Z, and 0-9

# Accept input from the user


input_string = input("Enter a string: ")

# Check if the string contains only a-z, A-Z, and 0-9


if input_string.isalnum():
print("The string contains only valid characters (a-z, A-Z, 0-9).")
else:
print("The string contains invalid characters.")

Example: Enter a string: Hello123

The string contains only valid characters (a-z, A-Z, 0-9).

If the string contains any characters other than alphanumeric characters (like spaces,
punctuation, etc.), the program will print that the string contains invalid characters.

Q4]

a) Python Program to Add ‘ing’ or ‘ly’ Based on the Given String


# Function to modify the string
def modify_string(s):
# Check if the length of the string is at least 3
if len(s) >= 3:
# If the string ends with 'ing', add 'ly'
if s.endswith('ing'):
return s + 'ly'
# Otherwise, add 'ing'
else:
return s + 'ing'
else:
# If the string length is less than 3, return it unchanged
return s

# Input from the user


input_string = input("Enter a string: ")

# Modify and print the string


modified_string = modify_string(input_string)
print("Modified string:", modified_string)
Example:

 Input:Enter a string: swim


 Output:Modified string: swimming

If the input string ends with "ing", like "sing", it will append "ly" instead:

 Input:Enter a string: sing


 Output:Modified string: singly

If the string has fewer than 3 characters, it remains unchanged:

 Input:Enter a string: hi
 Output:Modified string: hi

b) Python Program to Combine Values in a List of Dictionaries


from collections import Counter

# Sample data
 data = [{'item': 'item 1', 'amount': 400},
{'item': 'item2', 'amount': 300},
{'item': 'item1', 'amount': 750}]

# Initialize an empty Counter


 counter = Counter()

# Combine the amounts based on the item key


 for entry in data:
counter[entry['item']] += entry['amount']

# Print the resulting Counter


print(counter)
Output:
 Counter({'item1': 1150, 'item2': 300})

 Explanation:
o We iterate over each dictionary in the list and update the Counter object.
o The Counter keeps a running total for each unique item.
o After processing, we get the total amount for each item.

c) Python Program to Extract Year, Month, Date, and Time Using Lambda

Using the datetime module and a lambda function.

from datetime import datetime

# Get the current date and time


now = datetime.now()

# Lambda function to extract year, month, day, and time


extract_info = lambda dt: (dt.year, dt.month, dt.day, dt.hour, dt.minute,
dt.second)

# Extract and print the information


year, month, day, hour, minute, second = extract_info(now)
print("Year:", year)
print("Month:", month)
print("Day:", day)
print("Hour:", hour)
print("Minute:", minute)
print("Second:", second)
Output (Example):
Year: 2024
Month: 11
Day: 27
Hour: 12
Minute: 45
Second: 30

 Explanation:
o datetime.now() gives the current date and time.
o The lambda function extract_info takes a datetime object and returns a tuple
with the year, month, day, hour, minute, and second.
o We extract these values and print them.

Summary:

 a) The program modifies a string by adding "ing" or "ly" based on the string's conditions.
 b) The program combines values of the amount key in a list of dictionaries using Counter.
 c) The program uses a lambda function to extract the year, month, date, hour, minute, and
second from the current date and time.

Q5]
a) Check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']
Check2 = check1
Check3 = check1 [:]
Check2[0] = 'Code'
Check3[1] = 'Mcq'
Count = 0
For c in (check 1, check2 check3):
if c[0] == 'Code':
count + = 1
if c[1] == 'Mcq':
count + = 10

print (count)
 Ans=>

# Initial lists

 Check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']


 Check2 = Check1 # Check2 references Check1 (shallow copy, not a deep copy)
 Check3 = Check1[:] # Check3 is a shallow copy of Check1

# Modify elements
 Check2[0] = 'Code'
 Check3[1] = 'Mcq'

# Initialize counter

 count = 0

# Loop through Check1, Check2, and Check3

for c in (Check1, Check2, Check3):

if c[0] == 'Code': # Check if the first element is 'Code'

count += 1

if c[1] == 'Mcq': # Check if the second element is 'Mcq'

count += 10

# Print the result

 print(count)->12

b) Counter = {}
Def add To Counter (Country):
If country in counter:
Counter [country] + = 1
Else:
Counter [country] = 1
Add To Counter ('China')
Add To Counter ('Japan')
Add To Counter ('china')
Print (len(counter))
 Ans=>
# Initialize an empty dictionary to store the country counts

 counter = {}

# Function to add countries to the counter

 def add_to_counter(country):

# Convert the country to lowercase to make the count case-insensitive

country = country.lower() # This ensures that 'China' and 'china' are counted as the same

if country in counter:

counter[country] += 1 # Increment the count for the country


else:

counter[country] = 1 # Initialize the count for the country

# Add countries to the counter

 add_to_counter('China')
 add_to_counter('Japan')
 add_to_counter('china') # This will be counted as the same as 'China'

# Print the number of unique countries in the counter

 print(len(counter))
 2

You might also like