import sys
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
else:
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
sys.exit()
print("Access granted")
Is this the proper flowchart for this code? I'm trying to understand how to properly draw flowcharts with for loops. I'm teaching myself through 'Automate the Boring Things in Python'
Your program looks quite well following your flowchart, However, to complete it without having to explicitly invoking the exit() function and END the flow at the end of the module, consider introducing a new flag, I called mine bol_access_denied. Really, it could be called by any name:
import sys
bol_access_denied = False # You will need to introduce a flag before you enter your while...loop.
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
# else: # This else can be omitted since program flows here ONLY when username == joe
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
bol_access_denied = True # set the flag here.
# sys.exit() This can be replaced by 'break', then backed by [see STEP Final-Check]
if bol_access_denied: # Test the flag here.
break
if access: # STEP Final-Check, is to navigate the user to a personalized section of your program.
print("Access granted")
# Your program ends here naturally without explicitly invoking the exit function.
Hope it helps.
Related
I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue
Alright so here's the code
def user_password():
input('Please Enter Password: ')
#profiles
def intercept():
user_password()
if user_password == "intercept":
print("this is working so far")
else:
print("Incorect Password")
def Jimmy():
user_password()
if user_password == "Jimmy":
print("this is working so far")
else:
print("Incorect Password")
def Tommy():
user_password()
if user_password == "Tommy":
print("this is working so far")
else:
print("Incorect Password")
#login
user_functions = dict(
intercept=intercept,
Jimmy=Jimmy,
Tommy=Tommy,
# ...
)
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
PROBLEMS:
My code always starts with asking for the password even though I don't want it
to.
When I change the first variable to a function it fixes this
Why does it execute when I'm just setting the variable. I'm pretty sure I shouldn't have to use a function instead of a variable
No matter what it always ends up as Incorrect Password even if I give the correct password
I think you are trying to write something like that:
def get_user_password():
return input('Please Enter Password: ')
def Jimmy():
user_password = get_user_password()
if user_password == "Jimmy":
print("this is working so far")
So I'm trying to write a program that can create an account, by creating a .txt file that's the usernames, and then hashes the password with md5 and puts it in the file. However, whenever I run
hashlib.md5(pasw.encode)
it produces bizarrely inconsistent results, that vary whether it encodes it in a function or not, and last time I tested it seemed to produce a random hash the first time ran. Now, when testing in a new project it sometimes produces the same hash for different strings. I've tried everything I could think of and I've got nothing. You can see some of the things I've tried to do.
Thanks in advance for the help, sorry if my code looks horrible I'm doing this project to learn. Here's the full code, sorry if some is irrelevant:
import hashlib
# Creates an account
def create():
print('Create an account')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
f = open(usef,'w')
# hash'd it
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f.write(hash_object)
f.close()
# Logs into a pre-existing account
def login():
print('Welcome! To log in:')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
# Comparative hash
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f = open(usef,'r')
# Checks to see if it's right
if hash_object == f:
print('Welcome, '+user+'!')
return(user)
else:
print('User/password not found')
return(0)
# Changes a password for a user
def change(user):
while True:
pasw = input('Please enter your current password: ')
usef = user+'.txt'
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f = open(usef,'r')
if hash_object == f:
pasw = input('Please enter your new password: ')
past = input('Please repeat your new password: ')
while True:
if pasw == past:
usef = p+'.txt'
f = open(usef,'w')
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f.write(hash_object)
f.close()
print('Done!')
return()
else:
print('They aren\'t the same')
pass
else:
print('That doesn\'t match the password on the system')
# Help with commands
def halp():
print('You can type "Create" to create an account')
print('You can type "Login" to log into a pre-existing account')
print('More functionality will be added')
print('Maybe')
# =============== Main Body of Code ==================
while True:
print('What do you want to do?')
print('Type "Help" for commands')
x = input()
x = x.upper()
if x == 'CREATE':
create()
elif x == 'LOGIN':
p = login()
if p != 0:
while True:
print('What would you like to do now?')
print('"Logout" to log out')
print('or "Change password"')
print('I think you can guess that')
x = input()
x = x.upper()
if x == 'CHANGE PASSWORD':
change(p)
elif x == 'HELP':
halp()
elif x == 'DEV':
y = input()
print(str(hashlib.md5(y.encode())))
# This doesn't help but I tried
print(str(hashlib.md5(y.encode())))
else:
print("Command not found")
print("There are four commands")
print("It's not that hard")
edit: Oh, I understand now. Thanks for the help!
I have tried to create an app in Python that makes a user create a password and then makes them verify it. Obviously I had to create a loop so that when the user entered an unmatching password they had to try again. I am not very experienced with loops so here is what I got. How do I make this work?
here is the code:
password = raw_input ("Create a password: ")
passwordv = raw_input ("Retype your password: ")
a = ("Passwords don't match! Please try again!: ")
b = ("Congrats, you have created a password")
def password():
if password == passwordv :
print ("Congrats, you have created a password")
else :
print (a)
return password
return passwordv
while password !=passwordv:
print (a)
here is another set of code trying to do the same thing:
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again: ')
if (password == passwordv) :
print ('Password set')
break
Your conditional to test whether the passwords match was included in the loop which checks that they don't match -- so, it never gets run.
Try this instead:
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again. ')
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
continue
print ('Password set')
Note how only the code that should be run if the passwords don't match is included within the while loop.
What you need here is an "N and a half times loop". To avoid repeating code (guided by the DRY principle) you might consider writing a function to get the passwords. The following might work:
def get_passwords():
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
return password, passwordv
pw1, pw2 = get_passwords()
while pw1 != pw2:
print "Sorry, passwords do not match"
pw1, pw2 = get_passwords()
The loop won't be entered at all if the original passwords match. Otherwise it will repeat until they do.
password=raw_input('Enter password: \t\t\t')
passwordv=raw_input('Enter password again to verify: \t')
if password == passwordv:
print "\ncongratz you have created password"
else:
print "\nPlease try again...!"
while password != passwordv:
password=raw_input("Enter password: \t\t\t")
passwordv=raw_input("Enter password again to verify: \t")
if password == passwordv:
print"\ncongratz you have created password"
else:
print"\nPlease try again...!"
I know this one is long, It is just for basic understanding
The other answers provide the code that will do what you want. I thought that it could be interesting to tell you a little bit more what was wrong with the code you provided because the problem is more about your understanding of how things work.
1st attempt: a variable and a function have the same name
# Here you define your password variable as a string
password = raw_input ("Create a password: ")
[...]
# And then you reassign it here: it contains now the address of that function!
def password():
[...]
# Now you're comparing a function to a string: they'll never be equal
while password !=passwordv:
[...]
This could have been avoided simply by changing the name of your function (which is never called by the way so I'm not sure what you wanted to do but I thought you might find that interesting). Further reading: Python: function and variable with same name
2nd attempt: the values of the variables stay the same
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
# At this point, if the test is true, you'll reach the end of the code without
# displaying the 'Password set' message you wanted
while (password != passwordv):
# This only prints a message
print raw_input('Passwords do not match, try again: ')
# The condition below can never be true: you just tested that they were
# different but did nothing to give them new values!
if (password == passwordv) :
print ('Password set')
break
The way to fix that is what the other answers provide: take your message out of the loop (getting out of the loop means that your condition was met) ; make sure that you do something inside the loop that will assure that the next test will be different from the previous one (otherwise, you will end up testing the same values over and over again) ; to avoid breaking inside the loop, set your values outside the loop, and then get new values inside the loop in case the initial test failed.
Here's an idea:
First define these:
MinPass = 6
MaxPass = 12
Then this:
print ("Now, lets try with a password. Please enter one here")
EnteredPassword = input("Password: ")
while len(EnteredPassword) < MinPass:
print ("That password is too small. Please try again")
EnteredPassword = input("Password: ")
while len(EnteredPassword) > MaxPass:
print ("That password is too long, please try again")
EnteredPassword = input("Password: ")
Hope this helps!
I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")
Seems like you just want
users[createUser] = createPassword