Python3 exercise with solutions (Set 2)

 Problem 1:

To print n odd numbers.

Solution
n=int(input("Enter number:"))
i=0
for i in range(n+1):
    if(i%2!=0):
        print (i)

Output
Enter number:7
1
3
5
7

Problem 2:
To find the sum of digits of the given number.

Solution
n=int(input ("Enter number"))
sum=0
while(n>0):
    d=n%10
    n=n//10
    sum=sum+d
    print (sum)

Output
Enter number:345
12

Problem 3:
To print the given pattern.
1
1 3
1 3 5
1 3 5 7

Solution
n=int(input("Enter number"))
i=0
j=0
for i in range (0,n+1):
   for j in range (0,i+1):
       k=(2*j)+1
       print (k)
   print ("/n")

Output
Enter number:4
1
1 3
1 3 5
1 3 5 7

Problem 4:
To check whether the given number is an amstrong number or not.(eg.153=(1*1*1)+(5*5*5)+(3*3*3)=153

Solution
n=int(input ("Enter number"))
sum=0
x=n
while (n>0):
   d=n%10
   n=n//10
   cube=d*d*d
   sum=sum+cube
   print (sum)
   if(x==sum):
       print ("Amstrong number")
   else:
       print ("Not an amstrong number")

Output
Enter number:153
27
152
153
Amstrong number

Problem 5:
To print the given pattern.
1
1 2
1 2 3
1 2 3 4

Solution
n=int(input ("Enter number"))
for i in range (1,n+1):
    for j in range (1,i+1):
        print (j)
    print ("/n")

Output
Enter number:4
1
1 2
1 2 3
1 2 3 4

Problem 6:
To print Fibonacci series.

Solution
n=int(input ("Enter number"))
i=0
j=1
print (0)
print (1)
for s in range (n)
   s=i+j
   print (s)
   i=j
   j=s

Output
Enter number:10
0
1
1
2
3
5
8

Problem 6:
To find whether the given number is prime or composite.

Solution
n=int(input ("Enter number"))
i=2
k=n%i
for i in range (n):
   x=k
if(x==0):
   print ("composite")
else:
   print ("prime")

Output
Enter number:8
composite

Problem 7:
To print the given pattern.
1
1 0
1 0 1
1 0 1 0
1 0 1 0 1

Solution
n=int(input ("Enter number"))
for i in range (1,n+1):
   for j in range (1,i+1):
      if(j%2==0):
          print(0)
      else:
          print (1)

Output
Enter number:5
1
1 0
1 0 1
1 0 1 0 
1 0 1 0 1

Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution