Understanding a while loop
In the following program, the first line assigns an initial value to i
. The second line defines a condition for? when the while
loop should stop. The last one increases the value of i
by 1
. The i+=1
statement is equivalent to i=i+1
. Similarly, t**=2
should be interpreted as t=t**2
:
i=1 while(i<=4): print(i) i+=1
The key for a while
loop is that an exit condition should be satisfied at least once. Otherwise, we would enter an infinitive loop. For example, if we run the following scripts, we would enter an infinitive loop. When this happens, we can use Ctrl + C to stop it:
i=1 while(i!=2.1): print(i) i+=1
In the previous program, we compare two real numbers for equality. It is not a good idea to use the equals sign for two real/float/double numbers. The next example is related to the famous Fibonacci series: the summation of the previous two numbers is the current one:
The Python code for computing the Fibonacci series is given as follows:
def fib...