06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

62 Iteration<br />

First, equality is commutative and assignment is not. For example, in mathematics,<br />

if a =7then7=a. But in <strong>Python</strong>, the statement a = 7 is legal and 7 = a<br />

is not.<br />

Furthermore, in mathematics, a statement of equality is always true. If a = b<br />

now, then a will always equal b. In <strong>Python</strong>, an assignment statement can make<br />

two variables equal, but they don’t have <strong>to</strong> stay that way:<br />

a = 5<br />

b = a<br />

a = 3<br />

# a and b are now equal<br />

# a and b are no longer equal<br />

The third line changes the value of a but does not change the value of b, sothey<br />

are no longer equal. (In some programming languages, a different symbol is used<br />

for assignment, such as 0:<br />

print n<br />

n = n-1<br />

print "Blas<strong>to</strong>ff!"<br />

Since we removed the recursive call, this function is not recursive.<br />

You can almost read the while statement as if it were English. It means, “While<br />

n is greater than 0, continue displaying the value of n and then reducing the value<br />

of n by 1. When you get <strong>to</strong> 0, display the word Blas<strong>to</strong>ff!”<br />

More formally, here is the flow of execution for a while statement:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!