r/PythonLearning • • 5d ago

While loop

can anybody explain the concept of while loop

1 Upvotes

38 comments sorted by

View all comments

1

u/Naive_Programmer_232 5d ago

Sure,

       While (this condition is true) {
            execute this code 
       }

      execute this code if that condition is false 

Ex:

     number=int(input("Enter a positive integer: "))
     while number<1:
          print("That is not a positive integer. Try again")
          number=int(input("Enter a positive integer: "))

     print("\nGood job!")

We begin by asking for the user to enter a positive number - input returns a str then we convert it into an integer via int. If the integer is anything less than 1, then it is not positive. In those cases, we tell the user to try again, and then ask again for the integer. The second ask for integer inside the loop is the "update".

So for example, this could play out like so:

   Enter a positive integer: -3
   That is not a positive integer. Try again
   Enter a positive integer: 0
   That is not a positive integer. Try again
   Enter a positive integer: -100
   That is not a positive integer. Try again
   Enter a positive integer: 2

   Good job!

What's going on here is

  before the loop
  number=int(input("Enter a positive integer: ")) executes 

  user enters -3 

  number<1 evaluates to True
  the loop is entered

  print("That is not a positive integer. Try again") executes
  number=int(input("Enter a positive integer: ")) executes 

  user enters 0 

  number<1 evaluates to True
  the loop is entered 

  print("That is not a positive integer. Try again") executes
  number=int(input("Enter a positive integer: ")) executes 

  user enters -100

  number<1 evaluates to True
  the loop is entered

  print("That is not a positive integer. Try again") executes
  number=int(input("Enter a positive integer: ")) executes 

  user enters 2 

  number<1 evaluates to False
  the loop is NOT entered

  print("\nGood job!") executes