0% found this document useful (0 votes)
7 views

Python Record (30 Files Merged)

Uploaded by

nithishv098765
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)
7 views

Python Record (30 Files Merged)

Uploaded by

nithishv098765
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/ 101

Knowledge Institute of Technology

Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 1_MCQ

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. Which of the following is the use of id() function in Python?

Answer
Id() returns the identity of the object
Status : Correct Marks : 1/1

2. What is the return type of function id ?

Answer
int
Status : Correct Marks : 1/1
3. What is the id in Python?

Answer
Object's memory address
Status : Correct Marks : 1/1

4. Which of the following is the correct syntax for the id() function?

Answer
id(object)
Status : Correct Marks : 1/1

5. How is the identity of an object defined in Python?

Answer
Unique memory address
Status : Correct Marks : 1/1

6. If only one parameter is specified in the type() function, what does it


return?

Answer
Type of the object
Status : Correct Marks : 1/1

7. Which function is used to obtain the type of an object in Python?

Answer
type()
Status : Correct Marks : 1/1
8. What is the purpose of the "bases" parameter in the type() function?

Answer
Specifies the base classes
Status : Correct Marks : 1/1

9. What is the output for the following code?

a = ('apple', 'banana', 'cherry')


x = type(a)
print(x)
Answer
<class 'tuple'>
Status : Correct Marks : 1/1

10. What is the output for the following code?

b = "Hello World"
c = 33
y = type(b)
z = type(c)
print(y)
print(z)
Answer
<class 'str'><class 'int'>
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 1_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : COD

1. Problem Statement

Reni is a student who is learning about data types in programming. She


wants to create a program that takes user input for a float, a string, and an
integer using type() function.

After taking the input, the program should determine and display the types
of the provided values.

Answer
a=float(input())
b=(input())
c=int(input())
print(f"Type of 'a':{type(a).__name__}")
print(f"Type of 'b':{type(b).__name__}")
print(f"Type of 'c':{type(c).__name__}")
Status : Correct Marks : 10/10

2. Problem Statement

Teena is managing expenses for her household and wants to create a


simple program to calculate the total cost of a specific consumption item.
She knows the unit price of the item and the quantity consumed.

Teena needs a program that takes user input for the unit price and
consumption, calculates the total cost, and then displays both the total
cost and its data type using type() function.

Answer
unit_price = int(input())
quantity_consumed = int(input())

total_cost = unit_price * quantity_consumed

print(f"The total cost is: {total_cost}")


print(f"{type(total_cost)}")

Status : Correct Marks : 10/10

3. Problem statement:

Jai is an aspiring programmer who wants to create a temperature


converter program.

He wishes to develop a program that takes input in Celsius as an integer


and then converts the float and converts it to Fahrenheit.

Answer
def convert_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit

n=int(input())
result = convert_to_fahrenheit(n)
print(result)
print(type(result))

Status : Correct Marks : 10/10

4. Problem Statement

Varsha is a student studying complex numbers in her mathematics class.

She wants to write a Python program that takes input for the real and
imaginary parts of a complex number from the user, creates a complex
number using the input, and then prints out the complex number along
with its type.

Answer
real_part = int(input())
imaginary_part = int(input())
complex_number = complex(real_part,imaginary_part)
print(complex_number)
print(type(complex_number))

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 1_Automata Fix

Attempt : 3
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Trisha is an aspiring programmer who is learning about basic geometric


calculations. She wants to create a program that calculates the area of a
circle based on user input. Additionally, the program should round the
calculated area to two decimal places and display both the rounded area
and its data type using type() function.

Formula:
Circle = 3.14 * radius * radius

Answer
radius = float(input())
# You are using Python
area = 3.14 * radius * radius
rounded_area = round(area, 2)
print(rounded_area)
print(type(rounded_area))

Status : Correct Marks : 10/10

2. Problem Statement

John is an engineer working on a project that involves calculating the


square of the hypotenuse in a right-angled triangle.

He needs a program that takes user input for the lengths of the two shorter
sides of the triangle, converts them to floating-point numbers, calculates
the square of the hypotenuse using the Pythagorean theorem (C2 = A2 +
B2) and then displays the result along with its data type. type() function.

Answer
a_input = input()
b_input = input()
# You are using Python
c = int(a_input)
d = int(b_input)
result = float(c**2 + d**2)
print(result)
print(type(result))

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 2_MCQ

Attempt : 2
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What does the range() function in Python return?

Answer
A sequence of numbers
Status : Correct Marks : 1/1

2. What is the default starting value for the range() function if no start
parameter is provided?

Answer
0
Status : Correct Marks : 1/1
3. What is the output of the following code?

print(range(6))
Answer
range(0, 6)
Status : Correct Marks : 1/1

4. What is the output of the following code?

print(*range(2, 11, 2))


Answer
2 4 6 8 10
Status : Correct Marks : 1/1

5. What is the output of the following code?

total = sum(range(1, 10))


print(total)
Answer
45
Status : Correct Marks : 1/1

6. What is the output of the following code?

num_to_check = 7
is_in_range = num_to_check in range(1, 11)
print(is_in_range)
Answer
True
Status : Correct Marks : 1/1
7. Which of the following statements creates a range object that
generates numbers from 0 to 9 (inclusive)?

Answer
range(0, 10)
Status : Correct Marks : 1/1

8. What is the output of the following code?

c = len(range(5, 16))
print(c)
Answer
11
Status : Correct Marks : 1/1

9. Which of the following is the correct syntax of the range() function in


Python?

Answer
range(start, end, step)
Status : Correct Marks : 1/1

10. What is the output of the following code?

index = range(3, 13).index(8)


print(index)
Answer
5
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 2_COD

Attempt : 1
Total Mark : 30
Marks Obtained : 30

Section 1 : COD

1. Problem Statement

Joe is on a mission to boost his savings, and he has come up with a


challenge for himself. He wants to calculate the sum of integers within a
given range using the range() function.

Help him by creating a program to achieve this.

Answer
start = int(input())
end = int(input())
sum_of_integers = sum(range(start,end+1))
print(f"sum of integers from {start} to {end}: {sum_of_integers}")

Status : Correct Marks : 10/10


2. Problem Statement

Janu needs a program that calculates the average of numbers within a


given range. She wants to create a program that inputs the range of
numbers (a lower bound and b upper bound) and gets the average of all
integers within that range using the sum() function and range() function.

Answer
a = int(input())
b = int(input())
total_sum = sum(range(a,b+1))
average = total_sum / (b - a+1)
print(f"Average of numbers from {a} to {b}: {average: .1f}")

Status : Correct Marks : 10/10

3. Problem Statement

John wants to calculate the sum of a range of numbers starting from 2 to


a given integer n. He seeks your help to accomplish this task. Write a
program to assist John in finding the sum of the range.

For example, The sum of the numbers from 2 to 5 = 2 + 3 + 4 + 5 = 14

Answer
# You are using Python
n = int(input())
sum = 0
for i in range(2,n+1):
sum += i
print(sum)

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 2_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Hussain is working on a program to generate multiples of 5 up to a given


limit. He needs your help to create a program that takes a limit as input
and generates and prints all multiples of 5 up to that limit.

Answer
# You are using Python
limit = int(input())
for i in range(5,limit + 1,5):
print(i,end="")

Status : Correct Marks : 10/10

2. Problem Statement
Bharath is working on a project where he needs to check if a specific
number exists within a given range or not. He has tasked you with creating
a program to perform this check using the range() function.

Help Bharath by developing the required program.

Answer
x = int(input())
y = int(input())
B = int(input())
if x <= B <= y:
print(f"{B} exists in the range from {x} to {y}")
else:
print(f"{B} does not exist in the range from {x} to {y}")

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 3_MCQ

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What will be the output for the following code?

i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Answer
i is 20
Status : Correct Marks : 1/1
2. What does an if statement do?

Answer
Makes a decision
Status : Correct Marks : 1/1

3. What will be the output of the following code?

number=5
if not number>0:
print("Negative")
else:
print("Positive")
Answer
Positive
Status : Correct Marks : 1/1

4. What is the output of the following code?

x = False
y = True
if x and y:
print('Both x and y are True')
else:
print('x is False or y is False or both x and y are False')
Answer
x is False or y is False or both x and y are False
Status : Correct Marks : 1/1

5. What is the output of the following?

age = 38
if (age >= 11):
print ("You are eligible to see the Football match.")
if (age <= 20 or age >= 60):
print("Ticket price is $12")
else:
print("Ticket price is $20")
else:
print ("You're not eligible to buy a ticket.")
Answer
You are eligible to see the Football match. Ticket price is $20
Status : Correct Marks : 1/1

6. Fill in the code to find the greatest number among these numbers.

Output: 45

a,b,c = 12,23,45
if ____
print(a)
elif b>c:
print(b)
else:
print(c)
Answer
a&gt;b and a &gt;c :
Status : Correct Marks : 1/1

7. Which of the following is not a conditional statement in python?

Answer
switch
Status : Correct Marks : 1/1

8. Fill in the code to check whether the number is odd or not.


Output: odd

n=7
if ________
print("odd")
else:
print("even")
Answer
n%2!=0:
Status : Correct Marks : 1/1

9. What is the output of the following code?

a = 20
if a >= 22:
print("if")
elif a >= 21:
print("elif")
Answer
Nothing will be printed
Status : Correct Marks : 1/1

10. What is the output of the following?

grade=90
if grade >= 90:
print("A grade")
elif grade >=80:
print("B grade")
elif grade >=70:
print("C grade")
elif grade >= 65:
print("D grade")
else:
print("Failing grade")
Answer
A grade
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 3_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : COD

1. Problem Statement

Banu is an astrologer who specializes in identifying people's zodiac signs


based on their birthdates. She wants to develop a simple tool that can
assist her in determining the zodiac sign of individuals. She's seeking your
help to write a program that automates this process.

Zodiac Sign Determination:

Aries: March 21–April 19Taurus: April 20–May 20Gemini: May 21–June


20Cancer: June 21–July 22Leo: July 23–August 22Other: For dates
outside of the above ranges
Answer
def determine_zodiac_sign(day, month):
if month == "March":
return "Aries" if day >= 21 else "Other"
elif month == "April":
return "Aries" if day <= 19 else "Taurus"
elif month == "May":
return "Taurus" if day <= 20 else "Gemini"
elif month == "June":
return "Gemini" if day <= 20 else "Cancer"
elif month == "July":
return "Cancer" if day <= 22 else "Leo"
elif month == "August":
return "Leo" if day <= 22 else "Other"
else:
return "Other"

# Taking input from the user


day = int(input())
month = input()

# Determining the zodiac sign


zodiac_sign = determine_zodiac_sign(day, month)

# Printing the output


print(f"Your zodiac sign is {zodiac_sign}")

Status : Correct Marks : 10/10

2. Problem Statement

Fazil needs a triangle classification program. Given the lengths of the sides
of a triangle (side1, side2, and side3), the program determines whether the
triangle is classified as Equilateral, Isosceles, or Scalene based on the
following conditions:

If all sides are equal, classify the triangle as Equilateral.If exactly two sides
are equal, classify the triangle as Isosceles.If all sides are different,
classify the triangle as Scalene.
Answer
def classify_triangle(side1, side2, side3):
if side1 == side2 == side3:
return "Equilateral"
elif side1 == side2 or side1 == side3 or side2 == side3:
return "Isosceles"
else:
return "Scalene"

# Taking input from the user


side1 = float(input())
side2 = float(input())
side3 = float(input())

# Classifying the triangle


triangle_type = classify_triangle(side1, side2, side3)

# Printing the output


print(f"The triangle is classified as {triangle_type}")

Status : Correct Marks : 10/10

3. Problem Statement

Rathi is a manager at a company, and she's responsible for calculating the


bonuses, tax amounts, and net salaries of the employees. She wants to
automate this process through a simple program.

She asks for your help in creating a program that can calculate the bonus,
tax amount, and net salary based on years of service and other parameters.

Formula:
net_bonus = (bonus_percentage / 100) * salary
tax_amount = (tax_percentage / 100) * (salary + net_bonus)
net_salary = salary + net_bonus - tax_amount

Answer
def calculate_salary(salary, years_of_service, bonus_percentage,
tax_percentage):
if years_of_service > 5:
net_bonus = (bonus_percentage / 100) * salary
print("You have earned a bonus of {:.1f} units.".format(net_bonus))
else:
print("Sorry, you are not eligible for a bonus.")
net_bonus = 0

tax_amount = (tax_percentage / 100) * (salary + net_bonus)


net_salary = salary + net_bonus - tax_amount

print("Tax Amount: {:.1f} units".format(tax_amount))


print("Net Salary: {:.1f} units".format(net_salary))

# Input parameters
salary = float(input())
years_of_service = int(input())
bonus_percentage = float(input())
tax_percentage = float(input())

# Calculate and output


calculate_salary(salary, years_of_service, bonus_percentage, tax_percentage)

Status : Correct Marks : 10/10

4. Problem Statement

Nandha is learning about number categorization in his math class. He's


specifically interested in even and odd numbers and how they're classified
as "Weird" or "Not Weird" based on certain conditions. He needs a program
that can help him determine the category of a given integer. Can you assist
Nandha by creating a program that performs this categorization?

Given an integer, perform the following conditional actions:


If n is odd, print Weird.If n is even and in the inclusive range of 2 to 5, print
Not Weird.If n is even and in the inclusive range of 6 to 20, print Weird.If n
is even and greater than 20, print Not Weird.
Answer
n = int(input())
if n % 2 == 1 or (n % 2 == 0 and 6 <= n <= 20):
print("Weird")
elif n % 2 == 0 and (2 <= n <= 5 or n > 20):
print("Not Weird")

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 3_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Kamali recently received her electricity bill and wants to calculate the
amount she needs to pay based on her usage. The electricity company
charges different rates based on the number of units consumed.

For the first 100 units, there is no charge. For units consumed beyond 100
and up to 200, there is a charge of Rs. 5 per unit. For units consumed
beyond 200, there is a charge of Rs. 10 per unit.

Write a program to help Kamali calculate the amount she needs to pay for
her electricity bill based on the units consumed.

Answer
amount = 0
units = int(input())
# You are using Python

if units <= 100:


amount = 0
elif units <= 200:
amount = 5 * (units - 100)
else:
amount = 5 * 100 + 10 * (units - 200)

print("Rs. " + str(amount))

Status : Correct Marks : 10/10

2. Problem Statement

John's odd-even calculator program takes two integer inputs from the user,
calculates their sum, and determines whether the sum is odd or even.

Answer
n1 = int(input())
n2 = int(input())
sum = n1 + n2

# Determining if the sum is odd or even and printing the output


if sum % 2 == 0:
print("even")
else:
print("odd")
#FOOTER

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 4_MCQ

Attempt : 2
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What will be the output of the following program?

x = 'abcd'
for i in x:
print(i.upper())
Answer
ABCD
Status : Correct Marks : 1/1

2. What will be the output of the following code?

x = 123
for i in x:
print(i)
Answer
Error
Status : Correct Marks : 1/1

3. What will be the output of the following program?

x = 'abcd'
for i in range(len(x)):
print(i,end=" ")
Answer
0123
Status : Correct Marks : 1/1

4. What will be the output of the following Python code?

i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
Answer
24
Status : Correct Marks : 1/1

5. What will be the output for the following code?

x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")
Answer
aaaaaa
Status : Correct Marks : 1/1

6. What will be the output of the following program?

True = False
while True:
print(True)
break
Answer
Syntax Error
Status : Correct Marks : 1/1

7. What will be the output of the following program?

i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
Answer
012
Status : Correct Marks : 1/1

8. What will be the output of the following code?

s1={3, 4}
s2={1, 2}
s3=set()
i=0
j=0
for i in s1:
for j in s2:
s3.add((i,j))
i+=1
j+=1
print(s3)
Answer
{(3, 1), (4, 1), (4, 2), (5, 2)}
Status : Correct Marks : 1/1

9. What will be the output of the following Python code snippet?

x = 'abcd'
for i in range(len(x)):
x = 'a'
print(x)
Answer
abcdabcdabcdabcd
Status : Correct Marks : 1/1

10. Which of the following is a valid for loop in Python?

Answer
for i in range(0,5):
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 4_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : COD

1. Problem Statement

Raj wants to create a program that takes an integer input n and prints all
integers from 0 to n, inclusive, separated by space.

Answer
def print_numbers_up_to_n(n):
for i in range(n + 1):
print(i, end=' ')

# Input
n = int(input())

# Check if the input is within the valid range


if 0 <= n <= 1000:
print_numbers_up_to_n(n)
print() # Print a newline at the end
else:
print("Invalid Input")

Status : Correct Marks : 10/10

2. Problem Statement

Maya, a student in an arts and crafts class, wants to create a pattern using
stars (*) in a specific format. She plans to use a program to help her
construct the pattern.

Write a program that takes an integer as input and constructs the following
pattern using nested for loops.

Input: 5

Output:

*
**
***
****
*****
****
***
**
*

Answer
def print_pattern(rows):
# Upper half of the pattern
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=" ")
print()

# Lower half of the pattern


for i in range(rows - 1, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()

# Input
rows = int(input())

# Check if the input is within the valid range


if 1 <= rows <= 20:
print_pattern(rows)
else:
print("Invalid Input")

Status : Correct Marks : 10/10

3. Problem Statement

Write a program to find the factorial digit sum of a given number.

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the


digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Write a program to accept a number and print the factorial and the sum of
the digits in a factorial of the given number.

Answer
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

def sum_of_digits(number):
return sum(int(digit) for digit in str(number))
# Input
n = int(input())

# Check if the input is within the valid range


if 2 <= n <= 10:
fact = factorial(n)
print(fact)
print(sum_of_digits(fact))
else:
print("Invalid Input")

Status : Correct Marks : 10/10

4. Problem Statement

Harsh is interested in determining whether two numbers are amicable or


not. Amicable numbers are two distinct integers where the sum of the
proper divisors of each number equals the other number.

You need to develop a program that takes two integers as input and
determines whether they are amicable numbers or not.

Example
Input:
First number: 220
Second number:284
Output: Amicable numbers
Explanation:
The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110.
Therefore, the sum of its divisors is 284(second number).
The proper divisors of 284 are 1, 2, 4, 71, and 142.
So, the sum of the divisors is 220(First number).
Thus 220 and 284 are amicable numbers.
Answer
def sum_of_divisors(n):
divisors_sum = 1 # Start with 1 as 1 is always a divisor
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
divisors_sum += i
if n // i != i: # Avoid counting the same divisor twice
divisors_sum += n // i
return divisors_sum

# Input
num1 = int(input())
num2 = int(input())

# Calculate the sum of divisors for both numbers


sum1 = sum_of_divisors(num1)
sum2 = sum_of_divisors(num2)

# Check if the numbers are amicable


if sum1 == num2 and sum2 == num1:
print("Amicable numbers")
else:
print("Not Amicable numbers")

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 4_Automata Fix

Attempt : 2
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Jansi is learning about factors of a given number. She wants to write a


program that takes an integer as input and prints all its factors, including
itself. Help her in achieving this.

Write a program that takes an integer as input and prints all the factors of
the given number.

Answer
num=int(input())
# You are using Python
factors=[]
for i in range (1,num+1):
if num %i==0:
factors.append(i)
factors.remove(num)
print(*factors,end='')
print(num, end=' ')

Status : Correct Marks : 10/10

2. Problem Statement

Raj is working on a program to process a series of characters. He needs


your help to design a script that takes two inputs: a string of characters n
and a single character n1.

The program should iterate through the characters in n until it encounters


the character n1. Once it finds n1, it should stop printing the characters
and terminate.

Answer
n=input()
n1=input()
# You are using Python
for char in n:
if char == n1:
break
print(char)
##Footer

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 5_MCQ

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What is a recursive function?

Answer
A function that calls itself
Status : Correct Marks : 1/1

2. What will be the output of the following code?

def fun(n):
if n == 0:
return 1
else:
return fun(n - 1) + n
print(fun(3))
Answer
7
Status : Correct Marks : 1/1

3. What will be the output of the following code?

def rec(x, y):


if y == 0:
return 1
else:
return x * rec(x, y - 1)
print(rec(2, 3))
Answer
8
Status : Correct Marks : 1/1

4. What will be the output of the following code?

def fact(n):
return 1 if n == 0 else n * fact(n - 1)
print(fact(4))
Answer
24
Status : Correct Marks : 1/1

5. What will be the output of the following code?

def sum(num):
return 0 if num == 0 else num % 10 + sum(num // 10)
print(sum(456))
Answer
15
Status : Correct Marks : 1/1

6. What will be the output of the following code?

def calculate_sum(n):
result = 0
for i in range(1, n + 1):
result += i
return result

print(calculate_sum(6))
Answer
21
Status : Correct Marks : 1/1

7. What will be the output of the following code?

def power(b, e):


result = 1
for _ in range(e):
result *= b
return result

print(power(3, 2))
Answer
9
Status : Correct Marks : 1/1

8. What will be the output of the following code?

def disc(price, percent):


dp = price - (price * percent / 100)
return dp if dp >= 0 else 0
print(disc(50, 20))
Answer
40.0
Status : Correct Marks : 1/1

9. In a non-recursive function, how is the termination condition typically


achieved?

Answer
Using the return statement
Status : Correct Marks : 1/1

10. What is the primary advantage of non-recursive functions over


recursive functions?

Answer
All of the mentioned options
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 5_COD

Attempt : 2
Total Mark : 40
Marks Obtained : 40

Section 1 : COD

1. Problem Statement

Rithisa requires a program to determine whether a given string is a


palindrome. The program prompts for a string input and checks if it reads
the same backward as forward.

It utilizes a recursive function isPalindrome to conduct this check, taking


the string, left position, and right position as arguments. If the string is a
palindrome, the program returns True; otherwise, it returns False.

Function Specifications: def isPalindrome(string, left_pos, right_pos)

Answer
# You are using Python
def isPalindrome(string, left_pos, right_pos):
if left_pos >= right_pos:

return True

if string[left_pos] != string[right_pos]:
return False

return isPalindrome(string, left_pos + 1, right_pos - 1)

def checkPalindrome(string):
return isPalindrome(string, 0, len(string) - 1)

n = input()
print(checkPalindrome(n))

Status : Correct Marks : 10/10

2. Problem Statement

Write a Python program that calculates the sum of the positive integers in
the series n+(n-2)+(n-4)+... until n-x ≤ 0 using a recursive function.

Answer
# You are using Python
def sum_series(n):

if n < 1:

return 0
else:
return n + sum_series(n - 2)
n=int(input())
print(sum_series(n))

Status : Correct Marks : 10/10

3. Problem Statement
Sophia, a mathematician, wants to implement a Python function to
determine whether a given number is perfect or not.

Write a Python function to check whether a number is perfect or not.

Example: The first perfect number is 6, because 1, 2, and 3 are its proper
positive divisors, and 1 + 2 + 3 = 6.

Answer
# You are using Python
def perfect_number(n):

sum = 0

for x in range(1, n):


if n % x == 0:
sum += x
return sum == n
n1=int(input())
print(perfect_number(n1))

Status : Correct Marks : 10/10

4. Problem Statement

Sophie is an architect working on designing a circular building. She needs


to calculate the circumference of the building's circular base to estimate
the amount of material required for fencing.

Help Sophie write a program to calculate the circumference of a circle with


the given radius r. Take the PI value as 3.1415 and display the
circumference by rounding off to three decimal places.

Formula: 2 * PI * r

Answer
# You are using Python
PI = 3.1415
def circumference(r):
return (2 * PI * r)

n = int(input())
print("Circumference: {:.3f}".format(circumference(n)))

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 5_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : COD

1. Problem Statement

Riya is intrigued by finding the maximum value among given numbers. She
wants to write a program that can take three integer inputs, a, b, and c, and
then determine the maximum value among them.

Can you write a program to help Riya find the maximum of three numbers?

Function prototype: def max_of_three(a,b,c)

Answer
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three(a, b, c):
# Use the max_of_two function to find the maximum of three numbers
return max_of_two(a, max_of_two(b, c))

# Read three integers from input


a = int(input())
b = int(input())
c = int(input())

print(max_of_three(a,b,c))

Status : Correct Marks : 10/10

2. Problem Statement

Ethan is working on a text analysis project where he needs to analyze the


distribution of uppercase and lowercase letters in a given string.

He plans to write a Python function that accepts a string as input and


calculates the number of uppercase and lowercase letters in it.

Function Specification: string_test(s)

Answer
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}

for char in s:
if char.isupper():
d["UPPER_CASE"] += 1
elif char.islower():
d["LOWER_CASE"] += 1

print(d["UPPER_CASE"])
print(d["LOWER_CASE"])
str=input()
string_test(str)

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 6_MCQ

Attempt : 2
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What is the output of the following Python code?

name = "John"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)
Answer
My name is John and I am 25 years old.
Status : Correct Marks : 1/1

2. What is the output of the following Python code?

word = "programming"
answer = word.index("gram")
print(answer)
Answer
3
Status : Correct Marks : 1/1

3. What is the output of the following Python code?

string1 = "Hello"
string2 = "World"
result = string1 + string2
print(result)
Answer
HelloWorld
Status : Correct Marks : 1/1

4. What is the output of the following Python code?

word = "Python"
res = word[::-1]
print(res)
Answer
nohtyP
Status : Correct Marks : 1/1

5. What is the output of the following Python code?

text = "Super hero"


x = text.index("e")
print(x)
Answer
3
Status : Correct Marks : 1/1

6. What is the output of the following Python code?

message = "Learn Programming"


a = message.index("e", 1, 10)
print(a)
Answer
1
Status : Correct Marks : 1/1

7. What is the output of the following Python code?

b = "debugger Compiler"
print(b[-5:-2])
Answer
pil
Status : Correct Marks : 1/1

8. What is the output of the following code?

example = "snow world"


print("%s" % example[4:7])
Answer
wo
Status : Correct Marks : 1/1

9. What will be the output of the given code?

s1="Hello"
s2="Welcome"
print(s1+s2)
Answer
HelloWelcome
Status : Correct Marks : 1/1

10. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('yy', 2))
Answer
1
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 6_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : Coding

1. Problem Statement

You have two strings str1 and str2, both of equal length. Write a Python
program to concatenate the two strings such that the first character of str1
is followed by the first character of str2, the second character of str1 is
followed by the second character of str2, and so on.

For example, if str1 is "abc" and str2 is "def", the output should be "adbecf".

Answer
str1 = input()
str2 = input()

concatenated_string = ''
for char1, char2 in zip(str1, str2):
concatenated_string += char1 + char2
print(concatenated_string)

Status : Correct Marks : 10/10

2. Problem Statement

You have a string containing a phone number in the format "(XXX) XXX-
XXXX". You need to extract the area code from the phone number and
create a new string that contains only the area code.

Write a Python program for the same.

Note
(XXX) - Area code
XXX-XXXX - Phone number

Answer
phone_number = input()

area_code = phone_number[1:4]

print("Area code:", area_code)

Status : Correct Marks : 10/10

3. Problem Statement

Write a program to check if a given string is perfect.

A perfect string contains alternating consonants and vowels. Each


occurrence of a consonant is exactly one whereas vowels can occur more
than once, continuously. The given string always starts with a consonant.

If a string is perfect print “True” otherwise print “False”

Answer
s=input().lower()

consflag=0

vowels='aeiou'
for ch in s:
if consflag==0 and ch not in vowels:
consflag=1
elif ch in vowels and consflag==1:
consflag=0
elif ch not in vowels and consflag==1:
print('False')
break
else:
print('True')

Status : Correct Marks : 10/10

4. Problem Statement

Sarah needs a program to replace specific characters in two given strings.


She wants all occurrences of a particular character in both strings to be
replaced with another character using the format() function. Can you help
her with this task?

Example:

Input:
Hello
World
o
a

Output:
The updated string is: Hella Warld

Explanation:
Here the character 'o' is replaced with 'a' in the concatenated string.

Answer
# You are using Python
string1 = input()
string2 = input()
char_to_replace = input()
char_to_replace_with = input()

str1 = ""
for char in string1:
if char == char_to_replace:
str1 += char_to_replace_with
else:
str1 += char

str2 = ""
for char in string2:
if char == char_to_replace:
str2 += char_to_replace_with
else:
str2 += char

result = "{} {}".format(str1, str2)


print("The updated string is:", result)

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 6_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Kate needs a Python program that takes input from the user and displays
that input in lowercase using an in-built function. Help Kate with a program.

Answer
n=input()
# You are using Python
lowercase_string = n.lower()

# Output the lowercase string


print(lowercase_string)
#Footer

Status : Correct Marks : 10/10


2. Problem Statement

Write a program that takes a string and returns a new string with any
duplicate consecutive letters removed.

Example:
"ppoeemm" -> "poem"
"wiiiinnnnd" -> "wind"

Answer
word = input()
res = ""
i=0
# You are using Python
while i < len(word):
# Append the current character to the result
res += word[i]

# Check for consecutive duplicate characters


while i + 1 < len(word) and word[i] == word[i + 1]:
i += 1

# Move to the next character


i += 1
print(res)

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 7_MCQ

Attempt : 2
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. Which method in Python is used to create an empty list?

Answer
list()
Status : Correct Marks : 1/1

2. What will be the output of the following code?

numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers)
Answer
[1, 2, 3, 4, 5, 6]
Status : Correct Marks : 1/1

3. What will be the output of the following code?

numbers = [1, 2, 3, 4, 5]
numbers.remove(6)
print(numbers)
Answer
ValueError: list.remove(x): x not in list
Status : Correct Marks : 1/1

4. What is the output of the following addition (+) operator?

a = [10, 20]
b=a
b += [30, 40]
print(a)
print(b)
Answer
[10, 20, 30, 40][10, 20, 30, 40]
Status : Correct Marks : 1/1

5. What is the output of the following code?

L= [3, 4, 5, 20, 5, 25, 1, 3]


print(L.extend([34, 5]))
Answer
None of the mentioned options
Status : Correct Marks : 1/1

6. What will be the output of the following code?


a=(1,2,3,4)
print(sum(a,3))
Answer
13
Status : Correct Marks : 1/1

7. Which of the following is a Python tuple?

Answer
(1, 2, 3)
Status : Correct Marks : 1/1

8. Choose the correct way to access value 20 from the following tuple.

aTuple = ("Orange", [10, 20, 30], (5, 15, 25))


Answer
aTuple[1][1]
Status : Correct Marks : 1/1

9. Predict the output for the following code:

a=(1,2,3,4)
print(a[1:-1])
Answer
(2, 3)
Status : Correct Marks : 1/1

10. len() function returns the number of elements in the tuple. True or
False?

Answer
True
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 7_COD

Attempt : 2
Total Mark : 40
Marks Obtained : 40

Section 1 : Coding

1. Problem Statement

Alex is working on a Python program to manage a list of elements. He


needs to append multiple elements to the list and then remove an element
from the list at a specified index.

Your task is to create a program that helps Alex manage the list. The
program should allow Alex to input a list of elements, append them to the
existing list, and then remove an element at a specified index.

Answer
# You are using Python
def manage_list():
# Input the number of elements to append
n = int(input())
# Input the elements to append
elements = []
for _ in range(n):
elements.append(int(input()))

# Input the index to pop


M = int(input())

# Display the original list


print("List after appending elements:", elements)

# Pop the element at index M


popped_element = elements.pop(M)

# Display the list after popping and the popped element


print("List after popping last element:", elements)
print("Popped element:", popped_element)

# Calling the function


manage_list()

Status : Correct Marks : 10/10

2. Problem Statement

Dhoni is organizing his tasks for the day and wants to create a simple to-
do list using Python. He plans to input his tasks one by one and then
remove them as he completes them.

He wants to create a program that allows him to add tasks, mark them as
completed by removing first and last elements from the list, and visualize
his progress.

Answer
# You are using Python
# You are using Python
# Function to manage the to-do list
def manage_todo_list():
# Input the number of elements
N = int(input())
# Input the elements
tasks = []
for _ in range(N):
tasks.append(int(input()))

# Display the list after appending elements


print("List after appending elements:", tasks)

# Pop the last element


last_task = tasks.pop()

# Display the list after popping the last element and the popped element
print("List after popping last element:", tasks)
print("Popped element:", last_task)

# Pop the first element


first_task = tasks.pop(0)

# Display the list after popping the first element and the popped element
print("List after popping first element:", tasks)
print("Popped element:", first_task)

# Calling the function


manage_todo_list()

Status : Correct Marks : 10/10

3. Problem statement

Teju is exploring the fascinating world of tuples and their manipulation.


She is given a task to transform a list of integers into a tuple and
concatenate its elements into a single string.

Help Teju by writing a program that accomplishes this task efficiently.

Example
Input
3 // number of elements in the tuple
1
20
3
Output
(1, 20, 3)
1203

Answer
# You are using Python
def transform_and_concatenate():
# Input the number of elements
n = int(input())

# Input the elements into a list


elements = []
for _ in range(n):
elements.append(int(input()))

tuple_elements = tuple(elements)

print(tuple_elements)
concatenated_string = ''.join(map(str, tuple_elements))
print(concatenated_string)

transform_and_concatenate()

Status : Correct Marks : 10/10

4. Problem Statement

Jai wants to write a program that takes a tuple of elements as input, along
with an index and a new value. The program should replace the element at
the specified index with the new value and print the updated tuple.

Help him with the program.


Answer
# You are using Python
def update_tuple():
elements = input().split()

index = int(input())
new_value = input()

elements = tuple(map(str, elements))

updated_tuple = elements[:index] + (new_value,) + elements[index + 1:]

print(updated_tuple)

update_tuple()

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 7_Automata Fix

Attempt : 2
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Annie, a data analyst, needs to find common values between two arrays as
part of her data processing task. She wants to write a Python program to
efficiently identify and display the common values between the arrays.

Write a program that takes input from the user for two arrays and finds the
common values between them.

Answer
arr1 = [int(num) for num in input().split()]
arr2 = [int(num) for num in input().split()]
# You are using Python
common_values = []
for i in range(len(arr1)):
for j in range(len(arr2)):
if arr1[i] == arr2[j]:
common_values.append(arr1[i])
print(common_values)

Status : Correct Marks : 10/10

2. Problem Statement

Manny wants a program that takes a space-separated input string 'x',


converts it to a tuple, reverses it, and prints the reversed tuple. Assist him
with the program.

Answer
x = input()
# You are using Python
words = x.split()

# Reverse the list of words


x = words[::-1]

# Convert the list to a tuple


result_tuple = tuple(x)
print(tuple(x))

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 8_MCQ

Attempt : 2
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What will be the output of the following code?

d={1:'a',2:'b',1:'A'}
print(d[1])
Answer
A
Status : Correct Marks : 1/1

2. Predict the output for the following Python code:

a={'B':5,'A':9,'C':7}
print(sorted(a))
Answer
['A', 'B', 'C'].
Status : Correct Marks : 1/1

3. What is the output of the following code?

a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
Answer
{1: 'A', 2: 'D', 3: 'C'}
Status : Correct Marks : 1/1

4. Predict the output for the following code:

d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
print(D1 > d2)
Answer
Compilation Error
Status : Correct Marks : 1/1

5. Suppose d is given a snippet; to delete the entry for “John,” what


command do we use?

d = {"John": 40, "peter": 45}


_______
print(d)
Answer
del d["John"]
Status : Correct Marks : 1/1
6. What will be the output of the following program?

set1 = {1, 2, 3}
set2 = set1.copy()
set2.add(4)
print(set1)
Answer
{1, 2, 3}
Status : Correct Marks : 1/1

7. What is the output of the following?

set1 = {10, 20, 30, 40, 50}


set2 = {60, 70, 10, 30, 40, 80, 20, 50}
print(set1.issubset(set2))
print(set2.issuperset(set1))
Answer
TrueTrue
Status : Correct Marks : 1/1

8. What will be the output of the following code?

set1 = {"Yellow", "Orange", "Black"}


set2 = {"Orange", "Blue", "Pink"}
set3 = set2.difference(set1)
print(set3)
Answer
{'Pink', 'Blue'}
Status : Correct Marks : 1/1

9. If a = {5,6,7}, what happens when a.add(5) is executed?

Answer
a={5,6,7}
Status : Correct Marks : 1/1

10. Which of these about a set is not true?

Answer
Immutable data type
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 8_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : Coding

1. Problem Statement

Bala is a teacher who is responsible for managing the grades of his


students. He has a system where he inputs the names of the students
along with their respective scores in different subjects using dictionary.
Bala wants a program that can calculate the average score of a particular
student based on the given input.

Write a Python program to help Bala achieve this task.

Answer
# You are using Python
n = int(input())
mark = {}

for i in range(n):
x = input().split(" ", 1)
x[1] = x[1].split()
mark[x[0]] = [int(score) for score in x[1]]

find = input()
total_marks = sum(mark[find])
average_marks = total_marks / len(mark[find])
print(round(average_marks, 2))

Status : Correct Marks : 10/10

2. Problem Statement

Ram has completed his grocery shopping and has a list of products, each
with its corresponding quantity and price. He seeks assistance in
calculating the total amount he spent during his shopping trip.

Your task is to create a dictionary that takes input regarding the products
purchased by Ram, including the product name, quantity, and price, and
calculates the total amount spent.

Answer
N = int(input())
total_amount = 0
for _ in range(N):
name, quantity, price = input().split()
total_amount += float(quantity) * float(price)
print("{:.2f}".format(total_amount))

Status : Correct Marks : 10/10

3. Problem Statement

Lucy, a data analyst, is working on a project where she needs to compare


two sets of strings, set1 and set2. She wants to understand the
relationship between these sets by performing various set operations such
as finding the difference, union, intersection, and symmetric difference.
The results for each operation should be printed as sorted lists.

Your task is to write a program to assist Lucy with these tasks.

Answer
# You are using Python
set1_input = input()

set1 = set(elem.strip() for elem in set1_input.split(","))

set2_input = input()
set2 = set(elem.strip() for elem in set2_input.split(","))

print(sorted((set1.difference(set2))))
print(sorted((set1.union(set2))))
print(sorted((set1.intersection(set2))))
print(sorted((set1.symmetric_difference(set2))))

Status : Correct Marks : 10/10

4. Problem Statement

Rishi is working on a program to manipulate a set of integers. The program


should allow users to perform the following operations:

Find the maximum value in the set.Find the minimum value in the
set.Remove a specific number from the set.
Rishi needs to ensure that the program handles these operations
accurately and efficiently.

Answer
num_list = [int(x) for x in input().split()]

num_set = set(num_list)
print(num_set)

ch = int(input())

if ch == 1:
print(max(num_set))
elif ch == 2:
print(min(num_set))
elif ch == 3:
n1 = int(input())
num_set.discard(n1)
print(num_set)
else:
print("Invalid choice")

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 8_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata Fix

1. Problem Statement

Create a Python program that takes a set of integers as input, and


determines both the maximum and minimum values within the set. Display
these extremum values as the program's output.

Answer
input_list = input().split()
# You are using Python
for i in range(0,len(input_list)):
input_list[i] = int(input_list[i])

set1 = set(input_list)

print(max(set1))
print(min(set1))
#Footer

Status : Correct Marks : 10/10

2. Problem Statement

Anne works at a stationery shop that sells various items such as pens,
pencils, papers, etc. She is responsible for maintaining a record of the
items and their quantities. The information about each item is provided in
the format "item_name: quantity".

Your goal is to help Anna create a dictionary for the stationery shop and
print all the unique values in the dictionary.

Answer
n=int(input())
stat=[]
# You are using Python
for i in range(n):
dict1 = {}
inp = input().split(':')
dict1[inp[0]] = inp[1]
stat.append(dict1)
u_value = set( val for dict1 in stat for val in dict1.values())
print(sorted((set(u_value))))
##No Footer

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 9_MCQ

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. Which of the following blocks will be executed whether an exception is


thrown or not?

Answer
finally
Status : Correct Marks : 1/1

2. When is the finally block executed?

Answer
always
Status : Correct Marks : 1/1
3. When will the else part of try-except-else be executed?

Answer
when no exception occurs
Status : Correct Marks : 1/1

4. What is the output of the following code?

def foo():

try:

return 1

finally:

return 2

k = foo()

print(k)
Answer
2
Status : Correct Marks : 1/1

5. What will be the output of the following Python code?

def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(6)
Answer
6
Status : Correct Marks : 1/1

6. What will be the output of the following Python code?

int('65.43')
Answer
ValueError
Status : Correct Marks : 1/1

7. What will be the output of the following program?

def foo():
try:
print(1)
finally:
print(2)
foo()
Answer
12
Status : Correct Marks : 1/1

8. Which of the following statements is true?

Answer
The standard exceptions are automatically imported into Python programs
Status : Correct Marks : 1/1

9. Which of the following is not a standard exception in Python?

Answer
AssignmentError
Status : Correct Marks : 1/1
10. What will be the output of the following Python code?

def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
Answer
Error
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 9_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : Coding

1. Problem Statement

Write a program that calculates the average of a list of integers. The


program prompts the user to enter the length of the list (n) and each
element of the list. It performs error handling to ensure that the length of
the list is a non-negative integer and that each input element is a numeric
value.

Answer
n = -1

while n < 0:

try:
n = int(input())
if n <=0:
print("Error: The length of the list must be a non-negative integer.")
exit()
except ValueError:
print("Error: You must enter a numeric value.")
exit()
numbers = []
for i in range(n):
while True:
try:
num = int(input())
except ValueError:
print("Error: You must enter a numeric value.")
exit()
else:
numbers.append(num)
break

average = sum(numbers) / n
print("The average is: {:.2f}".format(average))

Status : Correct Marks : 10/10

2. Problem Statement

Write a program that takes a sequence of space-separated inputs,


attempts to convert them to integers, calculates their sum.

The program should calculates the sum of the integers, handles


exceptions by printing an error message "Only Integers are allowed" if a
non-integer value is encountered.

Answer
inp = input().split()

sum = 0

exp_ind = 0

for i in range(0, len(inp)):


try:
inp[i] = int(inp[i])
sum = sum + inp[i]
except ValueError:
print('Only Integers are allowed')
exp_ind = 1
break

if exp_ind == 0:
print('{}'.format(sum))

Status : Correct Marks : 10/10

3. Problem Statement

Alex has selected a secret number in a guessing game. The player receives
feedback after each guess, helping them determine the correct value. The
game continues until the player guesses correctly or decides to quit by
entering '$'.

Feedback indicates if the guess is too small, too large, or correct. Players
can choose to play again (by entering any character) or quit (by entering
'$').

Answer
x = int()
x = int(input())
ch = 'y'

while (ch != '$'):


try :
n = int(input())
if n<x :
raise Exception('Value is small')
elif n>x :
raise Exception('Value is large')
else :
print("Well Done")

except Exception as e:
print(e)
ch = input()[0]

Status : Correct Marks : 10/10

4. Problem Statement

Implement a program that checks whether a set of three input values can
form the sides of a valid triangle. The program defines a function
is_valid_triangle that takes three side lengths as arguments and raises a
ValueError if any side length is not a positive value. It then checks whether
the sum of any two sides is greater than the third side to determine the
validity of the triangle.

Answer
def is_valid_triangle(side1, side2, side3):

if side1 <= 0 or side2 <= 0 or side3 <= 0:

raise ValueError("Side lengths must be positive.")

if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2:
return True
else:
return False

def main():
side1 = int(input())
side2 = int(input())
side3 = int(input())

try:
if is_valid_triangle(side1, side2, side3):
print("It's a valid triangle.")
else:
print("It's not a valid triangle.")
except ValueError as e:
print("ValueError: " + str(e))
if __name__ == "__main__":
main()

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 9_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata fix

1. Problem Statement

Design a simple discount application that checks whether a given


purchase amount qualifies for a discount. If the purchase amount is less
than 1000, an exception (InvalidDiscountException) is raised, indicating
that no discount is applicable. Otherwise, it prints "Discount Applied !!".

Answer
class InvalidDiscountException:
def __init__(self,msg):
print(msg)
def check():
amount=int(input())
try:
if amount<1000:

InvalidDiscountException("No Discount")
else:
print("Discount Applied !!")
except InvalidDiscountException as e:
print(e)
check()

Status : Correct Marks : 10/10

2. Problem Statement

