KEMBAR78
All Q1 To Q7 Python Answers | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
13 views3 pages

All Q1 To Q7 Python Answers

Uploaded by

MAYANK DEORE
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)
13 views3 pages

All Q1 To Q7 Python Answers

Uploaded by

MAYANK DEORE
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/ 3

Q1 - Python Programs

A. Compute n+n*n+n*n*n without using if-else


n = int(input("Enter a number: "))
result = n + n*n + n*n*n
print("Result:", result)

B. Palindrome check without if-else


s = input("Enter string: ")
print("Palindrome" if s == s[::-1] else "Not Palindrome")

C. sum_all() with variable arguments


def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3))
print(sum_all(5, 10))

D. Extract company name from email


email = "john@google.com"
company = email.split("@")[1].split(".")[0]
print("Company:", company)

Q2 - Exchange Variables Menu


print("1. Using Comma
2. Without 3rd variable
3. Using XOR")
choice = int(input("Enter choice: "))
a = int(input("Enter a: "))
b = int(input("Enter b: "))

if choice == 1:
a, b = b, a
elif choice == 2:
a = a + b
b = a - b
a = a - b
elif choice == 3:
a = a ^ b
b = a ^ b
a = a ^ b

print("After swap: a =", a, "b =", b)

Q3 - List and Class


# List operations
lst = [24, 5, 36, 8, 9, 31, 12]
lst.insert(6, 17)
lst.reverse()
lst.extend([20, 30, 40])
print("Length:", len(lst))
print("Final List:", lst)

# Class with ticket info


class TicketBooking:
def __init__(self, ticket_no, name, fare):
self.ticket_no = ticket_no
self.name = name
self.fare = fare
def show(self):
print(f"{self.ticket_no}, {self.name}, {self.fare}")

people = [TicketBooking(101, "Alice", 500), TicketBooking(102, "Bob", 450)]


for p in people:
p.show()

Q3 - SQLite Student Info


import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE Student_Info (Stude_no INT, Student_name TEXT, SGPA REAL)")
cur.executemany("INSERT INTO Student_Info VALUES (?, ?, ?)", [
(123, "Ajay", 3.1), (223, "Akshay", 3.6), (323, "Govinda", 2.9)])
cur.execute("UPDATE Student_Info SET SGPA=3.5 WHERE Stude_no=323")
print("All records:", cur.execute("SELECT * FROM Student_Info").fetchall())
print("SGPA >= 3.2:", cur.execute("SELECT * FROM Student_Info WHERE SGPA >= 3.2").fetchall())
conn.close()

Q4 - File Word Count


filename = "output.txt"
with open(filename, "w") as f:
while True:
line = input("Enter text (stop to end): ")
if line.lower() == "stop":
break
f.write(line + "\n")

with open(filename, "r") as f:


words = f.read().split()
t_words = [w for w in words if w.lower().startswith("t")]
print("Words starting with t:", t_words)

Q5 - Inheritance, Dictionary
class Student:
def __init__(self, sapid): self.sapid = sapid
def whom(self): print(f"My SAP ID is {self.sapid}")

class AIDS(Student):
def __init__(self, sapid, year):
super().__init__(sapid)
self.year = year
def whom(self):
print(f"AIDS student, year {self.year}"); super().whom()

v1 = Student("2343"); v1.whom()
b1 = AIDS("2562", "2"); b1.whom()
students = {}
for i in range(2):
r = input("Roll: "); n = input("Name: "); c = float(input("CGPA: ")); d = input("Dept: ")
students[r] = [n, c, d]
dept = input("Enter dept: ")
for k,v in students.items():
if v[2] == dept: print(k, v)

Q6 - Array, Square Roots, Reverse Text


import numpy as np
arr = np.arange(1, 25).reshape(4, 6)
print("Size:", arr.size, "Sum:", arr.sum(), "Max:", arr.max())

import math
nums = [1.35, 6.09]
print(list(map(lambda x: round(math.sqrt(x), 3), nums)))

text = open("Story.txt").read()[::-1]
words = text.split()
print([w for w in words if w.lower().startswith("t")])

Q7 - Pandas and Product of Digits


import pandas as pd
Emp_Dict = {
"Empid": ["E001", "E002", "E003", "E004", "E005"],
"EmpName": ["Raj", "Vivek", "Rohan", "Neha", "Kristina"],
"Department": ["Marketing", "Sales", "HR", "Sales", "Finance"],
"Salary": [25000, 35000, 55000, 65000, 45000]
}
df = pd.DataFrame(Emp_Dict)
print(df.describe())
print(df[["Empid", "EmpName", "Department"]].head(3))
print(df.iloc[:-2]) # last 2 rows removed
print(df.iloc[:, :2]) # last 2 columns removed

def find_product(n):
p = 1
for d in str(n):
p *= int(d)
return p

n = 123
print("Product of digits:", find_product(n))

You might also like