0% found this document useful (0 votes)
32 views18 pages

PWP Exam Programs

The document contains Python code snippets demonstrating various Python programming concepts like functions, loops, conditional statements, lists, tuples, sets, dictionaries and string operations. The code snippets cover basics as well as more advanced concepts like scope of variables in functions, default arguments, keyword arguments etc.

Uploaded by

ghanshampawar25
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)
32 views18 pages

PWP Exam Programs

The document contains Python code snippets demonstrating various Python programming concepts like functions, loops, conditional statements, lists, tuples, sets, dictionaries and string operations. The code snippets cover basics as well as more advanced concepts like scope of variables in functions, default arguments, keyword arguments etc.

Uploaded by

ghanshampawar25
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/ 18

'''

#3. WAP to find sum of first 10 natural nos.


sum = 0
for i in range(1,11,1):
sum = sum+i
print("sum is : ",sum)
'''

'''
#4. WAP to display n terms of the Fibonacci series.
n = int(input("Enter no of term : "))
i=1
t1,t2 = -1,1
while i<=n:
t = t1+t2
print(t,end = "")
t1 = t2
t2 = t
i+=1
'''

'''
#25. WAP with function to calculate the factorial of a given number.
no=int(input("Enter No : "))
fact=1
if no<0:
print("Sorry factorial does not exist for negative numbers")
elif no == 0:
print("Factorial of 0 is 1")
else:
for i in range(1,no+1):
fact*=i
print("Factorial of",no,"is",fact)
'''

'''
#2. WAP to check if given number is palindrome or not.
no = int(input("Enter No : "))
temp = no
rev = 0
while(no>0):
rem = no%10
rev = rev*10+rem
no = no//10
if temp==rev:
print("Palndrome")
else:
print("Not a Palindrome")
'''

'''
#1. WAP to display the sum of digits and reverse of a number.
no = int(input("Enter No : "))
sum = 0
rev = 0
while no>0:
rem = no%10
rev = rev*10+rem
sum+=rem
no = no//10
print("Sum is :",sum,"Reverse is :",rev)
'''

'''
#5. WAP to create a list and demonstrate any four list methods.
l1 = [5,10,3,2,7]
print(l1.count(10))
l1.append(13)
print(l1)
l1.sort()
print(l1)
l1.reverse()
print(l1)
l1.pop(0)
print(l1)
'''

'''
#6. WAP to find the repeated elements of a list.
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]

uniqueList = []
duplicateList = []

for i in lis:
if i not in uniqueList:
uniqueList.append(i)
elif i not in duplicateList:
duplicateList.append(i)

print(duplicateList)
'''

'''
#7. WAP using list comprehension to create a list of cubes of all nos upto 10.
l = [1, 2, 3, 4]
res = []
for i in l:
res.append(i*i*i)
print(res)
'''

'''
#8. WAP using list comprehension to create a list of squares of all even nos from a given list.
data=[1,2,3,4,5,6,7,8]
result = [i*i for i in data if i%2==0]
print(result)
'''

'''
#9. WAP using list comprehension to include all strings in given list except those with letter ‘a’.
string_list = ['apple', 'banana', 'orange', 'kiwi', 'pear', 'grape']
filtered_list = [string for string in string_list if 'a' not in string]
print(filtered_list)
'''

'''
#10. WAP to create a tuple and demonstrate any four tuple methods/functions.
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)

# Demonstrating tuple methods/functions

# 1. count() - returns the number of occurrences of a specified value in the tuple


print("Number of occurrences of 3 in the tuple:", my_tuple.count(3))
# 2. index() - returns the index of the first occurrence of a specified value
print("Index of the first occurrence of 4 in the tuple:", my_tuple.index(4))

# 3. len() - returns the length of the tuple


print("Length of the tuple:", len(my_tuple))

# 4. max() - returns the largest item in the tuple


print("Maximum value in the tuple:", max(my_tuple))
'''

'''
#11. WAP to create a tuple from two existing tuples using slicing.
# Two existing tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Create a new tuple from two existing tuples using slicing


new_tuple = tuple1 + tuple2

# Print the new tuple


print("New tuple:", new_tuple)
'''

'''
#12. WAP to create a set and demonstrate any four set methods.
# Create a set
my_set = {1, 2, 3, 4, 5}

# 1. add() - Adds an element to the set


my_set.add(6)
print("After adding 6:", my_set)

# 2. remove() - Removes a specified element from the set


my_set.remove(3)
print("After removing 3:", my_set)

# 3. pop() - Removes and returns an arbitrary element from the set


popped_element = my_set.pop()
print("Popped element:", popped_element)
print("After popping an element:", my_set)
# 4. clear() - Removes all elements from the set
my_set.clear()
print("After clearing the set:", my_set)
'''

'''
#13. WAP using set comprehension to create a set of multiples of 5 till 100.
# Set comprehension to create a set of multiples of 5 till 100
multiples_of_5 = {x for x in range(1, 101) if x % 5 == 0}

# Print the set of multiples of 5


print("Multiples of 5 till 100:", multiples_of_5)
'''

'''
#14. WAP to create a dictionary and demonstrate any four dictionary methods.
# Create a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 4, 'kiwi': 5}

# 1. keys() - Returns a view of all the keys in the dictionary


print("Keys:", my_dict.keys())

# 2. values() - Returns a view of all the values in the dictionary


print("Values:", my_dict.values())

# 3. items() - Returns a view of all key-value pairs in the dictionary


print("Items:", my_dict.items())

# 4. get() - Returns the value associated with the specified key


print("Value for 'banana':", my_dict.get('banana'))

# Changing the value associated with a key


my_dict['banana'] = 6

# Printing the updated dictionary


print("Updated dictionary:", my_dict)
'''

'''
#15. WAP to combine values of two dictionaries having similar keys and create a new dictionary.
# Two dictionaries with similar keys
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 4, 'b': 5, 'd': 6}

# Combine values of dictionaries with similar keys


combined_dict = {}

for key in dict1.keys() & dict2.keys():


combined_dict[key] = (dict1[key], dict2[key])

# Print the combined dictionary


print("Combined Dictionary:", combined_dict)
'''

'''
#16. WAP to sort a dictionary by values.
# Dictionary to be sorted
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}

# Sort the dictionary by values


sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

# Print the sorted dictionary


print("Sorted Dictionary by Values:", sorted_dict)
'''

'''
#17. WAP to find all unique values in a dictionary.
# Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 3, 'e': 2}

# Get unique values from the dictionary using a set comprehension


unique_values = {value for value in my_dict.values()}

# Print the unique values


print("Unique values in the dictionary:", unique_values)
'''

'''
#18. WAP to demonstrate four built in string functions.
# 1. len() - Returns the length of the string
string = "Hello, World!"
print("Length of the string:", len(string))

# 2. upper() - Converts all characters in the string to uppercase


uppercase_string = string.upper()
print("Uppercase string:", uppercase_string)

# 3. split() - Splits the string into a list of substrings based on a delimiter


words = string.split(", ")
print("Split string into words:", words)

# 4. find() - Returns the index of the first occurrence of a specified substring


index = string.find("World")
print("Index of 'World' in the string:", index)
'''

'''
#19. WAP to count the number of vowels in the given string.
# Input string
input_string = "Hello, World!"

# Define vowels
vowels = "aeiouAEIOU"

# Initialize counter
count = 0

# Loop through each character in the string


for char in input_string:
# Check if the character is a vowel
if char in vowels:
count += 1

# Print the result


print("Number of vowels in the string:", count)
'''

'''
#20. WAP to find the least frequency character in given string.
# Input string
input_string = "hello world"

# Create a dictionary to store character frequencies


char_freq = {}

# Count frequencies of characters in the string


for char in input_string:
char_freq[char] = char_freq.get(char, 0) + 1

# Find the least frequent character


least_freq_char = min(char_freq, key=char_freq.get)

# Print the least frequent character


print("The least frequent character in the string is:", least_freq_char)
'''

'''
#21. WAP to demonstrate the L-E-G function scope in Python.
# Global variable
global_var = 10

def outer_function():
# Enclosing variable
enclosing_var = 20

def inner_function():
# Local variable
local_var = 30
print("Inside inner_function:")
print("Local variable:", local_var)
print("Enclosing variable:", enclosing_var)
print("Global variable:", global_var)

print("Inside outer_function:")
print("Enclosing variable:", enclosing_var)
print("Global variable:", global_var)

# Call inner function


inner_function()
# Call outer function
outer_function()
'''

'''
#22. WAP to demonstrate user defined functions with default arguments.
# Function with default arguments
def greet(name="Guest", country="India"):
print("Hello,", name, "! Welcome to", country)

# Calling the function with default arguments


greet()

# Calling the function with a specific name and default country


greet("Rohan")

# Calling the function with specific name and country


greet("Alice", "USA")
'''

'''
#23. WAP to demonstrate user defined functions with keyword arguments.
# Function to calculate the area of a rectangle
def calculate_area(length, width=5):
area = length * width
return area

# Calling the function with positional arguments


print("Area with default width (5):", calculate_area(4))

# Calling the function with keyword arguments


print("Area with custom width (3):", calculate_area(length=4, width=3))

# Calling the function with a mix of positional and keyword arguments


print("Area with custom width (6):", calculate_area(3, width=6))
'''
'''
#24. WAP with function that takes a number as parameter and checks if it is prime or not.
# Function to check if a number is prime
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True

# Input number
num = int(input("Enter a number: "))

# Check if the number is prime


if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
'''

'''
#26. WAP with function to calculate the number of uppercase and lowercase characters in given
string.
# Function to calculate the number of uppercase and lowercase characters
def count_upper_lower(string):
upper_count = sum(1 for char in string if char.isupper())
lower_count = sum(1 for char in string if char.islower())
return upper_count, lower_count

# Input string
input_string = input("Enter a string: ")

# Call the function to count uppercase and lowercase characters


upper, lower = count_upper_lower(input_string)

# Print the results


print("Number of uppercase characters:", upper)
print("Number of lowercase characters:", lower)
'''
'''
#27. WAP with function to find the smallest and largest word in a given string.
# Function to find the smallest and largest word
def find_smallest_largest_word(string):
words = string.split()
smallest_word = min(words, key=len)
largest_word = max(words, key=len)
return smallest_word, largest_word

# Input string
input_string = input("Enter a string: ")

# Call the function to find the smallest and largest words


smallest, largest = find_smallest_largest_word(input_string)

# Print the results


print("Smallest word:", smallest)
print("Largest word:", largest)
'''

#28. WAP to access and demonstrate any four functions of math module.
import math

# 1. Square root function (math.sqrt)


number = 16
square_root = math.sqrt(number)
print("Square root of", number, "is", square_root)

# 2. Exponential function (math.exp)


exponent = 5
result = math.exp(exponent)
print("Exponential of", exponent, "is", result)

# 3. Ceiling function (math.ceil)


number = 4.3
ceiling_value = math.ceil(number)
print("Ceiling of", number, "is", ceiling_value)

# 4. Floor function (math.floor)


number = 4.3
floor_value = math.floor(number)
print("Floor of", number, "is", floor_value)

'''
#29. WAP to access and demonstrate four functions of any built-in Python module.
import random

# 1. Random integer between a range (random.randint)


random_number = random.randint(1, 10)
print("Random number between 1 and 10:", random_number)

# 2. Random floating-point number between 0 and 1 (random.random)


random_float = random.random()
print("Random floating-point number between 0 and 1:", random_float)

# 3. Random choice from a sequence (random.choice)


colors = ['red', 'blue', 'green', 'yellow']
random_color = random.choice(colors)
print("Randomly chosen color:", random_color)

# 4. Random shuffle of a list (random.shuffle)


deck_of_cards = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
random.shuffle(deck_of_cards)
print("Shuffled deck of cards:", deck_of_cards)
'''

'''
#30. WAP to access methods of a user defined module.
# my_module.py

def greet(name):
return "Hello, " + name + "!"

def add(x, y):


return x + y

# main.py

import my_module
# Accessing the greet function
message = my_module.greet("Alice")
print(message)

# Accessing the add function


result = my_module.add(5, 3)
print("Result of addition:", result)
'''

'''
#31. WAP illustrating the use of user defined package in Python.

# operations.py

def add(x, y):


return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
raise ValueError("Cannot divide by zero")
return x / y

# main.py

import operations as ops

# Using functions from the user-defined package


Add_result = ops.add(5, 3)
print("Addition:", Add_result)

Sub_result = ops.subtract(8, 3)
print("Substraction:", Sub_result)

Mul_result = ops.multiply(4, 2)
print("Multiplication:", Mul_result)
'''

'''
#32. WAP to create a class and display class attributes.
class Student:
# Class attribute
college_name = "SSVPS"

def __init__(self, name, roll_number):


# Instance attributes
self.name = name
self.roll_number = roll_number

# Create an instance of the Student class


student1 = Student("Ghansham", 59)

# Display class attributes


print("School name:", Student.college_name)
print("Student name:", student1.name)
print("Roll number:", student1.roll_number)
'''

