Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAaron Elkind
1,393 PointsDifferent response in the video before this.
In the video before this, after several "no" responses the final response had "That was getting repetitive." at the end of it and not just "I'm pleased you understand While loops now.". I've tried to make a code that if no was entered more than 3 times it would print the "That was getting repetitive." response but if it was less that 3 it would print "I'm pleased you understand While loops now.". Is there a more simple way to write my code just using the while loop or would it have to basically be like I wrote it?
name = input('What's your name? ')
answer = input('{}, do you understand Python while loops?\n(Enter yes/no)'.format(name))
attempt_count = 1
while answer.lower() != 'yes':
answer = input('Ok {}, while loops in Python repeat as long as a certain Boolean condition is met.\n{}, now do you understand Python while loops?\n(Enter yes/no)'.format(name, name))
attempt_count += 1
if attempt_count > 3 and answer == 'yes':
print('That's great {}, I'm pleased you understand While loops now. That was getting repetitive.'.format(name))
if attempt_count < 3 and answer == 'yes':
print('That's great {}, I'm pleased you understand While loops now.'.format(name))
print('That's great {}, I'm pleased you understand While loops now.'.format(name))
1 Answer
Steven Parker
231,248 PointsYou don't need to do the testing inside the loop, you can wait until the loop ends. Then, since you know the loop was testing for "yes", you don't need to check that again. So just check the count, and a single test will do since you can use "else" to handle the other case:
name = input('What's your name? ')
answer = input('{}, do you understand Python while loops?\n(Enter yes/no)'.format(name))
# use the loop to just ask the question and update the count
attempt_count = 1
while answer.lower() != 'yes':
answer = input('Ok {}, while loops in Python repeat as long as a certain Boolean condition is met.\n{}, now do you understand Python while loops?\n(Enter yes/no)'.format(name, name))
attempt_count += 1
# after the loop ends, we know the answer was "yes" so check the count to control the response
if attempt_count > 3:
print('That's great {}, I'm pleased you understand While loops now. That was getting repetitive.'.format(name))
else:
print('That's great {}, I'm pleased you understand While loops now.'.format(name))