1. The 'while' statement
often used to automate repetitive tasks. Repeating identical or similar
tasks without making errors is something that computers do well and
people do poorly
is what countdown looks
like with a while statement:
of the things loops are good for is generating tabular data.
We can test if
'math.log()' is calculating the natural log: we put 'math.e' there as
the natural log constant, and we got all the '1's in the results.
Don't forget to
import the 'math' package if you did do this before.
If you want to
find the log for base 2:
Since we know:
alternative way to get log base 2 is:
This is verified
when x=2, the result is 1.
an index to traverse a set of values is so common that Python provides
an alternative, simpler syntax - the for
To print out all
the letters in 'fruit' one by one, you can use a 'while loop':
Or a 'for loop':
The 'for loop'
in Python has the index running on the back-end.
following program counts the
number of times the letter 'a'
appears in a string:
1. The value of pi can be approximated by:
Wriet a script (must use the 'while loop')
with a user-defined function which asks the user to input the number of
iterations (n), then computes the expression. The larger the number of
iterations, the closer the result should be to pi. Print out the final
result by calling the function. (You may want to force the input into
an 'int' varable)
2. Repeat the task above using the 'for loop' instead of the 'while loop'.