How do I store multiple strings as one variable - python

I have the write a if and else statement for every supposed user using my code in order to make sure they are who they are. I am wondering if there is a more efficient way to do that. What I want the code to look like is line 2 to 7 however currently I have to make it look like line 9 - 14 instead. Is there any way I can make line 2 to 7 work?
I've already tried to separate each user with a separate if and else statement which checks for whether the user exists already and if they get the password that is assigned to that user correct. I've also tried to already use a list function to store multiple different users as one variable so that if the program detects any of those users it moves them onto the next step however once I do that the program refuses to recognize any of the elements of the list as individuals.
For example in line 2 of the code neither of the users are recognized. The user blake is only recognized if I separate it in its own if else block.
user_name = input ("Hello, user please enter your username!")
if user_name == ["Jake", "Bake"]:
Password = input("Please enter your password %s" %user_name)
if Password == ["hello", "notem"]:
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
else:
if user_name == ("Bake"):
Password = input("Please enter your password %s" %user_name)
if Password == ("hell"):
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
Out of line 2 to 7 I expect that I can enter either Jake or even Blake to get the password question. Then once I put the corresponding, and only the corresponding, password then I should be getting a welcome back (which ever username I chose to go with). In reality the program quits on me as soon as I put in any of the usernames because it seems that the program doesn't know how to proceed from the username prompt.

if user_name == ["Jake", "Bake"]:
checks whether user_name equals the list ["Jake", "Bake"].
If you want test check whether the name is in the list, use the keyword in:
if user_name in ["Jake", "Bake"]:

Your problem is that the program checks to see if the username is the list ["Jake", "Bake"] and the password is the list ["hello", "notem"].
The correct code is:
user_name = input ("Hello, user please enter your username!")
if user_name in ["Jake", "Bake"]:
Password = input("Please enter your password %s" %user_name)
if Password in ["hello", "notem"]:
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
else:
if user_name == ("Bake"):
Password = input("Please enter your password %s" %user_name)
if Password == ("hell"):
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
Edit: you forgot to treat the case in which the user name is neither Jake nor Bake.

As pointed out by #DSC earlier:
What you've checked in your if statement is whether or not the input given by the user is a list in itself.
Instead what you should be checking is whether the input given by the user is an object inside the list.
Also, note using dictionary to hold { 'Username' : 'Password' } key:values will be helpful to match the username to the exact user's password, in case of multiple users.
users = {'Jake':'hello','Bake':'notem'}
user_name = input ("Hello, Please enter your username: ")
if user_name in users: #Checks whether user exists
Password = input("Please enter your password %s" %user_name)
if Password == users[user_name]: #Check for that particular user's password.
print("Welcome back %s" %user_name)
else:
print("You are an imposter! Begone!!")
else:
print('Sorry, That username doesn't exist.')
Not the safest way to go about, as it tells the potential attackers what exactly they've gotten wrong (The username/Password), But should do your work.
Also check this, should get you a few more steps ahead.

Supposing that you want to check for the username and password corresponding to that username, python provides structure called dictionary. May this will be helpful to you.
userPass = {"Jake": "Hello", "Bake": 'notem'} #dictonary named userPass, "username": "Password"
user_name = input ("Hello, user please enter your username!")
Password = input("Please enter your password %s" %user_name)
if userPass[user_name] == Password: #userPass[user_name] will return password defined in dictonary
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")

Related

How do I Avoiding Looping back to lines in code?

I am self-teaching myself python and have run into a problem that I can not seem to find a way around.
I have created a piece of code that compares an entered password to one stored in a database.
My code should have two possibilities.
1) If the password is correct.
The user is prompted to enter a new password and then the prompt to enter the password must appear again (This time accepting the new password).
2)If the password is incorrect the user will be prompted to enter the password until the correct password is entered.
In VBS I used to be able to use the GOTO command.
I am not sure if this is available in Python and if it is I would like to avoid using it as it creates a very illogical hard to follow the program.
password = "#123"
entry = input("Please Input The Password:")
if (password == entry):
entry = input("Password correct you may enter a new password.")
else:
entry = input("Password Incorrect, Try again.")
There are various ways you could complete this. Here is a simple way you could achieve it using while loop and break statement.
password = "#123"
while(True):
entry = raw_input("Please Input The Password: ")
if (password == entry):
print("Password correct you may enter a new password.")
break
else:
print("Password Incorrect, Try again.")
Hope it helped.
while password != entry: # Executes until (password == entry), and does not execute if it is met, even for the first time.
print('Sorry, wrong password.')
entry = input('Enter password >') # or other source of data
print('Correct!')
Edit: additional ways you can do this:
while True: # forever loop, but
entry = input('Enter password >') # or other source of data
if password == entry:
print('Correct!') # you can also put this outside of the loop
break # exit the loop no matter what
# do not put code after the break statement, it will not run!
print('Sorry, wrong password') # will execute only if password != entry, break ignores the rest of the code in the loop
Easiest to make a function with a while statement.
password = "#123"
def login():
while True:
answer = input("Please Input The Password:")
if answer == password:
print("Password correct you may enter a new password.")
else:
print("Password Incorrect, Try again.")
break
login()

how do i compare the contents of a text file with that of a set of inputs

so I am trying to create a program that will allow a user to login using a username and password for a school project. however, my teacher (he has allowed me to ask FYI) wants us to think of a way to make it secure.
so my thought process is that I would allow the user to create a login and store the usernames and passwords in a notepad file. to make these secure I decided to use the hash() function so that the username and passwords couldn't be seen even if the text file was accessed. the issue that I am running into is that I can't figure out how to get the program to see the saved hash version of the username and password in the text file and then compare it to the inputs for longing in without printing the hashes and or saving them as variables.
I can't do this however because if I have more than one login saved in the login file I cant save all the hashed logins as one variable.
if anyone can help it would be greatly appreciated
import sys
import time
print ("welcome to this quiz.")
account = input ("first off do you have a account already. please enter yes or no only").lower
if account == no:
account_create = input ("to continue with this quiz you need a password would you like to create a account. please enter yes or no only").lower
if account_create == no:
print (" the program will close in 30 seconds. if you change your mind come back and make an account")
time.sleep(30)
sys.exit
else:
print ("thank you for creating an account")
username = input ("first off you need a username. please enter a username. be carefull once it is chasen it cant be changed")
# need to add a function that searches the login file and compares no username is repeated
password = input ("secondly you need a password. please choose a password. be carefull you can change it later but you will need the current one to do this.")
username = hash(username)
password = hash(password)
file = open("Login.txt","w")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print ("now please login")
else:
login? = input ("would you like to login to the program").lower
if login? == no:
print ("please come back another time")
time.sleep(20)
sys.exit
else:
username_check = input ("please enter your username")
password_check = input ("please enter your username")
username_check = hash(username_check)
password_check = hash(password_check)
file = open("Login.txt","r")
if username_check ==
Load the file as a dictionary mapping usernames (or their hashes) to the hash of the password.
You can iterate through the file and load each line into your dictionary.
However this will be a bit fragile. What if some user want to have a space or comma in their username. A better and easier approach is to use a library to serialize and deserialize the dictionary. The common one used in python would be pickle or if you want the data to still be somewhat human readable json.

Python 2.7 for loop and not printing the right time

Okay so i am writing a simple login system, here is the code
import time
for counter in range(5):
username=str(raw_input("Please enter your username"))
password=str(raw_input("Please enter your password"))
if username =="bros10":
print "",username,"entered"
time.sleep(4)
print "You got the username right"
if password =="brosbros10":
print "You got the password right"
print "Welcome to the system"
break
else:
print "Try again"
And what happens when i run it is that it will print this bit print "",username,"entered" after i have entered the password
Any help appreciated
Move this:
print "",username,"entered"
To before this:
password=str(raw_input("Please enter your password"))
Now your program will ask for a username, repeat the username that is entered (and tell the user they got it right if they entered bros10), then ask for a password, then sleep 4 seconds.
Alternatively, you can place the password= line right before this one
if password =="brosbros10":
if you want it to ask for the password after waiting 4 seconds and repeating the user input.
If I understand you correct you want to print "",username,"entered" before entering a password. Then it should look like:
import time
for counter in range(5):
username=str(raw_input("Please enter your username"))
print "",username,"entered"
if username == "bros10":
print "You got the username right"
password=str(raw_input("Please enter your password"))
time.sleep(4)
if password =="brosbros10":
print "You got the password right"
print "Welcome to the system"
break
print "Try again"

Making a login forum in Python 3 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Checker = 'Incorrect'
name = input('Please Enter Your Name: ')
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
if Checker == 'Incorrect':
exit()
import time
time.sleep(5)
print('Password is Correct')
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
import time
time.sleep(1)
print ("Closing Python...")
import time
time.sleep(5)
input('Press Enter to continue...')
exit()
I need help , the correct password is badger123 but even if I enter the correct password it will print 'password is correct' and then exit but I want it to ignore exit and continue. When the wrong password is entered then the program will print incorrect and will exit. The programs reacts correctly when the incorrect password is entered but not when the correct password is entered. I NEED HELP!
The value of Checker never actually changes, so
if Checker == 'Incorrect':
exit()
always evaluates to True, which means exit() is always called.
One solution is to do the checking in the if statement
import time
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Password is Correct...')
else:
print('Password Incorrect')
exit()
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
time.sleep(1)
print ("Closing Python...")
input('Press Enter to continue...')
First you only need to import a module once (by convention at the top of your file), and not each time you want to use a function.
The problem you describe is impossible with the code you show
Checker = 'Incorrect'
if Checker == 'Incorrect':
exit()
Since you assign 'Incorrect' to Checker and never changes it after that, the rest of your code is not executed, and your program will never print 'password is correct', it will however print 'Checking Password...' when the correct password is entered and then exit because Checker is always the same, it's like doing if 1 == 1:exit()
Why it isn't working
You set value checker to "incorrect"
When the password is found to be correct, nothing is done about it. Nothing notifies the program in any way that the correct password has been entered. You can see in program that all the program does to acknowledge that the password is correct is simply say that it is "checking" and nothing else. 3 lines later the program will find that checker is still "incorrect" because the program, seeing that the password is correct does nothing to change checker so line 9 is inevitably going to happen.
Fix:
Put line 10 with the else statement and remove line 9. So your code will look something like.
password = input('Please enter your password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
exit()
I can suggest an improvement.
password = input('Please enter your password: ')
if not password == 'badger123':
print(Checker)
exit()
print('Checking Password...')
I think this would be the ANSWER to my question! , All I did is I changed the value of Checker. But now when the person gets the password wrong I want the program to automatically Restart . How do I do that?
Checker = 'Incorrect'
name = input('Please Enter Your Name: ')
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
Checker = exit()
if Checker == 'Incorrect':
input(Checker)
import time
time.sleep(5)
print('Password is Correct')
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
import time
time.sleep(1)
print ("Closing Python...")
import time
time.sleep(5)
input('Press Enter to continue...')
exit()

What's going on with my if-else statement? (Python 3.3)

I'm writing conditional statements for a billing program project. It's a bit advanced for a beginner I know but I welcome the challenge. Anyways, I plan on starting the program with asking for username and password. So this is my first coding for the program.
print ("Hello and welcome to Billing Pro, please enter your username and password to access the database.")
username = input ("Enter username:")
if username == "cking" or "doneal" or "mcook":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
password = input ("Enter password:")
if password == "rammstein1" or "theory1" or "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")
Now at first when I ran this code if I had typed in anything other than the three choices for username Python printed out the 'invalid username' line. For some reason now, it's printing out 'valid username' and then going ahead with the password prompt. Also if I input anything other than the choices for passwords it will always read out the 'valid password' prompt.
Also how do I loop the username prompt when the user inputs something other than the three choices? Should I be using a while statement instead of if-else or can a while statement be placed at the end of the if-else statement to trigger the prompting again?
Oh and I know you can't tell because my crappy formatting in the question, but I did use proper indentation on the script itself.
The problem with your boolean expressions themselves is that they're always True.
if a == 'b' or 'c' is like if (True|False) or 'c', and since 'c' is truthy, it's True regardless of the first expression (a == 'b').
You either want a == 'b' and a == 'c'… or the more succinct a in {'b', 'c'…}, which checks if a is a member of the set.
If you want to loop, use a loop :)
while username not in {"cking", "doneal", "mcook"}:
print ("Invalid username. Please try again.")
username = input ("Enter username:")
print ("Valid username.")
You need to compare your name with all names. Problem lies here:
if username == "cking" or "doneal" or "mcook":
Python evaluates first one to either true or false and then doing or with something, that evaluates to True in this context and at the end your comparison looks like this:
if username == "cking" or True or True:
which ends up being True. As suggested, you should use:
if username == "cking" or username == "doneal":
or simply do:
if username in ("cking", "doneal"):
The same applies to password.
I think this code can help you
from sys import argv
username=raw_input("Enter user name")
password=raw_input("Enter password")
if(username=="VARUN" or "Varun" or "varun"):
print "\n\tvalid Username "
else:
print "\n\tUsername already existes"
if (password=="#ppu1131986"):
print "\n\tPasssowrd matched"
else:
print "\n\tWeak Password"
~
print ("Hello, welcome to Facebook, please enter your username and password to access.")
username = input ("Enter username:")
if username == "cking":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
username = input ("Enter username:")
if username == "cking":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
password = input ("Enter password:")
if password == "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")
password = input ("Enter password:")
if password == "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")

Categories

Resources