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

Python Py

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)
5 views6 pages

Python Py

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

# Week - Basic Python Programs (Q&A Format)

# Q1. Write a program to print the triangle using a for loop.


for i in range(5, 0, -1):
for j in range(6 - i):
print(i, end=' ')
print()

# Q2. Write a program to check whether the given input is digit, lowercase, uppercase, or
special character.
char = input("Enter a character: ")
if [Link]():
print("It is a digit.")
elif [Link]():
print("It is a lowercase character.")
elif [Link]():
print("It is an uppercase character.")
else:
print("It is a special character.")

# Q3. Write a Python program to print the Fibonacci sequence using a while loop.
n = int(input("Enter number of terms: "))
a, b = 0, 1
count = 0
while count < n:
print(a, end=' ')
a, b = b, a + b
count += 1

# Q4. Write a program to print all prime numbers in a given interval using break.
start = int(input("Enter the start of interval: "))
end = int(input("Enter the end of interval: "))
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num, end=' ')

# Q5. Write a program to convert a list and tuple into arrays.


from array import array
my_list = [1, 2, 3, 4]
list_array = array('i', my_list)
print("List to array:", list_array)
my_tuple = (5, 6, 7, 8)
tuple_array = array('i', my_tuple)
print("Tuple to array:", tuple_array)

# Q6. Write a program to find common values between two arrays.


arr1 = [1, 2, 3, 4]
arr2 = [3, 4, 5, 6]
common = [i for i in arr1 if i in arr2]
print("Common values:", common)

# Q7. Write a function called gcd that returns the greatest common divisor.
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print("GCD is:", gcd(20, 8))

# Q8. Write a function called palindrome that checks if a string is a palindrome.


def palindrome(s):
return s == s[::-1]
print(palindrome("madam"))

# Q9. Write a function called is_sorted that checks if a list is sorted.


def is_sorted(lst):
return lst == sorted(lst)
print(is_sorted([1, 2, 3]))

# Q10. Write a function called has_duplicates that checks for duplicates in a list.
def has_duplicates(lst):
return len(lst) != len(set(lst))
print(has_duplicates([1, 2, 2]))

# Q11. Write a function to remove duplicates from a list.


def remove_duplicates(lst):
return list(set(lst))

# Q12. Add 'I', 'a', and '' to a list.


words = ['hello', 'world']
[Link](['I', 'a', ''])
print(words)

# Q13. Construct a function to invert a dictionary.


def invert_dict(d):
return {v: k for k, v in [Link]()}

# Q14. Add a comma between characters in a word.


word = "Apple"
print(",".join(word))

# Q15. Remove a given word from a string.


sentence = "This is Apple pie and Apple juice."
word_to_remove = "Apple"
print([Link](word_to_remove, ""))

# Q16. Capitalize the first letter of every word without using built-in methods.
def capitalize_words(sentence):
result = ""
word = ""
for ch in sentence + " ":
if ch != " ":
word += ch
else:
if word:
first = word[0].upper()
rest = "".join([Link]() for c in word[1:])
result += first + rest + " "
word = ""
return [Link]()

# Q17. Write a recursive function to generate all binary strings of n-bit length.
def generate_binary(n, s=""):
if n == 0:
print(s)
else:
generate_binary(n-1, s+"0")
generate_binary(n-1, s+"1")
generate_binary(3)

# Q18. Write a Python program that defines and prints a matrix.


matrix = [[1, 2], [3, 4]]
for row in matrix:
print(row)

# Q19. Write a Python program to add two square matrices.


A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print("Matrix Addition:")
for r in result:
print(r)

# Q20. Write a Python program to multiply two square matrices.


result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
val = sum(A[i][k] * B[k][j] for k in range(len(B)))
[Link](val)
[Link](row)
print("Matrix Multiplication:")
for r in result:
print(r)

# Q21. How do you make a module? Provide geometry functions as example.


def area_circle(r): return 3.14 * r * r
def perimeter_square(s): return 4 * s
def area_rectangle(l, w): return l * w

# Q22. Write code for general-purpose exception handling.


try:
a = int(input("Enter number: "))
b = int(input("Enter another number: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
except Exception as e:
print("Other error:", e)
finally:
print("Done.")

# Q23. Write a Python code to merge two given file contents into a third file.
with open('[Link]', 'r') as f1, open('[Link]', 'r') as f2, open('[Link]', 'w') as f3:
[Link]([Link]() + "\n" + [Link]())

# Q24. Write a function to check for given words present in a file.


def find_word_in_file(filename, word):
with open(filename, 'r') as f:
content = [Link]()
print(f"'{word}' found." if word in content else f"'{word}' not found.")
# Q25. Read a text file and find the word with the most number of occurrences.
from collections import Counter
with open('[Link]', 'r') as f:
words = [Link]().split()
common = Counter(words).most_common(1)[0]
print("Most frequent:", common[0], "-", common[1])

# Q26. Write a function to display word, vowel, space, lowercase, and uppercase counts from a
file.
def analyze_file(filename):
vowels = 'aeiouAEIOU'
with open(filename, 'r') as f:
text = [Link]()
print("Words:", len([Link]()))
print("Vowels:", sum(1 for c in text if c in vowels))
print("Spaces:", [Link](' '))
print("Lowercase:", sum(1 for c in text if [Link]()))
print("Uppercase:", sum(1 for c in text if [Link]()))

# Q27. Import numpy, matplotlib, scipy and explore their functionalities.


import numpy as np
import [Link] as plt
from scipy import stats
arr = [Link]([1, 2, 3])
print("Array:", arr)
x = [Link](0, 10, 100)
y = [Link](x)
[Link](x, y)
[Link]("Sine Wave")
[Link]()
data = [1, 2, 3, 4, 5]
print("Mean:", [Link](data))

# Q28. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
print("AND:", 1 & 1)
print("OR:", 1 | 0)
print("NOT:", ~1 & 1)
print("XOR:", 1 ^ 0)

# Q29. Write a program to implement Half Adder, Full Adder, and Parallel Adder.
def half_adder(a, b): return a ^ b, a & b
def full_adder(a, b, c):
s1, c1 = half_adder(a, b)
s2, c2 = half_adder(s1, c)
return s2, c1 | c2
def parallel_adder(A, B):
carry = 0
result = []
for a, b in zip(reversed(A), reversed(B)):
s, carry = full_adder(a, b, carry)
[Link](0, s)
[Link](0, carry)
return result

# Q30. Write a GUI program with labels, text fields, and submit/reset buttons.
import tkinter as tk
def submit():
print("Name:", [Link]())
print("Age:", [Link]())
def reset():
[Link](0, [Link])
[Link](0, [Link])
window = [Link]()
[Link]("Window Wizard")
[Link](window, text="Name:").grid(row=0, column=0)
[Link](window, text="Age:").grid(row=1, column=0)
entry1 = [Link](window)
entry2 = [Link](window)
[Link](row=0, column=1)
[Link](row=1, column=1)
[Link](window, text="Submit", command=submit).grid(row=2, column=0)
[Link](window, text="Reset", command=reset).grid(row=2, column=1)
[Link]()

You might also like