-1

This is part of a function used to check that a password is 9 characters long, alphanumeric, and contains at least 1 number. Ideally I should be able to use the first if statement but strangely, it doesn't run. I can't figure out why test1.isalpha runs as 'True' in the if statement but prints as 'False'.

test1 = 'abcd12345'

if len(test1) == 9 and test1.isalnum and not(test1.isalpha)
    print('This should work.')



if len(test1) == 9 and test1.isalnum:
    if (test1.isalpha):
        print('test1 is', test1.isalpha())

>>>('test1 is', False)        

3 Answers3

1

In your if (if (test1.isalpha):) you are testing the method instance and not the result of this method.

You have to use if (test1.isalpha()): (parentheses)

Arount
  • 9,853
  • 1
  • 30
  • 43
0

You have to do if test1.isalpha() instead of if test1.isalpha

test1.isalpha is a method, And test1.isalpha() will return a result True or False. When you check with if condition method will always satisfied. And other one depends on result.

Look the diffidence.

In [13]: if test1.isalpha:
    print 'test'
else:
    print 'in else'
   ....:     
test

In [14]: if test1.isalpha():
    print 'test'
else:
    print 'in else'
   ....:     
in else
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

How about something like this?

  • len(test1)==9 to ensure a length of 9
  • hasNumbers(inputString) function to return char.isdigit() on any digit in the string
  • re.match("^[A-Za-z0-9]*$", test1) to make sure there are only alpha and digit using python re / regular expression

import re test1 = 'abcd12345' def hasNumbers(inputString): return any(char.isdigit() for char in inputString) if re.match("^[A-Za-z0-9]*$", test1) and hasNumbers(test1) and len(test1) == 9: print('Huzzah!')

runningviolent
  • 317
  • 3
  • 13