Develop a program that calculates the salary per day for a person based on
the net salary earned (n) and the number of days worked (w). The program
includes error handling to address the scenario where the user inputs zero
for the number of days worked (w). In such a case, a ZeroDivisionError
exception is raised, and the program handles this exception by printing an
appropriate error message.

Answer
n = float(input())
w = int(input())
try:

s = float(n/w)

print('%.2f'%s)
except ZeroDivisionError as e:
print("Division by Zero")
#no footer

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 10_MCQ

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : MCQ

1. What is the correct syntax of open() function?

Answer
file object = open(file_name [, access_mode][, buffering])
Status : Correct Marks : 1/1

2. Which function is used to close a file in Python?

Answer
close()
Status : Correct Marks : 1/1
3. Which of the following mode will refer to binary data?

Answer
b
Status : Correct Marks : 1/1

4. Which of the following statements are true?

Answer
All of the mentioned options
Status : Correct Marks : 1/1

5. How do you get the name of a file from a file object (fp)?

Answer
fp.name
Status : Correct Marks : 1/1

6. In file handling, what do the terms "r, a" mean?

Answer
read, append
Status : Correct Marks : 1/1

7. Fill the code in order to get the following output.

Current position: 0

f = open("ex.txt", "w+")
_____________ #(1)
print("Current poistion: ",__________) #(2)
Answer
1) f.seek(0,0)2) f.tell()
Status : Correct Marks : 1/1

8. Which function is used to write a list of strings in a file?

Answer
writelines()
Status : Correct Marks : 1/1

9. How do you get the current position within the file?

Answer
fp.tell()
Status : Correct Marks : 1/1

10. To read the next line of the file from a file object infile, we use

Answer
infile.readline()
Status : Correct Marks : 1/1
Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 10_COD

Attempt : 1
Total Mark : 40
Marks Obtained : 40

Section 1 : Coding

1. Problem Statement

Sophie enjoys playing with words and wants to count the number of words
in a sentence. She inputs a sentence, saves it to a file, and then reads it
from the file to count the words.

Write a program to determine the number of words in the input sentence.

File Name: sentence_file.txt

Answer
sentence = input()

with open("sentence_file.txt", "w") as file:


file.write(sentence)

with open("sentence_file.txt", "r") as file:


saved_sentence = file.read()

words = saved_sentence.split()
word_count = len(words)

print(word_count)

Status : Correct Marks : 10/10

2. Problem Statement

John is a data analyst who often works with text files. He needs a program
that can analyze the contents of a text file and count the number of times a
specific character appears in the file.

John wants a simple program that allows him to specify a file and a
character to count within that file.

Answer
# You are using Python
def count_character_in_fle(fle_name, character):
try:
with open(fle_name, 'r') as fle:
content = fle.read()
count = content.lower().count(character.lower())
return count
except FileNotFoundError:
return -1

fle_name = input()
content = input()
character_to_count = input()

with open(fle_name, 'w') as fle:


fle.write(content)

result = count_character_in_fle(fle_name, character_to_count)


if result == -1:
print("File not found.")
elif result == 0:
print("Character not found in the file.")
else:
print(f"The character '{character_to_count}' appears {result} times in the file.")

Status : Correct Marks : 10/10

3. Problem Statement

Sophie enjoys playing with words and wants to determine whether a word
is a palindrome. She inputs a word, saves it to a file, and then reads it from
the file to check for palindromes. Write a program to confirm if her word
reads the same forwards and backwards.

File Name: word_file.txt

Answer
# You are using Python
word = input().strip()

with open("word_file.txt", "w") as file:


file.write(word)

with open("word_file.txt", "r") as file:


file_contents = file.read()

if file_contents.lower() == file_contents.lower()[::-1]:
print(f"'{word}' is a palindrome!")
else:
print(f"'{word}' is not a palindrome.")

Status : Correct Marks : 10/10

4. Problem Statement:
Bob, a data analyst, requires a program to automate the process of
analyzing character frequency in a given text. This program should allow
the user to input a string, calculate the frequency of each character within
the text, save these character frequencies to a file named
"char_frequency.txt," and display the results.

Answer
# You are using Python
text = input().strip()

char_frequency = {}
for char in text:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1

with open("char_frequency.txt", "w") as file:


file.write("Character Frequencies:\n")
for char, count in char_frequency.items():
file.write(f"{char}: {count}\n")

print("Character Frequencies:")
for char, count in char_frequency.items():
print(f"{char}: {count}")

Status : Correct Marks : 10/10


Knowledge Institute of Technology
Name: SANTHOSH V S Scan to verify results

Email: [email protected]
Roll no: 611223106092
Phone: 9715828387
Branch: Knowledge Institute of Technology
Department: ECE
Batch: 2027
Degree: BE ECE

2023_27_II_ECE_GE308_Programming in Python Lab Course

NeoColab_KIOT_Non_CSE_Python_Week 10_Automata Fix

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Automata fix

1. Problem Statement

Write a user-defined function countwords() to display the total number of


words present in the file from a text file "Quotes.Txt".

Note: Contents of the file are prepopulated.

Answer
f_out=open("Quotes.txt","w")
f_out.write("The world is beautiful")
f_out.close()
f_out = open("Quotes.txt", "w")
f_out.write("The world is beautiful")
f_out.close()
def countwords():
with open("Quotes.txt", "r") as file:
text = file.read()
words = text.split()
return len(words)
count = countwords()

print(count)

Status : Correct Marks : 10/10

2. Problem statement

Write a Python program that takes the names of two text files as input
from the user, prompts the user to enter the contents of each file, and then
writes the contents to the respective files on disk.

The program should then read in the contents of the two files, compare
them line by line, and output the lines that are different. If the two files are
identical, the program should output a message indicating that they are
identical.

Answer
# get file names from user input
file1_name = input()
file2_name = input()

# get file contents from user input


file1_contents = input()
file2_contents = input()
with open(file1_name, "w") as file1:
file1.write(file1_contents)

with open(file2_name, "w") as file2:


file2.write(file2_contents)
with open(file1_name, "r") as file1, open(file2_name, "r") as file2:
lines1 = file1.readlines()
lines2 = file2.readlines()
if lines1 == lines2:
print(f"{file1_name} and {file2_name} are identical.")
else:
print(f"The following lines are different in {file1_name} and {file2_name}:")
for i, (line1, line2) in enumerate(zip(lines1, lines2), start=1):
if line1 != line2:
print(f"{file1_name} line {i}: {line1.strip()}")
print(f"{file2_name} line {i}: {line2.strip()}")

Status : Correct Marks : 10/10

You might also like