Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python File

The document contains 20 questions related to Python programming concepts like calculating area of triangle, finding largest number in list, checking even/odd number, Armstrong number, factorial, reversing number, date calculations, encryption/decryption, mean, median, mode, standard deviation, list and tuple operations. Each question has sample code to demonstrate the concept through inputs, calculations and outputs.

Uploaded by

manishjanwani7
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python File

The document contains 20 questions related to Python programming concepts like calculating area of triangle, finding largest number in list, checking even/odd number, Armstrong number, factorial, reversing number, date calculations, encryption/decryption, mean, median, mode, standard deviation, list and tuple operations. Each question has sample code to demonstrate the concept through inputs, calculations and outputs.

Uploaded by

manishjanwani7
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Q1 Calculate area of a triangle

#let a = side1, b = side2 and c = side3 of triangle


a, b, c = map(int, input("Enter sides of triangle : ").split())

#The semi-perimeter of triangle ABC => s = (a + b + c)/2


s = (a + b + c) / 2

#Then, the area of triangle ABC = √[s × (s – a) × (s – b) × (s – c)]


area = (s * (s - a) * (s - b) * (s - c)) ** 0.5

print(f"Area of Triangle : {format(area, '0.3f')}")

Q2 Find largest number in a list


numbers = [5, 6, 8, 12, 3, 16, 1]

largest = numbers[0]
for item in numbers:
if item > largest:
largest = item

print(f"List : {numbers}")
print(f"Largest in list : {largest}")

Q3 Checking if given number is an even or odd

print("Checking Even or Odd")


number = int(input("Enter Number : "))

if abs(number) % 2 == 0 :
print("Number is Even")
else:
print("Number is Odd")

Q4 Checking if given number is an even or odd using function

def IsEven(num : int) -> bool:


if abs(num) % 2 == 0 :
return True
else:
return False
print("Checking Even or Odd")
number = int(input("Enter Number : "))

if IsEven(number):
print("Number is Even")
else:
print("Number is Odd")

Q5 Check if given number is an armstrong number

def IsArmstrong(num : int) -> bool:


temp = 0
num_ref = num
while num_ref > 0:
temp += ((num_ref % 10) ** 3)
num_ref = num_ref // 10

return temp == num

num = int(input("Enter number : "))

if IsArmstrong(num):
print("Number is Armstrong number.")
else:
print("Number is not Armstrong number.")

Q6 Find largest number in a list using function

def find_max(list):
maximum = list[0]
for item in list:
if item > maximum:
maximum = item

return maximum

numbers = [5, 6, 8, 12, 3, 16, 1]

print(f"List : {numbers}")
print(f"Largest in list : {find_max(numbers)}")
Q7 Find factorial of a given number

num = int(input("Enter number to find its factorial : "))

fact = 1
for i in range(1, num + 1):
fact *= i

print(f"Factorial of {num} : {fact}")

Q8 Check if user is eligible(18) or not

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

if age >= 18:


print("Eligible.")
else:
print("Not eligible.")

Q9 Reverse the given number

num = int(input("Enter number to reverse it : "))

rev = 0
while num > 0:
r = int(num % 10)
rev = int(r + rev * 10)
num //= 10

print(f"Reversed number : {rev}")

Q10 Find current age


from datetime import date

def calculate_age(birthdate : date):


today = date.today()
diff = today - birthdate
return diff.days // 365

dob = input("Enter Date of Birth in format (YYYY-MM-DD) : ")


try:
birthdate = date.fromisoformat(dob)
print(f"Your Age : {calculate_age(birthdate)}yrs")
except ValueError:
print("Enter DOB in valid format!")

Q11 Perform encryption and Decryption without using library

encryption_base = "bpcrfagdxejvqilsnhowtkumzyBPCRFAGDXEJVQILSNHOWTKUMZY~!@#$
%^&*()_+{/}\\|\":<>?] [';.,`-=0123456789"

def encrypt(string : str) -> str:


string = string[::-1]
temp = ""
for ch in string:
temp += "\\x" + str(encryption_base.find(ch))
if ch.isspace():
temp += "</>"
elif ch.isdigit():
temp += "//"
elif ch.isalpha():
temp += "xcb"
else:
temp += "/;"

return temp

def decrypt(string : str) -> str:


temp = string.split("\\x")
temp_str = ""
decrypted = ""
for st in temp:
for ch in st:
if ch.isdigit():
temp_str += ch

if temp_str != "":
decrypted += encryption_base[int(temp_str)]
temp_str = ""

return decrypted[::-1]

msg = input("Enter password to encrypt : ")


