Python password validator - python-3.x

I'm trying to make a basic program that checks if a password meets certain criteria. This isn't returning any errors but gives the 'password verified' message whether there is a special character or not. Any ideas welcome!
import re
begin = str(input("Would you like to check your password strength?"))
while begin.lower() == "yes" or begin.lower() == "y":
password = str(input("Please enter your password"))
if len(password)<8:
print ("Your password needs to be at least 8 characters long")
elif password.isupper() or password.islower():
print ("Please and include at least one upper and one lower case letter in your password")
elif password.isnumeric() or password.isalpha():
print ("Your password should not be numbers only or letters only but should include a mixture of both")
elif re.match("£$%^&*()",password) == True:
print ("Your password should contain at least one special character")
else:
print ("Password verified")

Your use of re.match() is flawed on several counts. Rather get into that, though, I would propose a different tactic:
elif set("£$%^&*()").isdisjoint(password):
This converts your string of special characters into a set of characters, then checks to see if it is disjoint from the password... that is, if it shares no elements with the password. If that is true, then you know that none of your special characters appear in the password and can proceed accordingly.

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

My output only shows wrong even though it is correct [duplicate]

This question already has answers here:
Comparing a string to multiple items in Python [duplicate]
(3 answers)
Closed 2 years ago.
I don't see why it only displays wrong it only displays the last line it worked when it used the username and password in the script?
def login():
for username in range(3):
username = input("Enter your username:")
password = input("Enter your password:")
d="example1"
k="example2"
s="school"
f=open("bob.txt")
lines=f.readlines()
if username == lines[0] and password == lines[1]:
print("welcome to soar valley",d)
break
if username == lines[2] and password ==lines[3]:
print("welcome to soar valley",s)
break
if username == lines[4] and password ==lines[5]:
print("welcome to soar valley",k)
break
if username or password != lines[0] or lines[1] or lines[2]or lines[3]or
lines[4] or lines[5]:
print("wrong try again")
login()
You misused the operator or.
if username or password != lines[0] or lines[1] or lines[2]or lines[3]or
lines[4] or lines[5]:
This line is not executed as what you was expected.
In the Python 3.7 documentation of or,
the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
So, a not-empty string is always interpreted as True, which means your target line can be simplified under the supposed condition (username and password are not empty, and the file "bob.txt" contains at least 6 non-empty lines at the beginning):
if True or True != True or True or True or True or
True or True:
Which become always true. And this is exactly what you don't expected.
For your situation, you may try the keyword not in:
if username not in lines[0:5] and password not in lines[0:5]:
Better to use a dict to make a username-password pair.

running a while loop in python and functions not defined

Hi I have this code below and I want the while loop to keep on getting an input from the user whenever the user enters an empty value or doesn't input any value, the program should keep on prompting the user to enter at least a single character, but the code seems to run even though I don't enter any value, thus an empty string the code still executes the (function) in the code, and also I get error "Function not defined"
word = ""
while True:
if word != "":
def str_analysis(string):
if string.isdigit():
if int(string) > 99:
print (string,"Is a big number")
else:
print(string,"Small number")
elif string.isalpha():
print(string,"Is all alphabetical characters")
else:
print(string,"is multiple character types")
word = input ("Enter a word or integer:")
break
str_analysis(word)
I don't know what you expect to happen. word is equal to "" so the if block won't run, so the function won't get defined. Next, we ask the user for input and after that break the loop. Then you try and call a function that was never defined.
What you wanna do is put a break at the end of the function and get rid of the existing one.

Python How to check if user input is a string?

My first question on here...
I want to know how to check if the user input is a string. If it is not a message should appear. Otherwise the answer should be accepted. Here is what I have (I am looking for the simplest fix please):
try:
name=str(raw_input("What is your name? "))
except:
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")
str.isalpha() checks if all characters in the string are alphabetic and there is at least one character. So
name=str(raw_input("What is your name? "))
if not name.isalpha():
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")
However this will not work if name is "Homer Simpson" (with a space) which is valid input for name.
And don't you forget this!!!
What about an assertion with the check for non ascii letters in the string , similar to here,
import string
try:
name = raw_input("What is your name? ")
assert any([char not in string.ascii_letters for char in name]) is False
except AssertionError:
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")

Resources