Oct-04-2021, 11:55 AM
(This post was last modified: Oct-04-2021, 11:58 AM by deanhystad.)
Your strTotal() function doesn't work because you are only passing the last word entered.
Why aren't you using the built-in Python function len()?
You should always close any open files before exiting the program.
Why are you counting characters twice? You count them for each word, then you count all the words a second time to get the total.
Do not use str as an argument name. str is a special Python word. Using it as an argument name prevents your function from using the str() function. It also causes a lot of confusion because you can use type annotation in Python, and str appearing in an argument list usually indicates the argument type. For example, your findLength function could be written like this:
I would write your code like this.
Why aren't you using the built-in Python function len()?
You should always close any open files before exiting the program.
Why are you counting characters twice? You count them for each word, then you count all the words a second time to get the total.
Do not use str as an argument name. str is a special Python word. Using it as an argument name prevents your function from using the str() function. It also causes a lot of confusion because you can use type annotation in Python, and str appearing in an argument list usually indicates the argument type. For example, your findLength function could be written like this:
def findLength(word:str) -> int: '''Return length of word''' return len(word)The annotation says that this function expects one argument that is a str and returns an int value. A good IDE will use this information to provide hints to help you write code that uses this function. Code analysis tools can use the annotation to spot errors where you pass the wrong argument type.
I would write your code like this.
with open("myOutFile.txt", "w") as outF: # Will close file automatically when loop ends total = 0 for _ in range (3): # Get three words scan_input = input("Enter line: ") scan_length = len(scan_input) # Get word length total += scan_length # Get total length so far outF.write(f'{scan_input}\nChar count: {scan_length}\n') print (" ", scan_input, scan_length) print ("How many lines of text: 3") # We know how many. No need to count print (f"How many characters of text (total chars): {total}")