ethanweed / pythonbook

Python adaptation of Danielle Navarro's Learning Statistics with R (http://learningstatisticswithr.com/). Work in progress!
107 stars 34 forks source link

Issue on page /03.04-basic_programming.html - in the conditional statements section 8.3 #39

Closed Snewski closed 1 month ago

Snewski commented 1 month ago

From the Ask me anything document

Original code, which prints 2 texts for Wednesday:

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for day in week: if day == 'Wednesday': print('Today is', day + '.', 'You need to leave early!') if day == 'Saturday' or day == 'Sunday': print('Today is', day + '.', 'You can sleep late!') else: print('Today is', day + '.', 'You can leave at the normal time today.')

As far as I understand it happens because the if statements are evaluated sequentially, which means that only the if statement related to saturday and sunday is "kept in pythons memory" when it evaluates the else statement, resulting in wednesday being printed with 2 different texts.

Fixed code example 1:

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for day in week: if day == 'Wednesday': print('Today is', day + '.', 'You need to leave early!') if day == 'Saturday' or day == 'Sunday': print('Today is', day + '.', 'You can sleep late!') elif day != 'Wednesday': # (!= basically means not equal to) print('Today is', day + '.', 'You can leave at the normal time today.')

Fixed code example 2:

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for day in week: if day == 'Wednesday': print('Today is', day + '.', 'You need to leave early!') elif day == 'Saturday' or day == 'Sunday': print('Today is', day + '.', 'You can sleep late!') else: print('Today is', day + '.', 'You can leave at the normal time today.')

I find the 2nd example a bit easier to understand, and it uses all 3 types of conditional statements.

ethanweed commented 1 month ago

Thanks, fixed with option 2 👍