1

I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"

The code doesn't work, I always get incorrect password.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
Meirshalom
  • 31
  • 3

3 Answers3

1
d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}

user_name = raw_input() #apple
password = raw_input() # red

if user_name in d.keys():
    #check if username: apple == password : red (key=value)
    if password == d.get(user_name) 
        print "great"
    else:
        print "Password incorrect!"
Alpesh Valaki
  • 1,611
  • 1
  • 16
  • 36
0

There're some things that you're doing wrong:

  • you're not calling raw_input() on password
  • you're storing the password in plain-text
  • raw_string() can take a string as parameter so you can get rid off your print statements
  • you're checking if user_name / password are in d but you should actually look for username in key and for password in value. More user_name and password are already defined above the for loop and that makes your for loop completely wrong.

So, a simple solution would be:

d = {'apple': 'red', 'green': 'lettuce', 'yellow': 'lemon', 'orange': 'orange'}

user_name = raw_input("Please enter your username: ")
password = raw_input("Please enter your password: ")

if password == d.get(user_name):
  print True
else:
  print False
0

You will get an error in line : "for user_name,password in d:"

Python ValueError: too many values to unpack

Correct code will be :

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'} 
print "Please enter your username: " 
user_name = raw_input() 
print "Please enter your password: " 
password = raw_input() 
for user,passw in d.iteritems(): 
    if user == user_name and password == passw :
         print "great"
         exit(0)
print "Password incorrect!"
Rohit
  • 13
  • 2