I am making a pretty basic password generator which asks the user for certain things they want in the password (e.g. the user can choose whether or not they want punctuation ). I've completed the program, and it runs perfectly fine, but it includes a section of if and statements:
if p == "N" and ucl == "N" and lcl == "N":
print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
x = lclList
generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
x = uclList
generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
x = uclList lclList
generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
x = pList uclList lclList
generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
x = pList lclList
generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
x = pList uclList
generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
x = pList
generate(x)
As I said, it runs fine, but looks real messy and inefficient - I can already imagine how convoluted it would have to be if I used 4 requirements, and god forbid any more. Is there another way of programming this that would make it repeatable and more efficient?
Side note, this is pretty much the first fully functioning program I've wrote, so don't be shocked if I've broken some programming Geneva convention.
CodePudding user response:
You could initialize x
as an empty list and then, depending on the choices of the user, add the things they want to add to it:
x = []
if lcl == "Y":
x = lclList
if ucl == "Y":
x = uclList
if p == "Y":
x = pList
generate(x)
CodePudding user response:
This is your first fully functioning program, so i will give you some tips:
- Use boolean (True/False) to determine the status of Yes or No (currently a string).
- When you are nesting if statements that are exclusive, use elif.
Your code (corrected) should look like this (assuming p, lcl and ucl are booleans, instead of strings):
# Init empty list.
x = []
# Append elements to your list.
if lcl:
x = lclList
if ucl:
x = uclList
if p:
x = pList
# Check if selections are valid (x won't be an empty list, you can use if statement too) or print error message.
if x:
generate(x)
else:
print("Invalid requirements ")
Hope this helps you to improve your coding!