144k views
3 votes
What is wrong with my code? (python)

When entering a input 8 characters long without a "!", the code still accepts it

What is wrong with my code? (python) When entering a input 8 characters long without-example-1

2 Answers

3 votes

Answer:

You can fix this in multiple ways.

1) Use single quotation marks instead of double, this will do the same thing.

'Enter a password with at least 8 characters and a "!" : '

What happened was "" tells the interpreter when a string begins and ends. It looks for those connecting quotation marks.

2) You can use \" to tell the interpreter that this is not the end of a string.

"Enter a password with at least 8 characters and a \"!\" : '

3) Use multiple double quotation marks (can also be used for multi-line strings).

"""Enter a password with at least 8 characters and a "!" : """

User Shadowcursor
by
4.8k points
3 votes

Answer:

password = input("Enter a password with at least 8 characters and a \"!\": ")

if ("!" not in (password) or (len(password) < 8)):

print("Your password does not meet the requirements.")

Step-by-step explanation:

You might notice this is a bit different from your code. Firstly, I added escape characters around the ! and changed it from "!" to \"!\" This is because a backslash "\" is considered an escape character. I'm going to explain this as best I can but I'm not the best at explaining things so bare with me. You see how the ! is white text in your code? That's because your compiler is going to read the code like follows. The phrase "Enter a password with at least 8 characters and a " is going to be seen as a string, then, the ! is going to be read as a function call or some sort of variable, and it will probably error out because it doesn't know what the fk you want to do with it. This can be solved by using escape characters. An escape character tells the compiler, 'hey, I'm going to put a special character here to represent some data, don't stop reading this phrase as a string just yet'. That being said, if you change it to \"!\", then the ! color will turn green, because the compiler is reading it properly (as a string). Also, I change your if statement logic. What you saying to the compiler is " if there is NOT a ! in password AND the password is less than 8 chars long, then its a bad password ". This means that if the password is 9 characters long, and DOESNT have a !, it will still pass. Because you're checking to make sure it fails both before you say "hey this is a bad password". This is a simple fix, you just change it the "and" to "or". And then it will read: "Hey, if their password doesn't have a ! in it OR is less than 8 chars, it's not a good password." Sorry for the wall of text, hopefully it helped you learn something though. :)

User Pehat
by
5.3k points