Python Slip 9

0feaed97e2dc49b2a2b9ff86e837f321

Q1. Write a python program to find square of given number using list comprehension.

data=[1,2,3,4,5,6,7]
result = [i*i for i in data]
print(result)

Q2. Write a python program which will find all such numbers which are divisible by 3 and not by 7 within given range m to n.

start_num = int(input("Enter The Start Number (m)"))
end_num = int(input("Enter The End Number (n)"))
cnt = start_num
while cnt <= end_num:
    # if number divisible by 3 and not by y
    if cnt % 3 == 0 and cnt % 7 != 0:
        print(cnt, " is divisible by 3 and not by 7.")
    cnt += 1
Enter The Start Number (m)3
Enter The End Number (n)30
3  is divisible by 3 and not by 7.
6  is divisible by 3 and not by 7.
9  is divisible by 3 and not by 7.
12  is divisible by 3 and not by 7.
15  is divisible by 3 and not by 7.
18  is divisible by 3 and not by 7.
24  is divisible by 3 and not by 7.
27  is divisible by 3 and not by 7.
30  is divisible by 3 and not by 7.

Q2. Write a python program to reverse each word of file and also count total lines.

num_lines=0
with open("test.txt", "r") as f:
    for line in f:
        num_lines += 1
with open("test.txt", "r") as f:
    data = f.read()
    for line in f:
        num_lines += 1
new_data = ""
for word in data.split():
    rev_word = word[::-1]
    new_data += rev_word
    new_data += " "
print(new_data)
print("Number of lines:")
print(num_lines)
luhaR enawanoS rebmevoN yluJ yaM hcraM nuJ laT ksN luhaR tsiD kihsaN luhaR 
Number of lines:
5

0 Comments:

Post a Comment