12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7Iteration7.1 MultipleassignmentAs you may have discovered, it is legal to make more than one assignment to the same variable. Anewassignmentmakesanexistingvariablerefertoanewvalue(andstopreferringtotheoldvalue).bruce = 5print bruce,bruce = 7print bruceThe output of this program is 5 7, because the first time bruce is printed, its value is 5, and thesecond time, its value is 7. The comma at the end of the first print statement suppresses thenewline, which iswhy both outputs appear on thesame line.Here iswhat multipleassignment looks likeinastatediagram:bruce57With multiple assignment it is especially important to distinguish between an assignment operationandastatementofequality. Because<strong>Python</strong>usestheequalsign(=)forassignment,itistemptingtointerpret astatement likea = bas a statement of equality. Itisnot!First, equality is a symmetric relation and assignment is not. For example, in mathematics, if a=7then 7=a. But in<strong>Python</strong>, thestatementa = 7islegal and7 = aisnot.Furthermore, in mathematics, a statement of equality is either true or false, for all time. If a = bnow, then a will always equal b. In <strong>Python</strong>, an assignment statement can make two variables equal,but they don’t have tostaythat way:a = 5b = aa = 3# a and b are now equal# a and b are no longer equal

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

Saved successfully!

Ooh no, something went wrong!