I am trying to create a module and import it into another program. My task for the module is for it to:
- accept a string
- have a docstring explaining what it does
- return the count of how many letters are in the string parameter
I was able to create the module, and I think it should return the correct count, but I am either having trouble implementing it into my original code, or the code in my new module file is wrong as well.
Here is the code from the original file:
# Program for Determining Palindromes
import stack
import letterCount
from letterCount import countLetters
# welcome
print ('This program can determine if a given string is a palindrome\n')
print ('(Enter return to exit)')
# init
char_stack = stack.getStack()
empty_string = ''
# get string from user
chars = input('Enter string to check: ')
while chars != empty_string:
if len(chars) == 1:
print('A one letter word is by definition a palindrome\n')
else:
# init
is_palindrome = True
# determine half of length. excluding any middle character
compare_length = len(chars) // 2
# push second half of input string on stack
for k in range(compare_length, len(chars)):
stack.push(char_stack, chars[k])
# pop chars and compare to first half of string
k = 0
while k < compare_length and is_palindrome:
ch = stack.pop(char_stack)
if chars[k].lower() != ch.lower():
is_palindrome = False
k = k + 1
# display results
if is_palindrome:
print (chars, 'is a palindrome\n')
print (
else:
print (chars, 'is NOT a palindrome\n')
# get string from user
chars = input('Enter string to check: ')
and here is the code for the module I created:
def countLetters(chars):
"""this function keeps track of the longest palindrome"""
palinlen = len(chars)
print("This Palindrome is ",palinlen," characters long!")
What exactly am I missing? Any help would be greatly appreciated!
1 Answer 1
You fail to actually call the function you have imported.
The comments on your question already explain this, but to go into a little more detail:
Say we have 2 files, one is my 'module', the other my project (this is a useless example btw)
#Module file, moduleFoo.py
def foo(bar):
print(bar)
.
#Project file
import moduleFoo
moduleFoo.foo("Some wild stuff")
With the final line of our project file, we call or invoke our function inside the module file
This can also be done doing:
from moduleFoo import foo
foo("Some wild stuff")
countLettersafter importing it, which means that you never invoke it. Pedantically, the function/module itself technically doesn'treturnanything, it only does aprint(), when you say you want it to return. Also, according to PEP guidelines, functions should be named using snake_case, all lowercase with underscores, not mixed case like you have