How to use tally from loop outside of that loop - python

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.

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

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

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)

Related

How to understand this loop program in Python

I'm trying to polish my Python skills and this made me confused. Here's the code:
greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')
I don't understand what the count does.
this exact code doubles letters which position number is even.
count is for counting letter position.
condition count % 2 == 0 to know which position is divided by 2 without leftovers (check if position is even number)
Let's comment up the code with explanations of what each line does and then examine the output.
# assign the string 'Hello!' to the name greeting
greeting = 'Hello!'
# assign the number 0 to the name count
count = 0
# assign letter to each character in greeting one at a time.
# in the first run of the loop, letter would be 'H', then 'e',
# etc.
for letter in greeting:
# add one to count. count starts at 0, so after this line
# on the first run of the loop, it becomes 1, then 2, etc.
count += 1
# use the modulo operator (%) to get the remainder after
# dividing count by 2, and compare the result to 0. this
# is a standard way of determining if a number is even.
# the condition will evaluate to True at 0, 2, 4, etc.
if count % 2 == 0:
# when count is even, print letter once followed by a
# new line. note that to not print a new line, you can
# write print(letter, end="")
print(letter)
# print letter once followed by a new line regardless of the
# value of count
print(letter)
# print 'done' followed by a new line
print('done')
So, based on all that, what should we expect the output to be? Well, we know that every character of greeting will be printed in the last line of the loop. We also know that every even character of greeting will be printed twice, once inside the if block, and once at the end of the loop. Finally, we know that "done" will be printed after the loop is complete. Therefore, we should expect the following output:
H
e
e
l
l
l
o
!
!
done
This this is very simple see:
greeting = 'Hello!'
In this line you assigned the variable greeting a string value Hello!.
count = 0
In this line you assigned the variable count a integer value 0.
Now the next code is:
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
As you may know strings are iterable. See this code before understanding the above:
for letter in greeting:
print(letter)
Forget the count. At each iteration of the loop the loop is printing every character of the greeting.
so the output is:
H
e
l
l
o
!
But why there a newline after each letter. The answer is that print has an optional argument end If the above code is like this:
for letter in greeting:
print(letter, end = '')
Then the output will be:
Hello!
Now there comes the count term. It is also simple. when the count is even it prints the letter iterating at that time in loop twice due to twice print statement. And the count is even or not is checked by if count % 2 == 0.

How do I insert multiple inputs via a variable/defined term and get multiple outputs with a code? (Python)

I'm trying to make my basic syllable counter run through multiple words, but I do not know how to do so without error. In the code below, I made a placeholder variable containing two words for the code to count syllables of. However, the code ends up not functioning and creates no output. Anyone know what to do?
new_variable = "WORD", "AGAIN"
def syllable_count(word):
word = word.lower()
count = 0
vowels = "aeiouy"
if word[0] in vowels:
count += 1
for index in range(1, len(word)):
if word[index] in vowels and word[index - 1] not in vowels:
count += 1
if word.endswith("e"):
count -= 1
if word.endswith("le"):
count += 1
if word.endswith("ia"):
count += 1
if count == 0:
count += 1
if word.endswith("management"):
count -= 1
if word.endswith("announcement"):
count -= 1
return count
print(syllable_count(new_variable))
As #TimRoberts mentioned in the comments. You are passing a tuple instead of a string to your syllable_counter function.
All you need to do is iterate through the tuple i.e. new_varieble and then call your syllable_counter for each value.
Just remove your last line and write these two:
for word in new_variable:
print(syllable_counter(word))
new_variable = "WORD", "AGAIN"
print(new_variable)
('WORD', 'AGAIN')
You could try to iterate through the list of new_variable instead, for example:
for new_variable in ["WORD", "AGAIN"]:
print(syllable_count(new_variable))

I have to code a linear search but my code doesn't seem to work

