0% found this document useful (0 votes)
10 views6 pages

Python Answers

The document contains 12 code examples demonstrating various Python programming concepts like input/output, conditional statements, loops, functions, lists, dictionaries, files, modules and more. A variety of tasks are performed such as calculating greatest of 3 numbers, finding student details, displaying Fibonacci sequence, binomial coefficient calculation, list operations, prime number checking, file sorting and traversal. Well-structured code snippets are provided to explain key Python programming techniques.

Uploaded by

Pratham Ahuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views6 pages

Python Answers

The document contains 12 code examples demonstrating various Python programming concepts like input/output, conditional statements, loops, functions, lists, dictionaries, files, modules and more. A variety of tasks are performed such as calculating greatest of 3 numbers, finding student details, displaying Fibonacci sequence, binomial coefficient calculation, list operations, prime number checking, file sorting and traversal. Well-structured code snippets are provided to explain key Python programming techniques.

Uploaded by

Pratham Ahuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

1.

# Get input numbers from the user


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

# Determine the greatest number using nested if-else statements


greatest = num1
if num2 > greatest:
greatest = num2
if num3 > greatest:
greatest = num3

# Print the result


print("The greatest number is:", greatest)

2.

a)

sname = input("Enter Student Name: ")


susn = input("Enter USN: ")
marks = []
tmarks = 0
avgmarks = 0.0
for i in range(3):
print(f"Enter the marks of {sname} in subject {i+1}: ")
m = int(input())
marks.append(m)
tmarks = sum(marks)
avgmarks = tmarks / 3
print(" ")
print("Student Name is: ", sname)
print("Student USN is: ", susn)
print(f"Total Marks scored by {sname} is: {tmarks}")
print(f"Average Marks scored by {sname} is: {avgmarks}")
print(" ")

b)

# Program to display the Fibonacci sequence up to n-th term


nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer!")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto", nterms, "terms :")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence upto", nterms, "terms :")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

3.

A)

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

def nCr(n, r):


return factorial(n) / (factorial(r) * factorial(n - r))

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


R = int(input("Enter the value of R: "))
print("The factorial of ", N, "is ", factorial(N))
print(f"The value of {N}C{R} is", nCr(N, R))

b)

from math import sqrt


list = []
n = int(input("Enter the number of elements to be entered in the list : "))
for i in range(n):
ele = int(input("Enter the element : "))
list.append(ele)
print(list)
total = sum(list)
mean = total / n
variance = sum((i - mean) ** 2 for i in list) / n
stddev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stddev)

4.

A)
num = int(input("Enter the number: "))
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

b)
sum = 0
for num in range(1, 11):
sum += num
average = sum / 10
print("Sum of first 10 natural numbers:", sum)
print("Average of first 10 natural numbers:", average)

5.

A)
def evennum(data):
for num in data:
if num % 2 == 0:
print(num)
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evennum(data)

b)
elements = []
elements.extend(['Carbon', 'Nitrogen', 'Oxygen', 'Helium'])
print("List after inserting four items:", elements)
sele = 'Helium'
if sele in elements:
print(f"{sele} is present in the list.")
else:
print(f"{sele} is not present in the list.")
dele = 'Nitrogen'
if dele in elements:
elements.remove(dele)
print(f"{dele} deleted from the list.")
else:
print(f"{dele} not found in the list.")
print("List after deleting an element:", elements)
nele = 'Boron'
elements.append(nele)
print(f"{nele} added to the end of the list.")
print("List after adding an element to the end:", elements)
elements.sort(reverse=True)
print("List after arranging in descending order:", elements)

6.
nstr = input("Enter a multi-digit number: ")
freq = {}
for char in nstr:
if char.isdigit():
freq[char] = freq.get(char, 0) + 1
for digit, frequency in freq.items():
print(f"The digit {digit} appears {frequency} time(s) in the number.")

7.
birthdays = {'Arun': 'April 10', 'Bindu': 'Jan 23'}
name = input("Enter a name: ")
if name in birthdays:
print(f"The birthday of {name} is on {birthdays[name]}.")
else:
birthdate = input(f"Enter the birthday of {name}: ")
birthdays[name] = birthdate
print(f"{name} has been added to the dictionary with the birthday
{birthdate}.")
print("Updated Birthday Dictionary:", birthdays)

8.
prime = []
for num in range(2, 101):
isprime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
isprime = False
break
if isprime:
prime.append(num)
print(f"Prime numbers between 1 and 100: {prime}")

9.

A)
def remtup(data, k):
return [t for t in data if len(t) != k]
data = [(1, 2, 3), (4, 5), (6, 7, 8, 9), (10, 11, 12)]
k = int(input("Enter the size: "))
ftuple = remtup(data, k)
print(f"Original data: {data}")
print(f"Data after removing tuples of length {k}: {ftuple}")

b)
def is_palindrome(s):
revstr = s[::-1]
return s == revstr
text = input("Enter a string: ")
text = text.lower()
if is_palindrome(text):
print(f"{text} is a palindrome.")
else:
print(f"{text} is not a palindrome.")

10.
def sort_file(input_file_path, output_file_path):
# Read the contents of the input file
with open(input_file_path, 'r') as file:
lines = file.readlines()

# Sort the lines


lines.sort()

# Write the sorted contents to the output file


with open(output_file_path, 'w') as file:
file.writelines(lines)

if __name__ == "__main__":
# Replace 'input.txt' and 'output.txt' with your file names
input_file_path = 'input.txt'
output_file_path = 'output.txt'

try:
sort_file(input_file_path, output_file_path)
print("File sorted successfully. Check", output_file_path)
except Exception as e:
print("An error occurred:", str(e))

def sort_text_file(input_filename, output_filename):


try:
with open(input_filename, 'r') as input_file:
lines = input_file.readlines()

# Sort the lines alphabetically


lines.sort()

with open(output_filename, 'w') as output_file:


output_file.writelines(lines)

print(f"File sorted successfully! Output written to {output_filename}")

except Exception as e:
print("Error: ",str(e))
input_filename = 'input.txt'
output_filename = 'sorted_output.txt'
sort_text_file(input_filename, output_filename)

11.

a)
import os
def walkdir(directory):
for root, directories, files in os.walk(directory):
print(f"Exploring: {root}")
print("Subdirectories:")
for subdirectory in directories:
print(f" - {subdirectory}")
print("Files:")
for file in files:
print(f" - {file}")

print("Directory traversal complete.")


dir = "C:/Users" # Replace with the desired directory path
walkdir(dir)

b)
import os
def delfile():
for filename in os.listdir():
if filename.endswith(".txt"):
file_path = os.path.join(os.getcwd(), filename)
try:
os.remove(file_path)
print(f"Deleted file: {filename}")
except OSError as error:
print(f"Error deleting file {filename}: {error}")

print("All .txt files in the current directory have been deleted.")

delfile()

12.
import shelve
db = shelve.open("example.db")
db["John Doe"] = {"department": "Engineering", "salary": 50000}
db["Jane Smith"] = {"department": "Marketing", "salary": 45000}
db.close()
db = shelve.open("example.db")
for name, data in db.items():
print(f"Name: {name}")
print(f"Department: {data['department']}")
print(f"Salary: ${data['salary']}")
db.close()

You might also like