Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping While Loops

Dominick Chism
Dominick Chism
8,430 Points

Is this good code practice?

I tried to complete the invalid attempts section of this video by using just loops, but I'm unsure if it's good practice or not. I did take an Python course in college and if I remember correctly I could've swore I stumbled across a problem on StackOverflow that said sys.exit() was bad practice. Any help would be appreciated!

password = input("Please enter the super secret password: ")

MASTER_PASSWORD = 'opensesame'
i = 1
while i <= 3:
  while password != MASTER_PASSWORD:
    password = input("Invalid password, try again: ")
    i += 1
    break
if password == 'opensesame':
  print("Welcome")
else: 
  print("Too many invalid password attempts\nTotal invalid attempts: {}".format(i))

1 Answer

Steven Parker
Steven Parker
221,323 Points

The video code segment is intended to prevent execution of some later code (not shown in the video sample) unless the correct password is entered. The use of system.exit() provided a convenient way to control program flow. Remember that the point of the lesson is just to demonstrate loop functionality.

And yes, it's more elegant to control program flow otherwise, and what you have here would do the job providing that the entire rest of the program was placed between the "welcome" message and the following "else".