r/pythonhelp • • Apr 16 '21

HOMEWORK Python Password Generator Program

Hello everyone! I am currently creating a randomly generated password program for a school project. I am wanting to make it so that if you answer the question “What should the length of the password be?” with something besides an integer, it will display and error message and then ask you the question again. Does anyone have any tips on how I can start to set this up? Thank you!

I have the link to my GitHub which has the code right here: https://github.com/snowiestdaisy56/Python---Password-Generator/blob/657c3ca6fafd6316071e9425c615c955e0f16cc7/main.py

This is my first time ever using GitHub so hopefully I did it correct!

4 Upvotes

2 comments sorted by

1

u/MrPhungx Apr 17 '21 edited Apr 17 '21

I guess you could do something like this:

gotNumber = False
while not gotNumber:
    try:
        length = int(input (...))
        gotNumber = True
    catch Exception as ex:
        print (ex)

1

u/[deleted] Apr 26 '21

A go-to method I use is to keep looping the question continuously until the program gets an integer input, then the program can break out of the loop and continue the code.

The function .isnumeric() can be used on a string to check if a string is made up of numbers or not, and break lets you leave the loops the program is in, they both come in handy here.

# Loop start!
while 1:
    password_length = input('\nWhat should the length of the password be?: ')

    # Check if the input is a string with numbers ini it
    if password_length.isnumeric() == True:
        # If input *does* have numbers in it, turn it into an integer and leave the loop with 'break' :)
        password_length = int(password_length)
        break
    
    # If it doesn't, the loop doesn't get exited so it just continues and asks the question again

rest_of_code_here()