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

Python Programming

The document provides a comprehensive overview of Python programming concepts, including syntax, data structures, functions, exception handling, and file operations. It includes code examples for various topics such as loops, input/output operations, and user-defined exceptions. Additionally, it covers advanced topics like packages, regular expressions, and lambda functions.

Uploaded by

r85761741
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Programming

The document provides a comprehensive overview of Python programming concepts, including syntax, data structures, functions, exception handling, and file operations. It includes code examples for various topics such as loops, input/output operations, and user-defined exceptions. Additionally, it covers advanced topics like packages, regular expressions, and lambda functions.

Uploaded by

r85761741
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python Programming

Q.1) 1 mark

1. Indentation: Indentation in Python is used to define code blocks and control flow. It is
essential for the language's readability and structure.
2. Printing List Elements:

Python

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


for element in my_list:
print(element)

Use code with caution.

3. Slice Operator: The slice operator ([start:stop:step]) is used to extract a portion of


a sequence (like a list or string).
4. Variable-Length Arguments: Functions can accept a variable number of arguments using
the *args syntax.
5. Adding Multiple Elements to a List:

Python

my_list = [1, 2, 3]
my_list.extend([4, 5, 6])

Use code with caution.

6. remove() Method: Removes the first occurrence of a specified element from a list.
7. Lambda Function to Add 10:

Python

add_10 = lambda x: x + 10

Use code with caution.

8. Raising Exceptions with Arguments:

Python

raise ValueError("Invalid input: ", value)

Use code with caution.

9. re Package Methods: match(), search(), findall(), sub(), split()


10. wb Mode in File: Write binary mode. Opens a file for writing binary data.
11. Comments in Python: Use # for single-line comments and triple quotes (""") for multi-line
comments.
12. index() in String: Returns the index of the first occurrence of a substring.
13. range() Function: Creates a sequence of numbers. Parameters: start, stop, step.
14. Void Function: A function that doesn't return a value. Use return None or omit the
return statement.
15. pop() vs. del: pop() removes an element by index and returns it. del removes an element
by index or slice.
16. List vs. Tuple: Lists are mutable (can be changed), while tuples are immutable (cannot be
changed).

Specific Topics

17. clock() and gmtime(): clock() returns the processor time, while gmtime() returns a
tuple representing the current time in UTC.
18. Exception Handling Syntax:

Python
try:
# code that might raise an exception
except ExceptionType as e:
# code to handle the exception
finally:
# code that always executes
Use code with caution.

19. math Module Functions: sqrt(), sin(), cos(), tan(), log()


20. enumerate(): Returns an iterator that yields tuples containing the index and value of each
item in a sequence.
21. Advantages of Python: Readability, versatility, large standard library, community support.
22. Lists vs. Tuples: Lists are mutable, tuples are immutable. Lists use square brackets, tuples
use parentheses.
23. Python as a Scripting Language: Python can be used to write scripts for automating tasks
and performing calculations.
24. Sets: Unordered collections of unique elements. Example: my_set = {1, 2, 3}
25. Dictionaries: Key-value pairs. Example: my_dict = {"name": "Alice", "age":
30}
26. Regular Expressions: Patterns used to match text. Example: import re;
re.search("hello", "hello world")
27. User-Defined Modules: Python files containing functions and variables that can be imported
into other programs.
28. Case Sensitivity: Python is case-sensitive. variable and Variable are different.
29. Dry Run: Manually executing a program step-by-step to understand its behavior.
30. Lambda Functions: Anonymous functions defined using the lambda keyword. Example:
lambda x: x + 1
31. Selection Statements: if, else, elif statements are used for conditional execution.
32. Type Conversion: int(), float(), str(), bool(), etc.
33. pass Statement: A placeholder that does nothing. Useful in function bodies or control flow
statements where code is not yet implemented.
34. extend() Method: Adds elements from another iterable to a list.
35. Required Arguments: Arguments that must be provided when a function is called.
36. time Module Functions: time(), sleep()
37. Types of Files: Text files, binary files, CSV files, JSON files, XML files, etc.
38. seek() and tell() Functions: seek() moves the file pointer to a specific position. tell()
returns the current position of the file pointer.
Q.2) 2 marks

1. Packages

A package is a collection of Python modules that are organized into a directory structure. This allows
for better organization and reusability of code.

Creating a Package:

1. Create a new directory with the desired package name.


2. Inside the directory, create an empty file named __init__.py. This file indicates to Python
that the directory is a package.
3. Create Python modules within the directory.
4. Import modules from the package using the dot notation: import
package_name.module_name.