encrypted = encrypt(msg)
print(f"Encrypted : {encrypted}")
print(f"Decrypted : {decrypt(encrypted)}")

Q12 Check if given number is positive, negative or zero

print("Checking if number is Positive, Negative or Zero ---")


num = int(input("Enter number : "))

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

Q13 Print Full name on string/screen using function

def full_name(firstname : str, lastname : str) -> str:


return f"{firstname} {lastname}"

f_name = input("Enter your first name : ")


l_name = input("Enter your last name : ")

print(full_name(f_name, l_name))

Q14 Find sum of positive, negative and zero numbers in a list

numbers = [12, 0, -74, 32, -12, 9, -1, -7, 0, 56, 0, -46, 0, 5, 12]

print(f"List : {numbers}")

zeros = 0
positives = []
negatives = []

for num in numbers:


if num > 0:
positives.append(num)
elif num < 0:
negatives.append(num)
print(f"Sum of Zero : 0")
print(f"Sum of Positives : {sum(positives)}")
print(f"Sum of Negatives : {sum(negatives)}")

Q15 Find Mean of given list

numbers = [30, 13, 94, 16, 97, 13]

print(f"List : {numbers}")

mean = sum(numbers) // len(numbers)

print(f"Mean : {mean}")

Q16 Find Median of given list

numbers = [30, 13, 94, 16, 97, 13]

print(f"List : {numbers}")
numbers.sort()
print(f"Sorted : {numbers}")

count = len(numbers)
half_count = count // 2 - 1
if count % 2 == 0:
median = (numbers[half_count] + numbers[half_count + 1]) / 2
else:
median = numbers[half_count + 1]

print(f"Median : {median}")

Q17 Find Mode of given list

numbers = [30, 13, 94, 16, 97, 13, 94]

print(f"List : {numbers}")

counts = {}
for num in numbers:
if num not in counts:
counts[num] = numbers.count(num)
max_count = 0
for item in counts.items():
if max_count < item[1]:
max_count = item[1]

mode = []
for item in counts.items():
if max_count == item[1]:
mode.append(item[0])

print(f"Mode : {mode}")

Q18 Perform operations of List like append, insert, extend, clear etc.

numbers = [1, 3, 9, 7, 1, 6]

print(f"Given List : {numbers}\n")

numbers.append(3)
print(f"Appended 3")
print(f"List : {numbers}\n")

numbers.insert(3, 4)
print(f"Inserted 4 at index 3")
print(f"List : {numbers}\n")

print(f"Index of element 4 in List : {numbers.index(4)}\n")

numbers.extend([4, 3, 0])
print(f"List extended with [4, 3, 0]")
print(f"List : {numbers}\n")

print(f"No. of 1 in List : {numbers.count(1)}\n")

n = numbers.pop(5)
print(f"Removed element ({n}) at index 5")
print(f"List : {numbers}\n")

numbers.remove(3)
print(f"Removed first occurence of element (3)")
print(f"List : {numbers}\n")
numbers.sort()
print(f"List sorted : {numbers}\n")

numbers.reverse()
print(f"List reversed : {numbers}\n")

numbers.clear()
print(f"List after clearing : {numbers}\n")

Q19 Find Standard Deviation of given list

def get_mean(nums: list) -> int:


return int(sum(nums) / len(nums))

def standard_deviation(data: list) -> float:


mean = get_mean(data)
total = 0
for item in data:
total += (item - mean) ** 2

sd = (total / (len(data) - 1)) ** 0.5


return sd

numbers = [30, 13, 94, 16, 97, 13, 94]

print(f"List : {numbers}")
print(f"Standard Deviation : {standard_deviation(numbers)}")

Q20 Perform operations on tuple

t1 = (51, 42, 34, 91, 76, 42, 81, 11, 42)


print(f"Tuple1: {t1}")

print("Using Built-in functions ->")


print(f"No. of 42 in Tuple1: {t1.count(42)}")
print(f"Index of 11 in Tuple1: {t1.index(11)}")

print("\nSlicing ->")
print(f"Slicing of Tuple1 to get 3rd to 5th item: {t1[2:5]}")

print("\nRepetition operation ->")


t2=(64, 90, 53)
print(f"Tuple2: {t2}")
print(f"3 times repetetion of Tuple2: {t2*3}")

print("\nUnpacking ->")
a, b, c = t2
print(f"A:{a}, B:{b}, C:{c} after unpacking Tuple2:{t2}")

print("\nConcatenation operation ->")


t3=(46, 90)
print(f"Tuple3: {t3}")
print(f"Tuple2 + Tuple3: {t2+t3}")

You might also like