Foundations of Python

86 / 134

While loop

It is one form of statements used for making iterations in Python. It helps in automating repetitive or similar tasks.

a = 1
while a <= 5:
    a = a + 1
print("a has crossed 5")

This program assigns 1 to the variable a and then iterates to the point when a <= 5 becomes False. So, finally when the value of a becomes 6, the flow comes out of the while and prints the further results, i.e. a has crossed 5 and value of a i.e. 6.

Precisely, the flow of while statement is as follows,

  • Check the condition whether it results in True or False
  • If it is True, execute the indented statements after the while and then again check the condition
  • If at any point of time the condition becomes False, the flow gets out of the loop and proceeds further in the program

This type of flow is called a loop because the last indented step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, "It had five iterations", which means that the body of the loop was executed five times.

The body of the loop should alter the value of one or more variables so that finally the condition becomes False and the loop terminates. We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable. For the above example, the iteration variable is a.

If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop.

  • Define a function with the name sum_func that takes one argument.
  • Return -1 if the argument is not int. Remember that there are various datatypes other than the primitive ones like string, float, and bool. You need to account for those datatypes too. So it is easier to check if it is int rather than checking if it is not an int.
  • If the argument is an int and if it is non-negative, return the sum of all integers from 0 to that argument. You can check if an int is non-negative by check if it is greater than or equal to zero. If it is less than zero than it is negative.
  • In case, the argument passed is negative int, return -1.

Sample Input:

  • sum_func(10)

  • sum_func(-1)

  • sum_func('abcd')

Sample Output:

  • 55

  • -1

  • -1

Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...