0% found this document useful (0 votes)
70 views22 pages

21EC014 Final Assignment

The document contains Python code snippets demonstrating various programming concepts like functions, loops, conditional statements, etc. It includes 16 code snippets/problems covering topics like: 1) Displaying user details 2) Arithmetic operations 3) Converting days to months/weeks 4) Temperature conversion 5) Distance conversion 6) Checking positive/negative numbers 7) Finding largest number 8) Averaging numbers 9) Checking prime numbers 10) Multiplication tables 11) Factorials 12) Break and continue statements 13) Computing gross pay 14) Finding family relationships 15) String input handling 16) Miscellaneous Python programs.

Uploaded by

Aditya Patel
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)
70 views22 pages

21EC014 Final Assignment

The document contains Python code snippets demonstrating various programming concepts like functions, loops, conditional statements, etc. It includes 16 code snippets/problems covering topics like: 1) Displaying user details 2) Arithmetic operations 3) Converting days to months/weeks 4) Temperature conversion 5) Distance conversion 6) Checking positive/negative numbers 7) Finding largest number 8) Averaging numbers 9) Checking prime numbers 10) Multiplication tables 11) Factorials 12) Break and continue statements 13) Computing gross pay 14) Finding family relationships 15) String input handling 16) Miscellaneous Python programs.

Uploaded by

Aditya Patel
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/ 22

EC 1 21EC014

EC262: PYTHON PROGRAMMING


ASSIGNMENT – 7

1) WAP to display basic details of a User like Name, Roll no, Division and
Address.
➢ def personal_details():
name , age = ‘ Sa ’ , 20
address = ‘ Vadodara , india ’
print(‘ Name: { }\nAge: { }\nAddress: { }’.format(name , age,
address ))
personal details()

2) WAP to perform arithmetic operations in python.


➢ num1 = input('Enter first number:')
➢ num2 = input('Enter second number:')
➢ sum = float(num1)+float(num2)
➢ min = float(num1)-float(num2)
➢ mul = float(num1)*float(num2)
➢ div = float(num1)/float(num2)
➢ print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
➢ print('The subtraction of {0} and {1} is
{2}'.format(num1,num2,min))
➢ print('The multiplication of {0} and {1} is
{2}'.format(num1,num2,mul))
➢ print('The division of {0} and {1} is {2}'.format(num1,num2,div))

1
EC 1 21EC014

3) WAP to Convert no. of Days into No. of Months and days.


➢ DAYS_IN_WEEK = 7

➢ def find( number_of_days ):

➢ year = int(number_of_days / 365)
➢ week = int((number_of_days % 365) /
➢ DAYS_IN_WEEK)
➢ days = (number_of_days % 365) % DAYS_IN_WEEK

➢ print("years = ",year,
➢ "\nweeks = ",week,
➢ "\ndays = ",days)


➢ number_of_days = 200
➢ find(number_of_days)

4) WAP to convert temperature from Celsius to Fahrenheit.


➢ celsius = int(input('Enter the celsius:'))
➢ fahrenheit = (celsius * 1.8) + 32
➢ print('%.2f Celsius is equivalent to: %.2f Fahrenheit' %(celsius,
fahrenheit))

5) WAP to convert distance from C.M. into meter, KM., feet, and inches.
➢ cm = int(input("Enter the cm value : "))
➢ meter = cm / 100.0;
➢ kilometer = cm / 100000.0;
➢ feet = cm / 30.48;
➢ inch = cm * 0.393701;
➢ print("Length in meter = " ,
➢ meter , "m");
➢ print("Length in Kilometer = ",
➢ kilometer , "km");
➢ print("Length in Feet = ",

2
EC 1 21EC014

➢ feet , "feet");
➢ print("Length in Inch = ",
➢ inch , "inch");

6) WAP to check whether the number is positive or not.


➢ num = float(input("Enter a number: "))
➢ if num > 0:
➢ print("Positive number")
➢ elif num == 0:
➢ print("Zero")
➢ else:
➢ print("Negative number")

7) WAP to find the largest among three numbers.


➢ num1 = float(input("Enter first number: "))
➢ num2 = float(input("Enter second number: "))
➢ num3 = float(input("Enter third number: "))
➢ if (num1 >= num2) and (num1 >= num3):
➢ largest = num1
➢ elif (num2 >= num1) and (num2 >= num3):
➢ largest = num2
➢ else:
➢ largest = num3
➢ print("The largest number is", largest)

8) WAP to find average of N numbers using while loop.


➢ num = int(input('How many numbers: '))
➢ total = 0
➢ for n in range(num):
➢ numbers = float(input('Enter the number : '))
➢ total += numbers

3
EC 1 21EC014

➢ avg = total/num
➢ print('Average of ', num, ' numbers is :', avg)

9) WAP to find given number is PRIME or NOT using for loop.


➢ num = int(input("Enter a number: "))
➢ flag = False
➢ if num == 1:
➢ print(num, "is not a prime number")
➢ elif num > 1:
➢ for i in range(2, num):
➢ if (num % i) == 0:
➢ flag = True
➢ break
➢ if flag:
➢ print(num, "is not a prime number")
➢ else:
➢ print(num, "is a prime number")

10) WAP to print Multiplication Table.


➢ num = int(input("Display multiplication table of? "))
➢ for i in range(1, 11):
➢ print(num, 'x', i, '=', num*i)\

11) WAP to find factorial of a given number.


➢ num = int(input("Enter a number: "))
factorial = 1

if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("Factorial of", num, "is", factorial)
4
EC 1 21EC014

12) WAP that demonstrates the use of break and continue statements
to alter the flow of the loop.
➢ # Example of break statement
➢ for i in range(1, 11):
➢ if i == 5:
➢ break # Exit the loop when i equals 5
➢ print(i)
➢ # Example of continue statement
➢ for i in range(1, 11):
➢ if i == 5:
➢ continue # Skip printing 5 and continue with the next iteration
➢ print( i )

13) WAP to prompt the user for hours and rate per hour to compute
gross
pay. Company will give the employee 1.5 times the Hourly rate for hours
worked above 40 hours.
➢ hours = float(input(“quot;Enter the number of hours worked: “quot;))
rate = float(input(“quot;Enter the hourly rate: “quot;))
if hours “gt; 40:
overtime_hours = hours - 40
overtime_rate = rate * 1.5
gross_pay = (40 * rate) + (overtime_hours * overtime_rate)
else:
gross_pay = hours * rate
print(“quot;Gross pay: $”quot;, gross_pay)

14) Given the family relationship below output all persons who fit in
theinput characteristic. These characteristics are SIBLING, PARENT,
CHILD,

5
EC 1 21EC014

GRANDPARENT and GRANDCHILD. Family 1-&gt; Ann and Marty have


children Bill, Cathy and Frank. Cathy and Don have children Madd and
Sally. Frank and Jill have child Sarah. Bill and Alice have no children.

Family 2-&gt; Debbie and Phil have children Jill and Betty. Jill and Frank
have child Sarah. Betty and Paul have children Marry, Jane and Bart.
➢ Family 1
family1 = {
“quot;Ann”quot;: [“quot;Bill”quot;, “quot;Cathy”quot;, “quot;Frank”quot;],
“quot;Marty”quot;: [“quot;Bill”quot;, “quot;Cathy”quot;, “quot;Frank”quot;],
“quot;Cathy”quot;: [“quot;Madd”quot;, “quot;Sally”quot;],
“quot;Don”quot;: [“quot;Madd”quot;, “quot;Sally”quot;],
“quot;Frank”quot;: [“quot;Sarah”quot;],
“quot;Jill”quot;: [“quot;Sarah”quot;]
}
# Family 2
family2 = {
“quot;Debbie”quot;: [“quot;Jill”quot;, “quot;Betty”quot;],
“quot;Phil”quot;: [“quot;Jill”quot;, “quot;Betty”quot;],
“quot;Jill”quot;: [“quot;Sarah”quot;],
“quot;Frank”quot;: [“quot;Sarah”quot;],
“quot;Betty”quot;: [“quot;Marry”quot;, “quot;Jane”quot;, “quot;Bart”quot;],
“quot;Paul”quot;: [“quot;Marry”quot;, “quot;Jane”quot;, “quot;Bart”quot;]
}
# Function to find all siblings
def find_siblings(person, family):

6
EC 1 21EC014

siblings = []
for parent, children in family.items():
if person in children and len(children) “gt; 1:
siblings += [sibling for sibling in children if sibling != person]
return siblings

# Function to find all parents


def find_parents(person, family):
parents = []
for parent, children in family.items():
if person in children:
parents.append(parent)
return parents

# Function to find all children


def find_children(person, family):
children = []
if person in family:
children = family[person]
return children

# Function to find all grandparents


def find_grandparents(person, family):
grandparents = []
for parent in find_parents(person, family):
grandparents += find_parents(parent, family)

7
EC 1 21EC014

return grandparents

# Function to find all grandchildren


def find_grandchildren(person, family):
grandchildren = []
for child in find_children(person, family):
grandchildren += find_children(child, family)
return grandchildren

# Test the functions


person = “quot;Sarah”quot;
print(“quot;Siblings of”quot;, person, “quot;:”quot;, find_siblings(person,
family1) +
find_siblings(person, family2))
print(“quot;Parents of”quot;, person, “quot;:”quot;, find_parents(person,
family1) +
find_parents(person, family2))
print(“quot;Children of”quot;, person, “quot;:”quot;, find_children(person,
family1) +
find_children(person, family2))
print(“quot;Grandparents of”quot;, person, “quot;:”quot;,
find_grandparents(person, family1)
+ find_grandparents(person, family2))
print(“quot;Grandchildren of”quot;, person, “quot;:”quot;,
find_grandchildren(person,
family1) + find_grandchildren(person, family2))

8
EC 1 21EC014

15) WAP which will print a string as it is except # and done is entered.
input_string = &quot;&quot;
while True:

➢ user_input = input(&quot;Enter a string: &quot;)


if user_input == &quot;done&quot;:
break
if &quot;#&quot; in user_input:
continue
input_string += user_input + &quot; &quot;
print(&quot;Input string:&quot;, input_string)

16) WAP to extract charusat.ac.in from python.team@charusat.ac.in


using string functions.
➢ email = &quot;python.team@charusat.ac.in&quot;
# Split the email address at &#39;@&#39;
username, domain = email.split(&#39;@&#39;)
# Extract the domain name
domain_name = domain.split(&#39;.&#39;)[0]
tld = domain.split(&#39;.&#39;)[1]
# Extract the required string
required_string = domain_name + &quot;.&quot; + tld
print(&quot;Required string:&quot;, required_string)

17) Write a program to concatenate the two lists.


➢ list1 = [1, 2, 3]
list2 = [4, 5, 6]

9
EC 1 21EC014

# Using the &#39;+&#39; operator to concatenate two lists


concatenated_list = list1 + list2
print(&quot;Concatenated List:&quot;, concatenated_list)

18) WAP to find the largest and smallest value in a list or sequence.
➢ my_list = [10, 20, 30, 40, 50]
# Using the min() and max() functions to find the smallest and largest
value
smallest_value = min(my_list)
largest_value = max(my_list)
print(&quot;Smallest Value:&quot;, smallest_value)
print(&quot;Largest Value:&quot;, largest_value)

19) WAP to demonstrate tuple operation.


➢ # Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
# Accessing tuple elements
print(&quot;Tuple Elements:&quot;)
for element in my_tuple:
print(element)
# Slicing tuples
print(&quot;\nSlicing Tuple:&quot;)
print(&quot;First three elements:&quot;, my_tuple[:3])
print(&quot;Last two elements:&quot;, my_tuple[-2:])
# Concatenating tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

10
EC 1 21EC014

concatenated_tuple = tuple1 + tuple2


print(&quot;\nConcatenated Tuple:&quot;, concatenated_tuple)
# Counting elements in a tuple
count = my_tuple.count(3)
print(&quot;\nCount of 3 in Tuple:&quot;, count)
# Finding index of an element in a tuple
index = my_tuple.index(4)
print(&quot;\nIndex of 4 in Tuple:&quot;, index)

20) WAP to count the occurrences of each word in the following


sentence
using dict(). the clown ran after the car and the car ran into the tent and
the tent fell down on the clown and the car
➢ # Input sentence
sentence = &quot;the clown ran after the car and the car ran into the tent and
the tent fell down on the clown and the car&quot;
# Splitting the sentence into words
words = sentence.split()
# Counting the occurrences of each word using a dictionary
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# Displaying the count of each word
print(&quot;Word count:&quot;, word_count)
11
EC 1 21EC014

21) WAP to demonstrate set operation.


➢ # Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Printing sets
print(&quot;Set 1:&quot;, set1)
print(&quot;Set 2:&quot;, set2)
# Union of sets
union_set = set1.union(set2)
print(&quot;\nUnion of Sets:&quot;, union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print(&quot;\nIntersection of Sets:&quot;, intersection_set)
# Difference of sets
difference_set = set1.difference(set2)
print(&quot;\nDifference of Sets (set1 - set2):&quot;, difference_set)
# Symmetric difference of sets
symmetric_difference_set = set1.symmetric_difference(set2)
print(&quot;\nSymmetric Difference of Sets:&quot;, symmetric_difference_set)

22) WAP to create a Function to swap values of a pair of integers.


def swap(a, b):
temp = a
a=b

b = temp
return (a, b)
12
EC 1 21EC014

# Example usage
x=5
y = 10
print(&quot;Before Swap: x =&quot;, x, &quot;and y =&quot;, y)
x, y = swap(x, y)
print(&quot;After Swap: x =&quot;, x, &quot;and y =&quot;, y)

23) WAP to print Fibonacci series of n numbers, where n is given by


the
programmer.
➢ # Input number of terms to generate
n = int(input(&quot;Enter the number of terms to generate in the Fibonacci
series: &quot;))
# Initializing the first two terms
a, b = 0, 1
# Displaying the Fibonacci series
print(&quot;Fibonacci series:&quot;)
for i in range(n):
print(a, end=&#39; &#39;)
c=a+b
a, b = b, c

24) WAP read a set of numbers from keyboard &amp; to find the sum
of all
elements of the given array using a function.
➢ def find_sum(numbers):
sum = 0

13
EC 1 21EC014

for num in numbers:


sum += num
return sum
# Input the list of numbers
numbers = list(map(int, input(&quot;Enter the set of numbers separated by
space: &quot;).split()))
# Display the list of numbers
print(&quot;Input Numbers:&quot;, numbers)
# Calculate and display the sum of the list of numbers
sum = find_sum(numbers)
print(&quot;Sum of Numbers:&quot;, sum)

25) WAP to demonstrate usage of positional, keyword and default


parameters.
➢ # Example function with positional, keyword, and default parameters
def my_function(a, b, c=10, d=20):
print(&quot;a =&quot;, a)

print(&quot;b =&quot;, b)
print(&quot;c =&quot;, c)
print(&quot;d =&quot;, d)
# Calling the function with positional arguments
my_function(1, 2)
# Calling the function with keyword arguments
my_function(a=1, b=2, c=3, d=4)
# Calling the function with mixed arguments

14
EC 1 21EC014

my_function(1, b=2, d=4)


# Calling the function with default values
my_function(1, 2, d=4)

26) WAP to implement take a break story. This program will notify
users to
take a break by playing their favorite video on YouTube after fixed
amount of time.
➢ import time
import webbrowser
# Function to play the favorite video on YouTube
def play_video():
url = &quot;https://www.youtube.com/watch?v=dQw4w9WgXcQ&quot;
webbrowser.open_new_tab(url)
# Main function to implement the &quot;Take a Break&quot; story
def take_a_break(total_breaks, break_time):
count = 0
while count &lt; total_breaks:
# Wait for the break time
time.sleep(break_time)
# Play the favorite video on YouTube
play_video()
count += 1
# Set the total number of breaks and the break time in seconds
total_breaks = 3
break_time = 60 * 60 # 1 hour
# Call the take_a_break function
15
EC 1 21EC014

take_a_break(total_breaks, break_time)

27) WAP to help weatherman who will predict weather for a particular
week
and for next seven days. Implement this scenario by creating two
modules namely daily.py and weekly.py for predicting daily and weekly
weather respectively.
➢ import random

# List of possible weather conditions


conditions = [&quot;sunny&quot;, &quot;cloudy&quot;, &quot;rainy&quot;,
&quot;stormy&quot;]
# Function to predict the weather for a single day
def predict_weather():
return random.choice(conditions)
import daily
# Function to predict the weather for a week
def predict_weekly_weather():
week_weather = []
for i in range(7):
day_weather = daily.predict_weather()
week_weather.append(day_weather)
return week_weather

28) Rewrite Spam confidence program (5.2) using try and except.
➢ fname = input(&quot;Enter file name: &quot;)
try:

16
EC 1 21EC014

fhand = open(fname)
except:
print(&quot;File cannot be opened:&quot;, fname)
quit()
count = 0
total = 0
for line in fhand:
if line.startswith(&quot;X-DSPAM-Confidence:&quot;):
count += 1
try:
confidence = float(line[line.find(&quot;:&quot;)+1:].strip())
total += confidence
except:
print(&quot;Error: could not convert confidence value to float&quot;)
if count &gt; 0:
average = total / count
print(&quot;Average spam confidence:&quot;, average)
else:
print(&quot;No lines starting with &#39;X-DSPAM-Confidence:&#39; were
found in
the file.&quot;)

29) WAP to read through the mail box data and when you find line
that starts
with “From”, you will split the line into words using the split function.
We are interested in who sent the message, which is the second word
on the From line.

17
EC 1 21EC014

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008


You will parse the From line using regular expression and print out the
second word for each
From line, then you will also count the number of From (not From:) line

and print out a count at the end.


Enter a file name: mbox-short.txt
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
➢ import re
filename = input(&quot;Enter a file name: &quot;)
count = 0
with open(filename, &#39;r&#39;) as file:
for line in file:
if line.startswith(&quot;From &quot;):
count += 1
words = line.split()
email = re.findall(&#39;\S+@\S+&#39;, words[1])
print(email[0])
print(&quot;There were&quot;, count, &quot;lines in the file with From as the
first word.&quot;)

30) WAP to demonstrate usage of compile() method of RE module in


Python.
➢ import re
18
EC 1 21EC014

# create a regular expression pattern using compile method


pattern = re.compile(r&#39;\d+&#39;) # matches one or more digits
# use the pattern to find all matches in a string
text = &#39;There are 12 cats and 3 dogs in the park.&#39;
matches = pattern.findall(text)
# print the matches
print(matches)

31) WAP to draw a flower using turtle to understand the concepts of


OOP.
➢ import turtle
# create a turtle object
t = turtle.Turtle()
# set the pen color and fill color
t.color(&quot;red&quot;, &quot;yellow&quot;)
# start filling the color
t.begin_fill()
# draw the flower shape
for _ in range(18):
t.forward(100)
t.left(100)

# end filling the color


t.end_fill()
# hide the turtle object
t.hideturtle()
# exit on click

19
EC 1 21EC014

turtle.exitonclick()

32) Define a class name Circle which can be constructed using a


parameter
radius. The circle class has a method which can compute the area using
area method.
➢ import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)

33) Create class namely Employee. And show the Employee name,
salary
and count using OOP concept.
➢ class Employee:
# class variable to keep track of the number of employees
count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.count += 1
def displayEmployee(self):
print(&quot;Name : &quot;, self.name, &quot;, Salary: &quot;, self.salary)
def displayCount(self):
print(&quot;Total Employees %d&quot; % Employee.count)

20
EC 1 21EC014

34) Create two classes namely Employee and Qualification. Using


multiple
inheritance derive two classes Scientist and Manager. Take suitable
attributes &amp; operations. WAP to implement this class hierarchy.
➢ class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary

def display(self):
print(&quot;Name:&quot;, self.name)
print(&quot;Salary:&quot;, self.salary)
class Qualification:
def __init__(self, qualification):
self.qualification = qualification
def display(self):
print(&quot;Qualification:&quot;, self.qualification)
class Scientist(Employee, Qualification):
def __init__(self, name, salary, qualification, field_of_study):
Employee.__init__(self, name, salary)
Qualification.__init__(self, qualification)
self.field_of_study = field_of_study
def display(self):
Employee.display(self)
Qualification.display(self)
print(&quot;Field of Study:&quot;, self.field_of_study)
21
EC 1 21EC014

class Manager(Employee, Qualification):


def __init__(self, name, salary, qualification, team_size):
Employee.__init__(self, name, salary)
Qualification.__init__(self, qualification)
self.team_size = team_size
def display(self):
Employee.display(self)
Qualification.display(self)
print(&quot;Team Size:&quot;, self.team_size)
# Example usage
scientist1 = Scientist(&quot;John Doe&quot;, 50000, &quot;PhD&quot;,
&quot;Biology&quot;)
scientist1.display()
manager1 = Manager(&quot;Jane Smith&quot;, 75000, &quot;MBA&quot;, 10)
manager1.display()

22

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