Example:

Python
# package_name/module1.py
def function1():
print("This is function1 from module1")

# package_name/module2.py
def function2():
print("This is function2 from module2")

# main.py
import package_name.module1
import package_name.module2

package_name.module1.function1()
package_name.module2.function2()

2. Tuple Functions

• zip(): Creates a tuple of tuples, combining elements from multiple iterables.


• tuple(): Converts an iterable into a tuple.
• count(): Returns the number of occurrences of a specified element in a tuple.
• index(): Returns the index of the first occurrence of a specified element in a tuple.

3. Anonymous Functions (Lambda Functions)

Anonymous functions are functions defined without a name using the lambda keyword. They are
often used for simple, one-time functions.

Example:

Python
add = lambda x, y: x + y
result = add(10, 20)
print(result) # Output: 30
4. Loops

i) While Loop: Executes a block of code repeatedly as long as a condition is true.

Python
count = 0
while count < 5:
print("Count:", count)
count += 1

ii) For Loop: Iterates over a sequence of elements.

Python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

5. Input/Output Operations

Input:

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

Output:

Python
print("Hello, world!")

6. Reading from a File

• read(): Reads the entire contents of a file as a string.


• readline(): Reads a single line from a file.

Python
# Reading the entire file
with open("file.txt", "r") as f:
content = f.read()
print(content)

# Reading line by line


with open("file.txt", "r") as f:
for line in f:
print(line)

7. Dictionary Methods

• copy(): Creates a shallow copy of a dictionary.


• get(): Retrieves the value of a specified key, or a default value if the key doesn't exist.
• items(): Returns a view of the dictionary's key-value pairs as tuples.
• keys(): Returns a view of the dictionary's keys.
8. Union and Intersection

Union: Combines elements from two sets, removing duplicates.

Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}

Intersection: Finds the elements common to both sets.

Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set) # Output: {3}

9. Statements

• continue: Skips the rest of the current iteration and moves to the next iteration.
• if: Executes a block of code if a condition is true.
• if-else: Executes one block of code if a condition is true, and another block if it's false.
• break: Exits a loop.

10. Features of Python

• Interpreted language: No compilation required.


• Dynamic typing: Variables can change data types during execution.
• Object-oriented programming: Supports classes and objects.
• Large standard library: Includes modules for various tasks.
• Cross-platform compatibility: Runs on different operating systems.

11. Calculating X^Y

Python
x = int(input("Enter the base: "))
y = int(input("Enter the exponent: "))
result = x ** y
print("Result:", result)

12. Perfect Number

Python
num = int(input("Enter a number: "))
sum_of_divisors = 0
for i in range(1, num):
if num % i == 0:
sum_of_divisors += i
if sum_of_divisors == num:
print(num, "is a
perfect number")
else:
print(num, "is not a perfect number")
13. seek() and tell()

• seek(): Moves the file pointer to a specific position.


• tell(): Returns the current position of the file pointer.

14. List Slicing

Python
my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4] # Elements from index 1 to 3 (exclusive)
print(sliced_list) # Output: [2, 3, 4]

15. Tuples are Ordered

Tuples are ordered collections, meaning the elements maintain their position and can be accessed by
index.

16. Exception Handling

Python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero")

17. Metacharacters in Regular Expressions

• \d: Matches any digit (0-9).


• \w: Matches any word character (alphanumeric or underscore).

18. Built-in List Functions

• append(): Adds an element to the end of a list.


• sort(): Sorts the elements of a list in ascending order.

19. Backward Indexing in Strings

Python
my_string = "hello"
print(my_string[-1]) # Output: o

20. Identifiers

Identifiers are names given to variables, functions, classes, and modules. They must start with a letter
or underscore and can contain letters, digits, and underscores.
(Q.3)&(Q.4) 4 marks

1. Program to accept a string from user and display the string in reverse order eliminating the
letter ‘s’:

python
Copy code
# Reverse string and remove 's'
def reverse_remove_s(string):
return ''.join([char for char in string[::-1] if char.lower() !=
's'])

string = input("Enter a string: ")


print(reverse_remove_s(string))

2. Program to raise a user-defined exception to check if age is less than 18:

python
Copy code
class AgeException(Exception):
def __init__(self, age):
self.age = age
super().__init__(f"Age {age} is less than 18.")

def check_age(age):
if age < 18:
raise AgeException(age)
else:
print("Age is acceptable.")

try:
age = int(input("Enter age: "))
check_age(age)
except AgeException as e:
print(e)

3. Program to check if a string contains only a certain set of characters (a-z, A-Z, 0-9):

