Home > Net >  Trying to understand flow control/charting
Trying to understand flow control/charting

Time:06-06

import sys

access = False
while not access:
    username = input('Enter username: ')
    if username.lower() != 'joe':
        print("imposter!")
        continue
    
    else:
        print(f'Hello {username.capitalize()}')
        for i in range(3):
            password = input('Enter password: ')
            if password == 'Water':
                access = True
                break
        else:
            print("3 strikes, you're out")
            sys.exit()

print("Access granted")

My attempt at making a flowchart Is this the proper flowchart for this code? I'm trying to understand how to properly draw flowcharts with for loops. I'm teaching myself through 'Automate the Boring Things in Python'

CodePudding user response:

Your program looks quite well following your flowchart, However, to complete it without having to explicitly invoking the exit() function and END the flow at the end of the module, consider introducing a new flag, I called mine bol_access_denied. Really, it could be called by any name:

import sys

bol_access_denied = False  # You will need to introduce a flag before you enter your while...loop.
access = False
while not access:
    username = input('Enter username: ')
    if username.lower() != 'joe':
        print("imposter!")
        continue
    
    # else:  # This else can be omitted since program flows here ONLY when username == joe 
    print(f'Hello {username.capitalize()}')
    for i in range(3):
        password = input('Enter password: ')
        if password == 'Water':
            access = True
            break
    else:
        print("3 strikes, you're out")
        bol_access_denied = True  # set the flag here.
        # sys.exit()  This can be replaced by 'break', then backed by [see STEP Final-Check]
    if bol_access_denied:  # Test the flag here.
        break

if access:  # STEP Final-Check, is to navigate the user to a personalized section of your program.
    print("Access granted")

# Your program ends here naturally without explicitly invoking the exit function.

Hope it helps.

  • Related