0

I am trying to write a basic password checking program and whenever the user has used two attempts to entering the correct password I am supposed to print a hint as to how many letters are in their password. Password is the variable that I stored the correct string in.

elif attempts == 1:
        letters = 0 
        for i in password:
            if password[i].isaplha():
                letters = letters + 1
        print('There are',letters,'letters in your password')

My code gives the error

TypeErrorTraceback (most recent call last)
<ipython-input-195-c967c81bda5f> in <module>()
       letters = 0
       for i in password:
---->      if password[i].isaplha():
               letters = letters + 1
TypeError: string indices must be integers

What am I doing wrong?

miradulo
  • 28,857
  • 6
  • 80
  • 93
  • Why do you think there's something wrong with it? Give a [mcve] we can actually test with an input and expected and actual output. – jonrsharpe Feb 26 '17 at 23:43
  • 1
    Possible duplicate of [Letter Count on a string](http://stackoverflow.com/questions/2932511/letter-count-on-a-string) – Renats Stozkovs Feb 26 '17 at 23:49

3 Answers3

3

Two issues here.

  • for i in password is iterating over the actual characters in password and not their indices, so you should be checking i.isalpha().
  • The string method is not isaplha, it is isalpha.

Fixing these while maintaining your current approach,

... 
elif attempts == 1:
    letters = 0 
    for i in password:
        if i.isalpha():
            letters = letters + 1
    print('There are',letters,'letters in your password')

and if you wanted to do so a bit more concisely, you could sum a generator of booleans based on whether each character isalpha or not, using the fact that True is 1 in Python.

... 
elif attempts == 1:
    letters = sum(i.isalpha() for i in password)
    print('There are {0} letters in your password'.format(letters))
miradulo
  • 28,857
  • 6
  • 80
  • 93
0

IsAplha() method return true if you have only alphabetic characters in your string , it does not tell the length of the string, you can do this like print('you have',len(password),'letters in password')

Khan Saab
  • 434
  • 1
  • 8
  • 20
0

You can use regex to achieve this as well.

import re
password = 'hE1Ar'
lett_count = len(re.findall('[A-z]', password))

Update/Correction:

lett_count = len(re.findall('[A-Za-z]', password))
Du D.
  • 5,062
  • 2
  • 29
  • 34