python
Copy code
import re

def is_valid_string(s):
return bool(re.match('^[a-zA-Z0-9]+$', s))

string = input("Enter a string: ")


print("Valid string" if is_valid_string(string) else "Invalid
string")

4. Program to add ‘ing’ or ‘ly’ to a string:

python
Copy code
def add_ing_ly(string):
if len(string) >= 3:
if string.endswith('ing'):
return string + 'ly'
else:
return string + 'ing'
return string

string = input("Enter a string: ")


print(add_ing_ly(string))

5. Program to combine values in a list of dictionaries:

python
Copy code
from collections import Counter

data = [{'item': 'item1', 'amount': 400}, {'item': 'item2',


'amount': 300}, {'item': 'item1', 'amount': 750}]
counter = Counter()

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

print(counter)

6. Program to extract year, month, date, and time using Lambda:

python
Copy code
import datetime

now = datetime.datetime.now()

year = lambda x: x.year


month = lambda x: x.month
day = lambda x: x.day
time = lambda x: x.time()

print("Year:", year(now))
print("Month:", month(now))
print("Day:", day(now))
print("Time:", time(now))

7. Program to swap first two characters of two strings:

python
Copy code
def swap_first_two_chars(s1, s2):
return s2[:2] + s1[2:], s1[:2] + s2[2:]

str1 = input("Enter first string: ")


str2 = input("Enter second string: ")
result = swap_first_two_chars(str1, str2)
print(result[0], result[1])
8. Program to display power of 2 up to a given number using anonymous function:

python
Copy code
N = int(input("Enter a number: "))
powers_of_two = list(map(lambda x: 2 ** x, range(N+1)))

for i in range(len(powers_of_two)):
print(f"2 raised to {i} is {powers_of_two[i]}")

9. Program to read an entire text file:

python
Copy code
def read_file(filename):
with open(filename, 'r') as file:
return file.read()

filename = input("Enter the filename: ")


print(read_file(filename))

10. Program to count vowels and consonants in a string:

python
Copy code
def count_vowels_consonants(string):
vowels = 'aeiouAEIOU'
v_count = c_count = 0
for char in string:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count

string = input("Enter a string: ")


vowels, consonants = count_vowels_consonants(string)
print(f"Vowels: {vowels}, Consonants: {consonants}")

11. Program to print dictionary where keys are numbers between 1 and 15 and values are the
square of keys:

python
Copy code
squares = {i: i**2 for i in range(1, 16)}
print(squares)

12. Program to count upper and lower case letters in a string:

python
Copy code
def count_upper_lower(string):
upper_count = lower_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
return upper_count, lower_count

string = input("Enter a string: ")


upper, lower = count_upper_lower(string)
print(f"Uppercase letters: {upper}, Lowercase letters: {lower}")

13. Program to check for Zero Division Error Exception:

python
Copy code
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

14. Program to find GCD using recursion:

python
Copy code
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
print(f"GCD of {a} and {b} is {gcd(a, b)}")

15. Program to check if a given key exists in a dictionary:

python
Copy code
def check_key(dictionary, key):
return key in dictionary

dictionary = {'a': 1, 'b': 2, 'c': 3}


key = input("Enter key to check: ")
print("Key exists" if check_key(dictionary, key) else "Key does not
exist")
Q.5) 3 marks

a) Check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']

Check2 = Check1

Check3 = Check1[:]

Check2[0] = 'Code'

Check3[1] = 'Mcq'

count = 0

for c in (Check1, Check2, Check3):

if c[0] == 'Code':

count += 1

if c[1] == 'Mcq':

count += 10

print(count)

output: 11

b) counter = {}

def addToCounter(country):

if country in counter:

counter[country] += 1

else:

counter[country] = 1

addToCounter('China')

addToCounter('Japan')

addToCounter('china')

print(len(counter))

output: 3

c) a = True

b = False

c = False

if not a or b:

print(1)

elif not a or not b and c:


print(2)

elif not a or b or not b and a:

print(3)

else:

print(4)

output: 3

d) def f1(x, l=[]):

for i in range(x):

l.append(i * i)

print(l)

f1(2)

f1(3, [3, 2, 1])

f1(3)

output: [0, 1]

[3, 2, 1, 0, 1, 4]

[0, 1, 0, 1, 4]

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

output: 7

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

output: hello

NO

g) sum = 0

for i in range(12, 2, -2):

sum += i

print(sum)

output: 40

h) count = 1

def doThis():

global count

for i in (1, 2, 3):

count += 1

doThis()

print(count)

output: 4

You might also like