I created a password generator, which creates random passwords out of symbols, numbers and characters. There I have an input, where the user must enter a value and it has to be numeric. So I tried to solve this with elif
. But, even when expected number (int
) is entered, the loop is still stuck at elif
. Here my code:
def PasswordGenerationFunc():
password = None
passwordLength = inputPasswordLength.get()
userName = inputUsername.get()
if len(passwordLength) == 0:
ResultDisplay.configure(text="Length of password is mandatory.", fg="red")
elif type(passwordLength) != int:
ResultDisplay.configure(text="Only digits are allowed." passwordLength, fg="red")
else:
passwordLength = int(passwordLength)
if passwordLength > maxPasswordLength:
ResultDisplay.configure(text="The limit of password length are 20 characters.", fg="red")
else:
if userName != "":
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password for " userName " is:\n" password, fg="white")
else:
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password is: \n" password, fg="white")
In
ResultDisplay.configure(text="Only digits are allowed." passwordLength, fg="red")
I print out passwordLength
to check if wrong values were passed, but was not the case. I am so into the loop, I might ignoring some logic.
Expected behaviour:
- User enters letters, loop stops at
elif
. User enters digits, loop enterselse
condition.
Now:
- User enters digits, loop still stops at
elif
.
CodePudding user response:
First, convert the input to int
.
try:
passwordLength = int(input("Your message "))
except ValueError:
print(f"Input is not a valid integer. Please try again.")
Modify the if conditions for an integer input as follows:
if passwordLength == 0:
pass # your output here
else:
pass # your logic to generate a password
CodePudding user response:
To compare objects and its datatype use isinstance(object, type)
:
isinstance(3, int) ===> True
isinstance(3, str) ===> False