'''
#33. WAP to access object methods.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_info(self):
print("Car brand:", self.brand)
print("Car model:", self.model)

def start_engine(self):
print("Engine started for", self.brand, self.model)

# Create an instance of the Car class


my_car = Car("Toyota", "Corolla")

# Access object methods


my_car.display_info()
my_car.start_engine()
'''

'''
#34. WAP to demonstrate data hiding.
class Car:
def __init__(self, brand, model, price):
self.__brand = brand # Private attribute
self.__model = model # Private attribute
self.__price = price # Private attribute

def display_info(self):
print("Car brand:", self.__brand)
print("Car model:", self.__model)
print("Car price:", self.__price)

def __start_engine(self): # Private method


print("Engine started for", self.__brand, self.__model)

# Create an instance of the Car class


my_car = Car("Toyota", "Corolla", 25000)

# Access public method to display information


my_car.display_info()

# Attempt to access private attribute directly (will raise AttributeError)


# print("Car brand:", my_car.__brand)

# Attempt to access private method directly (will raise AttributeError)


# my_car.__start_engine()
'''

'''
#35. WAP to demonstrate method overriding.
class Animal:
def make_sound(self):
print("Generic animal sound")

class Dog(Animal):
def make_sound(self):
print("Bark")
class Cat(Animal):
def make_sound(self):
print("Meow")

# Create instances of Dog and Cat classes


dog = Dog()
cat = Cat()

# Call the overridden method for each instance


dog.make_sound() # Outputs: Bark
cat.make_sound() # Outputs: Meow
'''

'''
#36. WAP to demonstrate multiple inheritance.
class Vehicle:
def __init__(self, color):
self.color = color

def drive(self):
print("Driving the vehicle")

class Electric:
def __init__(self, battery_capacity):
self.battery_capacity = battery_capacity

def charge(self):
print("Charging the battery")

class ElectricCar(Vehicle, Electric):


def __init__(self, color, battery_capacity):
Vehicle.__init__(self, color)
Electric.__init__(self, battery_capacity)

def display_info(self):
print("Electric car color:", self.color)
print("Battery capacity:", self.battery_capacity)

# Create an instance of ElectricCar


my_car = ElectricCar("Blue", "5000 mAh")
# Access methods from both parent classes
my_car.drive() # Outputs: Driving the vehicle
my_car.charge() # Outputs: Charging the battery

# Access method from the subclass


my_car.display_info() # Outputs: Electric car color: Blue, Battery capacity: 5000 mAh
'''

'''
#37. WAP to demonstrate multilevel inheritance.
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def bark(self):
print("Dog barks")

class GoldenRetriever(Dog):
def fetch(self):
print("Golden Retriever fetches")

# Create an instance of GoldenRetriever


my_dog = GoldenRetriever()

# Access methods from all levels of inheritance


my_dog.speak() # Outputs: Animal speaks
my_dog.bark() # Outputs: Dog barks
my_dog.fetch() # Outputs: Golden Retriever fetches
'''

'''
#38. WAP to open a file in append mode, write data to it and then read it.
# Open the file in append mode and write data to it
with open("my_file.txt", "a") as file:
file.write("This is line 1\n")
file.write("This is line 2\n")
file.write("This is line 3\n")

# Open the file in read mode and read its contents


with open("my_file.txt", "r") as file:
content = file.read()

# Print the contents of the file


print("Contents of the file:")
print(content)
'''

'''
#39. WAP to read contents of file1.txt and write the same to file2.txt.
# Read the contents of file1.txt
with open("file1.txt", "r") as file1:
content = file1.read()

# Write the contents to file2.txt


with open("file2.txt", "w") as file2:
file2.write(content)

print("Contents of file1.txt have been written to file2.txt.")


'''

'''
#40. WAP to raise the ZeroDivisionError exception.
def divide(x, y):
try:
result = x / y # Attempt division
except ZeroDivisionError: # Catch ZeroDivisionError exception
print("Error: Division by zero!") # Print error message
else: # If no exception occurs
print("Result:", result) # Print result if division is successful
finally: # Finally block always executes
print("Division operation completed.") # Print completion message

# Test cases
divide(10, 2) # Normal division
divide(5, 0) # Division by zero
'''

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy