0% found this document useful (0 votes)
2 views16 pages

Python Assignment

The document contains a series of Python programming assignments covering variable assignments, logical expressions, error categorization, and various programming tasks such as calculating simple interest, temperature conversion, and generating sequences. It includes code snippets and expected outputs for each task, providing a comprehensive guide for beginners to practice Python programming. The assignments also involve mathematical computations and user input handling.

Uploaded by

rsgvg125247
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)
2 views16 pages

Python Assignment

The document contains a series of Python programming assignments covering variable assignments, logical expressions, error categorization, and various programming tasks such as calculating simple interest, temperature conversion, and generating sequences. It includes code snippets and expected outputs for each task, providing a comprehensive guide for beginners to practice Python programming. The assignments also involve mathematical computations and user input handling.

Uploaded by

rsgvg125247
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

Python Assignment

Ques. Write the corresponding Python assignment statements:

a) Assign 10 to variable length and 20 to variable breadth.


length = 10
breadth = 20
b) Assign the average of values of variables length and breadth to a variable sum.
sum = (length + breadth) / 2
c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable
stationery.
stationery = ['Paper', 'Gel Pen', 'Eraser']
d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle
and last.
first = 'Mohandas'
middle = 'Karamchand'
last = 'Gandhi'
e) Assign the concatenated value of string variables first, middle and last to variable
fullname. Make sure to incorporate blank spaces appropriately between different parts
of names.
fullname = first + " " + middle + " " + last

Ques. Write logical expressions corresponding to the following statements in Python and
evaluate the expressions (assuming variables num1, num2, num3, first, middle, last are
already having meaningful values):

a) The sum of 20 and –10 is less than 12.


(20 + (-10)) < 12
b) num3 is not more than 24.
num3 <= 24
c) 6.75 is between the values of integers num1 and num2.
(num1 < 6.75 < num2) or (num2 < 6.75 < num1)
d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.
first < middle < last
e) List Stationery is empty.
len(Stationery) == 0

Ques. Add a pair of parentheses to each expression so that it evaluates to True.

a) 0 == 1 == 2
Correction : 0 == (1 == 2)
b) 2 + 3 == 4 + 5 == 7
Correction : 2 + (3 == 4) + 5 == 7
c) 1 < -1 == 3 > 4
Correction : (1 < -1) == (3 > 4)

Ques. Write the output of the following:

a) num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
I. 2 5
b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
II. 6 4
c) num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
III. NameError: name 'num3' is not defined

Ques. Give the output of the following when num1 = 4, num2 = 3, num3 = 2

a) num1 += num2 + num3


print(num1)
IV. 9
b) num1 = num1 ** (num2 + num3)
print(num1)
=> 1024
c) num1 **= num2 + num3
print(num1)
⇒ 1024
d) num1 = '5' + '5'
print(num1)
⇒ 55
e) print(4.00/(2.0+2.0))
⇒ 1.0
f) num1 = 2 + 9 * ((3 * 12) - 8) / 10
print(num1)
⇒ 27.2
g) num1 = 24 // 4 // 2
print(num1)
⇒3
h) num1 = float(10)
print(num1)
⇒ 10.0
i) num1 = int('3.14')
print(num1)
⇒ ValueError: invalid literal for int() with base 10: '3.14'
j) print('Bye' == 'BYE')
⇒ False
k) print(10 != 9 and 20 >= 20)
⇒ True
l) print(10 + 6 * 2 ** 2 != 9 // 4 - 3 and 29 >= 29 / 9)
⇒ True
m) print(5 % 10 + 10 < 50 and 29 <= 29)
⇒ True
n) print((0 < 6) or (not(10 == 6) and (10 < 0)))
⇒ True

Ques. Categorise the following as syntax error, logical error or runtime error:

a) 25 / 0
⇒ Runtime Error (ZeroDivisionError)
b) num1 = 25
num2 = 0
num1 / num2
⇒ Runtime Error (ZeroDivisionError)

Ques. A dartboard of radius 10 units and the wall it is hanging on are represented using a
two-dimensional coordinate system, with the board's center at coordinate (0,0). Variables x
and y store the x-coordinate and the y-coordinate of a dart that hits the dartboard. Write a
Python expression using variables x and y that evaluates to True if the dart hits (is within) the
dartboard, and then evaluate the expression for these dart coordinates.

