Python Essentials Classroom Series – 07/Sept/2021

Looping constructs in Python while and for

  • Repeat with While:
    • This is simplest mechanism for looping
    • The syntax is
    while <conditional expression>:
        # code block
    
    • Examples Preview
    • Lets try to write a program which prints all the even numbers between 10 and 50 Preview
    • Lets write a program to find the factors of a given number
      number = int(input('Enter the number: '))
      index = 2
      while index < number:
          if number%index == 0:
              print(index)
          index += 1
    
    
    • Lets modify the above program to print only last 5 factors
      number = int(input('Enter the number: '))
      index = number -1
      factors_found = 0
      while index >= 2:
          if number%index == 0:
              if factors_found < 5:
                  print(index)
                  factors_found += 1
                  if factors_found == 5:
                      break
              
          index -= 1 
    
    
    • Exercise: Write a python program to find out if the number given is prime or not
      number = int(input('Enter the number: '))
      index = 2
      is_prime = True
      while index < number:
          if number%index == 0:
              is_prime = False
              break
          index += 1
    
      if is_prime:
          print(f"{number} is prime")
      else:
          print(f"{number} is not prime")
    
    • Exercise: Extend the program to print all the prime numbers between 10 and 100

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin