Lab 2 Assingment
Lab 2 Assingment
Problem Statements
1. Write a Python program to Sum only even natural numbers up to n terms given by the
user. Use control flow tokens.
Solution
n=int(input("enter the number of terms"))
sum=0
for i in range(2,n+1):
if i%2==0:
sum+=i
i+=2
print("sum of even natural numbers up to", n, "terms is:",sum)
Explanation
- The program asks the user to input the number of terms.It initializes a sum
variable to store the sum of even numbers and a counter i starting from 2.The while loop
runs until i reaches n*2 (since we're considering even numbers up to n terms).Inside the
loop, it checks if i is even using the modulus operator (%). If i is even, it adds i to the
sum.The counter i increments by 2 in each iteration to consider only even numbers.
Finally, the program prints the sum of even natural numbers up to n terms.
2. Write a Python program to find the factorial of a number using loops. Take input from the
user.
Solution
n=int(input("enter the number"))
fact=1
for i in range(1,n+1):
fact*=i
print("factorial is",fact)
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
Explanation
This code takes the number as input from the user. Then fact is declared as a
variable which is assigned to value 1.The for loop is declared to multiply the input
number from 1. Then print statement is used to diplay the factorial.
3. Create a Python program that counts down from 10 to 1 using a while loop. For each
number, if the number is odd, print "Odd: <number>", and if it is even, print "Even:
<number>". When it reaches 0, print "Blast off!".
Expected output:
Odd: 9
Even: 8
Odd: 7
Even: 6
Odd: 5
Even: 4
Odd: 3
Even: 2
Odd: 1
Blast off!
Solution
n=10
while(n>0):
if n%2==0:
print(f"even",n)
else:
print(f"odd",n)
n=n-1
print("blast off")
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
Explanation:
3.Write a Python program that takes a number from the user and prints its multiplication table
(from 1 to 10) using a for loop.
Solution
n=int(input("enter the number"))
print(f"multiplication table of {n} is:")
for i in range(1,11):
print(f"{n} x {i} = {n*i}")
Explanation
Input statement is used to take number for multiplication table. Second statement is used
to print a title for the multiplication table with the number. For loop iterates the number
from 1 to 10. The last statement is used to print the table with the numbers and product.
F string is used for clean and readable strings.
4. Create a Python program that prints the numbers from 1 to 30. For multiples of 3, print
"Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers that are
multiples of both 3 and 5, print "FizzBuzz".
Expected output:
1
2
Fizz
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Solution
for i in range(1,30):
if i%3==0:
print("fizz")
elif i%5==0:
print("buzz")
elif i%3 and i%5 ==0:
print("fizz buzz")
else:
print(i)
Explanation
In this code the for loop iterates from 1 to 30. If condition is used to check if the
number is multiple of 3 it prints fizz and if it is a multiple of 5 it prints buzz. If any
number is multiple of 3 and 5 both it prints fizzbuzz.if it is not multiple of 3 or 5 it
prints the number itself
.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
5. Write a Python program that takes a number as input and checks whether the number is
prime or not. A prime number is a number greater than 1 that has no divisors other than
1 and itself.
Solution
n=int(input("enter a number"))
if n>1:
for i in range(2,n):
if(n%i)==0:
print(n,"is not prime")
break
else:
print(n,"is prime")
Explanation
The code first checks if n is greater than 1, since prime numbers are greater than 1. It
then iterates from 2 to n-1 and checks if n is divisible by any of these numbers (if (n % i)
== 0). If n is divisible, it prints "n is not prime" and exits the loop using break. Otherwise,
it prints "n is prime".
6. Write a Python program to print a right-angled triangle of numbers where each row
contains the number repeated multiple times. The number of rows is provided by the
user.
For input 5
1
22
333
4444
55555
Solution
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
n=int(input("enter a number"))
for i in range(n+1):
for j in range(i):
print(i,end=" ")
print(" ")
Explanation:
The outer loop (for i in range(n+1)) iterates from 0 to n. The inner loop (for j in
range(i)) prints the number i repeatedly, i times. The end=" " argument in print(i,end=" ")
ensures numbers are printed on the same line, separated by spaces.
7. Write a Python program to find the sum of the digits of a given number. For eg. , for input
123, the output should be 6 (1 + 2 + 3 = 6).
Solution
n=int(input("enter a number"))
sum=0
while(n>0):
rem=n%10
sum=sum+rem
n=n//10
print("sum is",sum)
Explanation:
The user inputs a number, which is stored in n. The code enters a loop where it extracts
the last digit of n using n % 10 (remainder), adds it to the sum, and then removes the last
digit from n using n // 10 (integer division). The loop repeats until n becomes 0.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
8. John is using a computer in which arithmetic operations (+, -, *, /, **) are not working. But
as his assignments deadline are near he is looking for alternative methods. Help him out
in solving the below questions using other operators.
a. To calculate the power of 2 up to n terms.
Eg. 2 , 2 , …… ,2
0 1 (n-1)
- (33 = 2 + 2 )
5 0
Try using “bitwise or” and “bitwise shifts” operators instead of addition and
multiplication operators.
Solution
a)
n=int(input("enter the number"))
for i in range(0,n+1):
print("power of 2",i,"",1<<i)
b)
n=int(input("enter the number"))
binary= bin(n)[2:]
if binary[-1]=='0':
print(f"{n} is even")
else:
print(f"{n} is odd")
Explanation
a) The loop iterates from 0 to n (inclusive) using range(0, n+1).Inside the loop, 1 << i
calculates the power of 2 using bitwise left shift operation (equivalent to 2^i).
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
b) The bin() function converts the input number to its binary representation.The [2:]
slicing removes the '0b' prefix from the binary string. The [-1] indexing accesses
the last character (least significant bit) of the binary string. If the least significant
bit is '0', the number is even; otherwise, it's odd.
c) we prompt the user to enter another number and calculate its product with 33 by
left-shifting the number 1 by 5 positions to multiply it by 32 and then adding the
original number. We print the final result of this multiplication.
b. Imagine you are a student calculating your final semester grade. You have 5 subjects,
and each subject has a score between 1 and 100. Write a Python program that:
Takes the score of each subject using a for loop.
Calculates the average score.
Assigns a grade based on the following scale:
o 90 and above: Grade A
o 80-89: Grade B
o 70-79: Grade C
o 60-69: Grade D
o Below 60: Grade F
Solution:
total_score=0
score=[]
for i in range(6):
while True:
score=float(input(f"enter score for subject{i+1} (1-100):"))
if 1<=score<=100:
score.append(score)
break
else:
print("invalid score enter a score between 1 and 100")
average_score=sum(scores)/len(scores)
if average_score>=90:
grade="A"
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
Explanation
We prompt the user to enter the marks for five subjects using a for loop. Each entered mark is
appended to a list called l. After collecting the marks, we calculate the total by summing the
values in the list and compute the percentage by dividing the total by 6. Then, we determine the
grade based on the percentage: if the percentage is 90 or above, we assign the grade 'A'; if it's
between 80 and 89, we assign 'B'; if it's between 70 and 79, we assign 'C'; if it's between 60 and
69, we assign 'D'; otherwise, we assign 'F'. Finally, we print the calculated percentage and the
corresponding grade.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
1. You need to introduce yourself to your new classmates. What will you say as an ice
breaker? Display it in the format: My name is _____ and a fun fact about me is ____
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
2. You go out for dinner with your friends and need to split the bill equally, how will you do
so by taking input of the bill amount and number of friends?
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
3. You have a certain amount of total work(n) that needs to be shared among a fixed
number of workers m. Write a program to calculate the amount of work for each worker
and how much extra work is left. Take input for no. of work and no. of workers.
eg:
n = 100
m=6
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
4. Tiling of a rectangular floor is performed. Write a program that calculates the number of
tiles required and the total cost to tile the entire floor. Take the dimensions of the floor
and the size and price of each tile as input from the user. Also consider labor charges.
Input:
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
5. Two persons A and B are conducting a Chemical experiment. In which A is user element
D and E in ratio of 2:1 and B uses the ratio of 4:3, calculate the mass of the compound if
each generates a 1 mole gram of substance given that the mass of D is 1 unit(amu) and
E is 5 units(amu). Take the values from the user.
Hint - Consider using split() method on the input string
eg-
"1:2".split(":") # [‘1’,’2’]
a,b = "1:2".split(":") # a <- '1' ; b <- ‘2
a,b = int(a), int(b) # type casting char/string to integers
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
6. Given a 4 digit integer no. , display the individual digit & compute the sum of digits.
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
7. You are asked to color quarter of a circle withreed, one third of the remaining with blue
and rest in yellow, find the area covered by each color and perimeter of each color
(include inner boundaries also ). Take radius as input.
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
8. You've just celebrated your birthday, and you're curious about how many months, days,
and hours you've been alive. Write a Python program that takes your age(in years) as
input and prints your age in months and days.
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
9. Imagine you've just opened a savings account at your local bank. You're curious how
much interest you'll earn after a few years. Write a Python program that calculates the
simple interest based on the amount you've deposited, the bank’s interest rate, and the
number of years you plan to keep the money in the account.
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
10. You’re planning a vacation to a different country, but their weather forecasts are in
Celsius, and you’re more familiar with Fahrenheit. Write a Python program to help you
convert temperatures from Celsius to Fahrenheit so you can pack accordingly for your
trip! (use the formula: F = C * 9/5 + 32)
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
11. You’re baking a cake, but the recipe you’re following is for 12 servings, and you need to
make enough for a different number of people. Write a Python program that takes the
number of servings you want to make and adjusts the ingredients accordingly. If the
recipe calls for 2 cups of sugar for 12 servings, calculate how many cups of sugar you'll
need for the number of servings entered by the user.
Solution
Explanation
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4
12. You're throwing a pizza party for your friends, and you want to make sure everyone gets
an equal number of slices. Write a Python program that takes the number of pizzas,
slices per pizza, and the number of people attending the party as input, and calculates
how many slices each person gets. Also, calculate how many slices will be left over.
Solution
Explanation