Page 1 of 2

if Statements in python

PostPosted: Thu Jan 03, 2013 8:54 pm
by Paulsmith94
Hi all could someone tell me whats wrong with this code in python. Im trying to use if statements so that if a name isnt in the predefined list it will print false and ask to re-enter given name to delete, here is my code...please bear with me as im a n00b! :oops:
Code: Select all
names=(['Paul','Tim','Fred'])

def main():
    for i in range(len(names)):
    e=names[i]
        print names
        print
        a = raw_input("Choose name to be deleted:\n")
    if(a==e)
        names.remove(a)
        print "name deleted"
    if(a!=e):
        print "No such name!Please Re-enter!"


Thanks once again!

Added code tags as they are necessary with Python especially. ~fas

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 9:49 pm
by fashizzlepop
You need to double check your indentation.

Are you trying to make it an infinite loop that allows you to select a name to delete until there are none? I'm confused at what exactly you are trying to do.

I would suggest something like this:
Code: Select all
names = ["Ed", "Edd", "Eddy"]
while 1:
  if not names:    # if names is empty.
     exit()            # exit python, use 'break' to escape the while loop if you don't wish to exit the script.
  a = raw_input  ("Enter a name to remove: ")
  if a in names:   # check if a is in names.
    names.remove(a)
  else:
    print a + " not found in names: " + names

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 10:05 pm
by Paulsmith94
Hi thanks for speedy reply.......Yes i want it to loop until ALL names are deleted, but say for instance if you mis-spell the name
or forget to put a capital on the beginning of the name, then it should say "No such name, please re-enter"

Im trying to understand the IF statements better i know its something im missing that probs very simple but as im a n00b to this language i cant figure out.

This error just appeared with your code:

Enter a name to remove: sadsa

Traceback (most recent call last):
File "D:\Users\********\Desktop\example.py", line 9, in <module>
print a + " not found in names: " + names
TypeError: cannot concatenate 'str' and 'list' objects



>>>

-- Thu Jan 03, 2013 10:11 pm --

Ahhh my bad i took the + operator out and works fine now! thanks man! :)

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 10:14 pm
by fashizzlepop
Putting
Code: Select all
+ str(names)
should also work. I tested my code but changed that last print line before posting for clarity and thusly broke it. :P

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 10:26 pm
by Paulsmith94
Thanks once again dude....been stuck on that for 8 hours!!!

Perhaps you can help me on this last thing........ I made a username and password in each tuple. From what ive been told and can make out myself the loop is checking the names fine, but doesnt acknowledge any password for each username, i can log in without entering anything....heres the code:

Code: Select all
Users=[("Paul","password1"),("Ches","password2"),("Chad","password3"),("Krystal","blue")]

def userLogin(Users):
    for i in range(len(Books)):
        a = raw_input("Please enter username:")
        b = raw_input("Please enter password:")
        c,d=Users[i]
        if (a==c)or(b==d):
            print ""
            print "Welcome",a
            print ""
            User()
            break
        else:
            (a!=c)or(b!=d)
            print "either password or username incorrect please try again!"
            userLogin(Users)
            break

Don't forget CODE tags!!! ~fas

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 10:56 pm
by fashizzlepop
I'd suggest using a dictionary (or hash, or associative array, etc) instead of a list of tuples.

Code: Select all
>>> logins = {"Ed":"password1", "Edd":"%jfu93jk(*", "Eddy":"ButteredToast4Evar"}
>>> logins["Ed"]
'password1'


So, then you can do something like this,

Code: Select all
user = raw_input("Enter username: ")
if user not in logins.keys():    # .keys() returns a list of all the keys (aka, first element of each pair, {"key":"value"})
  print "User not found!"
pass = raw_input("Enter password: ")
if pass != logins[user]:
  print "password incorrect!"
else:
  login()

Re: if Statements in python

PostPosted: Thu Jan 03, 2013 11:13 pm
by Paulsmith94
The reason I am Using lists and tuples is because of University. Else I would do differently. However thanks for the code you gave me I will try that more in the morning at the moment its not liking the pass function. :/ thanks for you help man, sorry for such n00bish questions, only been in programming a year to date now, so a long way to go.

-- Thu Jan 03, 2013 11:16 pm --

1)Admin Login
2)User login
Please Select:
2
Enter username: Paul
User not found!
Enter password: password

Traceback (most recent call last):
File "F:\Python\Think python Work\Help\Attempt2.py", line 68, in <module>
login()
File "F:\Python\Think python Work\Help\Attempt2.py", line 12, in login
userLogin(logins)
File "F:\Python\Think python Work\Help\Attempt2.py", line 30, in userLogin
if a!= logins[logins]:
TypeError: unhashable type: 'dict'

This is the error and below is my code what you gave me (modified a little by me):
Code: Select all
logins={"Paul":"password1", "Ches":"Pass", "Krystal":"Blue"}
def userLogin(logins):
   
        user = raw_input("Enter username: ")
        if logins not in logins.keys():
          print "User not found!"
        a=raw_input("Enter password: ")
        if a!= logins[logins]:
          print "password incorrect!"
        else:
          User()

Seriously, start using the CODE tags! It is incredibly important for Python to see the indentation which is not visible without the CODE tags. ~fas

Re: if Statements in python

PostPosted: Fri Jan 04, 2013 1:54 am
by fashizzlepop
PLEASE start using the CODE tags:
Code: Select all
[code][/code]
within your posts!

As for your issues, you have many things wrong with your code. logins[logins] for example. No idea where you got that...

Re: if Statements in python

PostPosted: Fri Jan 04, 2013 5:02 am
by tgoe
fas... somehow you got roped into doing this guy's homework. LOL.

Re: if Statements in python

PostPosted: Fri Jan 04, 2013 6:16 am
by fashizzlepop
Maybe... just giving him some tips. Also, it looks like he's got a good amount of work to go to get this working right...