pearTrack
pearTrack

Reputation: 23

How to use tally from loop outside of that loop

New to coding, sorry if the question is too simple.

I am trying to keep a tally of how many times a character in a certain string range appears. I want to use that tally, count, later and add it to different values, and other tallies. If I return it I can't seem to be able to reuse it. How would I be able to reuse the tally, but outside of the loop?

def function(word):
    letters = 'abcdefgh'
    while count < len(word):
       for i in word:
          if i in letters:
              count += 1
        return count
     a = count + 5
     print(a)
print(function('AaB5a'))

count should be 2, but how do I take it, and add it to other values, like a = count + 5? print(a) does not print 7, or anything.

Upvotes: 2

Views: 567

Answers (3)

hserrano
hserrano

Reputation: 1

I set the count variable to zero because it throws UnboundLocalError: local variable 'count' referenced before assignment. The function will return the count of the string passed in. The count is now returned by the function. You can then assign it to a variable and then add, subtract, etc., to that variable.

def function(word):
    letters = 'abcdefgh'
    count=0
    while count < len(word):
        for i in word:
            if i in letters:
                count += 1
    return count

c=function('AaB5a')
a=c + 5
print(a)

Upvotes: 0

Tacratis
Tacratis

Reputation: 1055

Like most of the comments already covered, you should remove the return to the end, and also the while loop doesn't seem to be required (and in fact, appears to provide a wrong result). Please let me know if this is not what you wanted, and I will correct it based on your input, but it does output 2 and prints 7 as you requested in OP

def function(word):
    count = 0
    letters = 'abcdefgh'
    for i in word:
        if i in letters:
            count += 1
    a = count + 5
    print(a)
    return count

Upvotes: 2

eddyizm
eddyizm

Reputation: 585

First, you should probably not use the word function to name your function. I changed your sample to check_letters You also want to create the variable count outside of the while loop so you can save the incremented count. At the end, return the count.

def check_letters(word):
    letters = 'abcdefgh'
    count = 0
    while count < len(word):
        for i in word:
            if i in letters:
               count += 1
    return count

Once that is done, you can call the function and pass in your paramenter, it will return an int which in this case, you want to add 5. We're then saving the results to the variable

a = check_letters('AaB5a') + 5

print (a)

11

if you print the check letters, you'll get the return count to the output.

print (check_letters('AaB5a'))
6

Upvotes: 0

Related Questions