Enrollments started for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 5 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
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")
print(a)
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,
True
or False
True
, execute the indented statements after the while
and then again check the conditionFalse
, the flow gets out of the loop and proceeds further in the programThis 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.
sum_func
that takes one argument.-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
.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.int
, return -1
.Sample Input:
sum_func(10)
sum_func(-1)
sum_func('abcd')
Sample Output:
55
-1
-1
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
Note - Having trouble with the assessment engine? Follow the steps listed here
Loading comments...