0

The program asked is:

"besides testing if the length of the given string is more than ten characters, it also tests if there is the character "X" (capital X) in the given string. If the string is longer than 10 characters and it has X in it, the tester subfunction returns a value True to the main function, otherwise False.

If the subfunction returns True to the main function, the program prints "X spotted!". As earlier, if the user inputs "quit", the program terminates."

This is what I tried, but the part of checking the x character does not work at all

def check(st,res="Too short"):
    if len(st)>=10:
        if checkX(st):
            st=st+"\nX spotted!"
        return st
    else:
        return res

def checkX(st):
    for i in st:
        if i=="X":
            return True
    return False

def main():
    while True:
        st=input("Write something (quit ends): ")
        if st=="quit":
            break
        print(check(st))

It only checks if introduced string length is equal or higher than 10 characters.

Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

3

The code works.

What should you change in your code:

You can use the in operator:

if "blah" not in somestring: 
    continue

Does Python have a string 'contains' substring method?

Do a real "main":

if __name__ == '__main__':

What you can do if you want to keep the main() function:

A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

main — Top-level script environment

Result (this code works, it is simplier, more pythonic and respect pep8):

def check_input(tested_sentence: str, result: str = "Too short"):
    if len(tested_sentence) >= 10:
        if "X" in tested_sentence:
            result = tested_sentence + "\nX spotted!"
        else:
            result = tested_sentence
    return result


def main():
    while True:
        sentence = input("Write something (quit ends): ")
        if sentence == "quit":
            break
        print(check_input(sentence))

if __name__ == '__main__':
    main()

Code Style — The Hitchhiker's Guide to Python

Community
  • 1
  • 1
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67