Add conditionals
The while loop that corrects the offset is a good start, but what if offset is negative? You can try to run the sample code on the right where offset is initialized to -6, but your sessions will be disconnected. The while loop will never stop running, because offset will be further decreased on every run. offset != 0 will never become False and the while loop continues forever.
Fix things by putting an if-else statement inside the while loop.
This exercise is part of the course
Intermediate Python for Data Science
Exercise instructions
- Inside the
whileloop, replaceoffset = offset - 1by anif-elsestatement:- If
offset > 0, you should decreaseoffsetby 1. - Else, you should increase
offsetby 1.
- If
- If you've coded things correctly, hitting Submit Answer should work this time.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Initialize offset
offset = -6
# Code the while loop
while offset != 0 :
print("correcting...")
offset = offset - 1
print(offset)