I need to write a code that does a linear search on a character within a string. I have to do it without using any inbuilt functions.
The program should output the index of the found character.
If the character isn't in the sentence it should output -1.
I have tried writing the code but it inputs the sentence and character but then doesn't work.
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
count = count + 1
found = True
break
return found
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
if character_found:
print("The character is", count, "on the index")
else:
print("The character is -1")
You probably want this:
def linear_search(intList, target):
count = 0
while count < len(intList):
if intList[count] == target:
return count
else:
count += 1
return -1
Problems with your code:
If the value at the current index is equal to target, then you've found it! You can just return count. If not, then you want to increase count. Currently, your code does the opposite.
Your code returns found, which means that it will only ever return True or False. There is actually no need for a found variable, since you can break out of the function by returning, but in any case you should be returning count.
Outside the function, you attempt to refer to count. That won't work, because count is a local variable: a new instance of count is created for every time you run the function, and destroyed after the function returns. Incidentally, this is another reason you should be returning count, not found: you can just check if count == -1.
You are getting stuck in an infinite loop, because you only update the count variable after the solution is found.
Proper implementation of the while loop:
def linear_search(intList, target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
found = True
break
count = count + 1
I also suggest using a for-loop instead of a while-loop to prevent this mistake:
def linear_search(intList, target):
found = False
count = 0
for i in range(len(intList)):
if intList[i] == target:
found = True
count = i
break
return found
I also noticed some other mistakes, but since they aren't a part of your question I will let you try and solve those yourself first.

Loop Issue with Local Variable

I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count

Count letters in a word in python debug

I am trying to count the number of times 'e' appears in a word.
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
It seems to work fine except when the word ends with an 'e'. It will count that 'e' twice. I have no idea why. Any help?
I know my code may be sloppy, I'm a beginner! I'm just trying to figure out the logic behind what's happening.
>>> word = 'eeeooooohoooooeee'
>>> word.count('e')
6
Why not this?
As others mention, you can implement the test with a simple word.count('e'). Unless you're doing this as a simple exercise, this is far better than trying to reinvent the wheel.
The problem with your code is that it counts the last character twice because you are testing index -1 at the end, which in Python returns the last character in the string. Fix it by changing while letters >= 0 to while letters > 0.
There are other ways you can tidy up your code (assuming this is an exercise in learning):
Python provides a nice way of iterating over a string using a for loop. This is far more concise and easier to read than using a while loop and maintaining your own counter variable. As you've already seen here, adding complexity results in bugs. Keep it simple.
Most languages provide a += operator, which for integers adds the amount to a variable. It's more concise than count = count + 1.
Use a parameter to define which character you're counting to make it more flexible. Define a default argument for using char='e' in the parameter list when you have an obvious default.
Choose a more appropriate name for the function. The name has_no_e() makes the reader think the code checks to see if the code has no e, but what it actually does is counts the occurrences of e.
Putting this all together we get:
def count_letter(word, char='e'):
count = 0
for c in word:
if c == char:
count += 1
return count
Some tests:
>>> count_letter('tee')
2
>>> count_letter('tee', 't')
1
>>> count_letter('tee', 'f')
0
>>> count_letter('wh' + 'e'*100)
100
Why not simply
def has_no_e(word):
return sum(1 for letter in word if letter=="e")
The problem is that the last value of 'letters' in your iteration is '0', and when this happens you look at:
word[letters-1]
meaning, you look at word[-1], which in python means "last letter of the word".
so you're actually counting correctly, and adding a "bonus" one if the last letter is 'e'.
It will count it twice when ending with an e because you decrement letters one time too many (because you loop while letters >= 0 and you should be looping while letters > 0). When letters reaches zero you check word[letters-1] == word[-1] which corresponds to the last character in the word.
Many of these suggested solutions will work fine.
Know that, in Python, list[-1] will return the last element of the list.
So, in your original code, when you were referencing word[letters-1] in a while loop constrained by letters >= 0, you would count the 'e' on the end of the word twice (once when letters was the length-1 and a second time when letters was 0).
For example, if my word was "Pete" your code trace would look like this (if you printed out word[letter] each loop.
e (for word[3])
t (for word[2])
e (for word[1])
P (for word[0])
e (for word[-1])
Hope this helps to clear things up and to reveal an interesting little quirk about Python.
#marcog makes some excellent points;
in the meantime, you can do simple debugging by inserting print statements -
def has_no_e(word):
letters = len(word)
count = 0
while letters >= 0:
ch = word[letters-1] # what is it looking at?
if ch == 'e':
count = count + 1
print('{0} <-'.format(ch))
else:
print('{0}'.format(ch))
letters = letters - 1
print count
then
has_no_e('tease')
returns
e <-
s
a
e <-
t
e <-
3
from which you can see that
you are going through the string in reverse order
it is correctly recognizing e's
you are 'wrapping around' to the end of the string - hence the extra e if your string ends in one
If what you really want is 'has_no_e' then the following may be more appropriate than counting 'e's and then later checking for zero,
def has_no_e(word):
return 'e' not in word
>>> has_no_e('Adrian')
True
>>> has_no_e('test')
False
>>> has_no_e('NYSE')
True
If you want to check there are no 'E's either,
def has_no_e(word):
return 'e' not in word.lower()
>>> has_no_e('NYSE')
False
You don't have to use a while-loop. Strings can be used for-loops in Python.
def has_no_e(word):
count = 0
for letter in word:
if letter == "e":
count += 1
print count
or something simpler:
def has_no_e(word):
return sum(1 for letter in word if letter=="e")

Categories