Expression:
x2 + y2 <= 100

a) (x, y) = (0, 0)
02 + 02 <= 100
⇒ True
b) (x, y) = (10, 10)
102 + 102 <= 100
⇒ False
c) (x, y) = (6, 6)
62 + 62 <= 100
⇒ True
d) (x, y) = (7, 8)
72 + 82 <= 100
⇒ False

Ques. Write a Python program to convert temperature in degree Celsius to degree Fahrenheit.
If water boils at 100°C and freezes at 0°C, use the program to find out what is the boiling
point and freezing point of water on the Fahrenheit scale.

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = celsius * 9 / 5 + 32
print("Temperature in Fahrenheit =", fahrenheit)

Boiling Point:
100°C = 212.0°F
Freezing Point:
0°C = 32.0°F

Ques. Write a Python program to calculate the amount payable if money has been lent on
simple interest. Principal or money lent = P, Rate of interest = R% per annum and Time = T
years. Then Simple Interest (SI) = (P × R × T) / 100. Amount payable = Principal + SI. P, R
and T are given as input to the program.

P = float(input("Enter Principal Amount: "))


R = float(input("Enter Rate of Interest: "))
T = float(input("Enter Time (in years): "))

SI = (P * R * T) / 100
Amount = P + SI

print("Simple Interest =", SI)


print("Amount Payable =", Amount)

Ques. Write a program to calculate in how many days a work will be completed by three
persons A, B and C together. A, B and C take x days, y days and z days respectively to do the
job alone. The formula to calculate the number of days if they work together is xyz / (xy + yz
+ xz) days where x, y and z are given as input to the program.

x = float(input("Enter number of days taken by A: "))


y = float(input("Enter number of days taken by B: "))
z = float(input("Enter number of days taken by C: "))
days = (x * y * z) / (x * y + y * z + x * z)
print("Number of days taken together =", days)

Ques. Write a program to enter two integers and perform all arithmetic operations on them.

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


num2 = int(input("Enter second number: "))

print("Addition =", num1 + num2)


print("Subtraction =", num1 - num2)
print("Multiplication =", num1 * num2)
print("Division =", num1 / num2)
print("Modulus =", num1 % num2)
print("Floor Division =", num1 // num2)
print("Exponent =", num1 ** num2)

Ques. Write a program to swap two numbers using a third variable.

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


num2 = int(input("Enter second number: "))

temp = num1
num1 = num2
num2 = temp

print("After Swapping:")
print("num1 =", num1)
print("num2 =", num2)

Ques. Write a program to swap two numbers without using a third variable.

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


num2 = int(input("Enter second number: "))

num1, num2 = num2, num1

print("After Swapping:")
print("num1 =", num1)
print("num2 =", num2)

Ques. Write a program to repeat the string "GOOD MORNING" n times.

n = int(input("Enter the value of n: "))


print("GOOD MORNING " * n)
Ques. Write a program to find average of three numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

average = (num1 + num2 + num3) / 3

print("Average =", average)

Ques. The volume of a sphere with radius r is 4/3πr³. Write a Python program to find the
volume of spheres with radius 7 cm, 12 cm and 16 cm respectively.

pi = 3.14159

r=7
volume = (4/3) * pi * r**3
print("Volume of sphere with radius 7 cm =", volume)
r = 12
volume = (4/3) * pi * r**3
print("Volume of sphere with radius 12 cm =", volume)

r = 16
volume = (4/3) * pi * r**3
print("Volume of sphere with radius 16 cm =", volume)

Ques. Write a program that asks the user to enter their name and age. Print a message
addressed to the user that tells the user the year in which they will turn 100 years old.

name = input("Enter your name: ")


age = int(input("Enter your age: "))

current_year = 2026
year = current_year + (100 - age)

print(name, "will turn 100 years old in", year)


Ques. The formula E = mc² states that the equivalent energy (E) can be calculated as the
mass (m) multiplied by the speed of light (c = 3 × 10⁸ m/s) squared. Write a program that
accepts the mass of an object and determines its energy.

m = float(input("Enter mass (in kg): "))

c = 3 * (10 ** 8)
E = m * c ** 2

print("Energy =", E, "Joules")

Ques. Presume that a ladder is put upright against a wall. Let variables length and angle store
the length of the ladder and the angle that it forms with the ground as it leans against the wall.
Write a Python program to compute the height reached by the ladder on the wall for the
following values of length and angle.

import math

length = float(input("Enter the length of the ladder: "))

angle = float(input("Enter the angle in degrees: "))

height = length * [Link]([Link](angle))

print("Height reached by the ladder =", height)

For the given values:


a) length = 16 feet, angle = 75°
⇒ Height = 15.45 feet

