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.
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.')
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.
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.