1. Home
  2. Docs
  3. Learn Python By Examples
  4. Learn Python by examples – Ex-06-10

Learn Python by examples – Ex-06-10

Learn Python by examples – Ex-06-10

 
Note there are multiple ways to solve a problem.
Here is one solution.
 

Exercise 6: Write a program to print number 1 to 10
 

Solution:
 

Concept:
Use of while loop, increment of value inside loop, augmented assignment,

print() with end= ‘ ‘, argument.

 

#option 1:

#not a scale able option
 
print(1,2,3,4,5,6,7,8,9,10)

#option 2:

#while loop and variable increment, we don't have ++, --

num = 1 

while num < 11:

    print (num, end=' ')

    num = num + 1

    #num += 1

Output:

1 2 3 4 5 6 7 8 9 10 

 
 

Exercise 7: Write a program to print odd number between 20 to 50
 
Concept:

Solving using while loop, with for loop and range() built-in function.

 
Solution:
 

#option 1: using while loop

#while loop and variable increment, we don't have ++, --

num = 21

while num < 50:

    print(num, end=' ')

    #num = num + 2

    num += 2

Output:

21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 

#option 2:

#using for loop and range() built-in function


for num in range(21,50, 2):

    print(num, end =' ')


Output:

21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 


 
 
Exercise 8: Write a program to print even numbers between 50 to 20. i.e in reverse order
 
Solution:

 
Concept:
for loop and range() function with negative step
 


#for loop with range(start,end,step) -ve step , 1st form

for num in range(50,20, -2):

    print(num, end=' ')

Output:

50 48 46 44 42 40 38 36 34 32 30 28 26 24 22 

 
 

Exercise 9: Write a program to print all the characters in a given string “justlearnpython”
 
Solution:

 
Concept:

second form of for loop, without range() iterating through sequence.
 


#second form of for loop

for c in "justlearnpython":

    print(c, end=' ')

Output:

j u s t l e a r n p y t h o n 

 
 

Exercise 10: Write a program to print the Fibonacci series up to 50,

Ex: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

 
Solution:

 
Concept:
Parallel assignment.
 

#parallel assignment 

a,b = 0 , 1

while a < 50:

    print(a, end=' ')

    a, b = b, a + b


Output:

0 1 1 2 3 5 8 13 21 34