b) length = 20 feet, angle = 0°


⇒ Height = 0.00 feet

c) length = 24 feet, angle = 45°


⇒ Height = 16.97 feet

d) length = 24 feet, angle = 80°


⇒ Height = 23.64 feet

Ques. Find the output of the following program segments.

I. a = 110
while a > 100:
print(a)
a -= 2
 110
108
106
104
102

II. for i in range(20, 30, 2):


print(i)
 20
22
24
26
28

III. country = "INDIA"


for i in country:
print(i)
 I
N
D
I
A

IV. i=0
sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i=i+2
print(sum)

 12

V. for x in range(1, 4):


for y in range(2, 5):
if x * y > 10:
break
print(x * y)

 2
3
4
4
6
8
6
9
V. var = 7
while var > 0:
print("Current variable value:", var)
var = var - 1
if var == 3:
break
else:
if var == 6:
var = var - 1
continue
print("Good bye!")

 Current variable value: 7


Current variable value: 5
Current variable value: 4
Good bye!

Ques. Write a program that takes the name and age of the user as input and displays a
message whether the user is eligible to apply for a driving license or not.

 name = input("Enter your name: ")


age = int(input("Enter your age: "))

if age >= 18:


print(name, "is eligible to apply for a driving license.")
else:
print(name, "is not eligible to apply for a driving license.")

Ques. Write a function to print the table of a given number. The number has to be entered by
the user.

 def table(num):
for i in range(1, 11):
print(num, "x", i, "=", num * i)

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


table(n)

Ques. Write a program that prints minimum and maximum of five numbers entered by the
user.

 num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
num4 = int(input("Enter fourth number: "))
num5 = int(input("Enter fifth number: "))

print("Minimum =", min(num1, num2, num3, num4, num5))


print("Maximum =", max(num1, num2, num3, num4, num5))
Ques. Write a program to check if the year entered by the user is a leap year or not.

 year = int(input("Enter a year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):


print(year, "is a Leap Year.")
else:
print(year, "is not a Leap Year.")

Ques. Write a program to generate the sequence: –5, 10, –15, 20, –25..... upto n, where n is
an integer input by the user.

 n = int(input("Enter the value of n: "))

for i in range(1, n + 1):


if i % 2 == 1:
print(-5 * i, end=" ")
else:
print(5 * i, end=" ")

Ques. Write a program to find the sum of 1 + 1/8 + 1/27 + ...... + 1/n³, where n is the number
input by the user.

 n = int(input("Enter the value of n: "))

sum = 0

for i in range(1, n + 1):


sum = sum + (1 / (i ** 3))

print("Sum =", sum)

Ques. Write a program to find the sum of digits of an integer number, input by the user.

 num = int(input("Enter an integer: "))

sum = 0

while num > 0:


digit = num % 10
sum = sum + digit
num = num // 10

print("Sum of digits =", sum)


Ques. Write a function that checks whether an input number is a palindrome or not.

 def palindrome(num):
temp = num
rev = 0

while num > 0:


digit = num % 10
rev = rev * 10 + digit
num = num // 10

if temp == rev:
print("Palindrome Number")
else:
print("Not a Palindrome Number")

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


palindrome(n)

Ques. Write a program to print the following patterns:

a) for i in range(1, 4):

print(" " * (3 - i) + "* " * (2 * i - 1))

for i in range(2, 0, -1):

print(" " * (3 - i) + "* " * (2 * i - 1))

b) for i in range(1, 6):

for j in range(i, 1, -1):

print(j, end=" ")

for j in range(1, i + 1):

print(j, end=" ")

print()

c) for i in range(5, 0, -1):

for j in range(1, i + 1):

print(j, end=" ")

print()
d) n = 5

for i in range(n):

print(" " * (n - i), end="")

print("*")

for i in range(1, n - 1):

print(" " * (n - i - 1) + "* *")

print(" " * n + "*")

Ques. Write a program to find the grade of a student when grades are allocated as given in
the table below. Percentage of the marks obtained by the student is input to the program.

 percentage = float(input("Enter Percentage: "))

if percentage > 90:

print("Grade = A")

elif percentage >= 80:

print("Grade = B")

elif percentage >= 70:

print("Grade = C")

elif percentage >= 60:

print("Grade = D")

else:

print("Grade = E")
Ques. Write a program to check the divisibility of a number by 7 that is passed as a
parameter to the user defined function.

 def check(num):
if num % 7 == 0:
print(num, "is divisible by 7.")
else:
print(num, "is not divisible by 7.")

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


check(n)

Ques. Write a program that uses a user defined function that accepts name and gender (as M
for Male, F for Female) and prefixes Mr/Ms on the basis of the gender.

 def greet(name, gender):


if gender == 'M':
print("Mr.", name)
elif gender == 'F':
print("Ms.", name)
else:
print("Invalid Gender")

name = input("Enter your name: ")


gender = input("Enter Gender (M/F): ")

greet(name, gender)

Ques. Write a program that has a user defined function to accept the coefficients of a
quadratic equation in variables and calculates its determinant.

 def determinant(a, b, c):


d = b ** 2 - 4 * a * c
print("Determinant =", d)

if d > 0:
print("Determinant is Positive.")
elif d == 0:
print("Determinant is Zero.")
else:
print("Determinant is Negative.")

a = float(input("Enter coefficient a: "))


b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

determinant(a, b, c)
Ques. ABC School has allotted unique token IDs from 1 to 600 to all the parents for
facilitating a lucky draw on the day of their Annual Day function. Write a program using
Python that helps to automate the task.

 import random

winner = [Link](1, 600)

print("Winning Token ID =", winner)

Ques. Write a program that implements a user defined function that accepts Principal
Amount, Rate, Time, Number of Times the interest is compounded to calculate and displays
Compound Interest.

 def compound_interest(P, R, T, N):


A = P * (1 + R / (100 * N)) ** (N * T)
CI = A - P
print("Compound Interest =", CI)
print("Amount =", A)

P = float(input("Enter Principal Amount: "))


R = float(input("Enter Rate of Interest: "))
T = float(input("Enter Time (in years): "))
N = int(input("Enter Number of Times Interest is Compounded per Year: "))

compound_interest(P, R, T, N)

Ques. Write a program that has a user defined function to accept 2 numbers as parameters. If
number 1 is less than number 2 then the numbers are swapped and returned, otherwise the
same order is returned.

 def swap(num1, num2):


if num1 < num2:
return num2, num1
else:
return num1, num2

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


b = int(input("Enter second number: "))

a, b = swap(a, b)

print("First Number =", a)


print("Second Number =", b)

Ques. Write a program that contains user defined functions to calculate area, perimeter or
surface area for various shapes like square, rectangle, triangle, circle and cylinder.
 import math

def square(side):
return side * side

def rectangle(length, breadth):


return length * breadth

def triangle(base, height):


return 0.5 * base * height

def circle(radius):
return [Link] * radius * radius

def cylinder(radius, height):


return 2 * [Link] * radius * (radius + height)

print("Area of Square =", square(5))


print("Area of Rectangle =", rectangle(8, 4))
print("Area of Triangle =", triangle(10, 6))
print("Area of Circle =", circle(7))
print("Surface Area of Cylinder =", cylinder(5, 10))

Ques. Write a program that creates a GK quiz consisting of any five questions of your choice.
The questions should be displayed randomly. Create a user defined function score() to
calculate the score of the quiz and another user defined function remark(scorevalue) that
accepts the final score to display remarks.

 import random

questions = [
("Capital of India?", "Delhi"),
("National Animal of India?", "Tiger"),
("2 + 2 = ?", "4"),
("Largest Planet?", "Jupiter"),
("Who wrote Ramayana?", "Valmiki")
]

[Link](questions)

def score():
marks = 0
for q, ans in questions:
user = input(q + " ")
if [Link]() == [Link]():
marks += 1
return marks

def remark(scorevalue):
if scorevalue == 5:
print("Outstanding")
elif scorevalue == 4:
print("Excellent")
elif scorevalue == 3:
print("Good")
elif scorevalue == 2:
print("Read more to score more")
elif scorevalue == 1:
print("Needs to take interest")
else:
print("General knowledge will always help you. Take it seriously.")

marks = score()

print("Marks =", marks)

remark(marks)

You might also like