WHAT IS WHILE STATEMENT AND AUGMENTED ASSIGNMENTS AND HOW TO USE IN PYTHON PROGRAMMING

WHILE STATEMENT

The while statement allows you to repeat one or more actions while a condition remains True. Let’s use a while statement to find the first power of 3 larger than 50:

In [1]: product = 3
In [2]: while product <= 50:
...: product = product * 3
...:
In [3]: product
Out[3]: 81

Something in the while statement’s suite must change product’s value, so the condition eventually becomes False. Otherwise, an infinite loop occurs. In applications executed from a Terminal, Anaconda Command Prompt or shell, type Ctrl + c or control + c to terminate an infinite loop. IDEs typically have a toolbar button or menu option for stopping a program’s execution.
Snippet [3] evaluates product to see its value, 81, which is the first power of 3 larger than 50.

AUGMENTED ASSIGNMENTS

Augmented assignments abbreviate assignment expressions in which the same variable name appears on the left and right of the assignment’s =, as total does in:

for number in [1, 2, 3, 4, 5]:
total = total + number

Snippet [2] reimplements this using an addition augmented assignment (+=) statement:

In [1]: total = 0
In [2]: for number in [1, 2, 3, 4, 5]:
...: total += number # add number to total
...:
In [3]: total
Out[3]: 15

The += expression in snippet [2] first adds number’s value to the current total, then stores the new value in total.

*

إرسال تعليق (0)
أحدث أقدم