简体   繁体   中英

Why dont my functions work?

This is python 3, this code basically checks if a word is the same when read backwards. When i execute this through Visual Studio, nothing happens, and I get the prompt to press any key to continue...

if "__name__" == "__main__":
    StartProgram() 

def StartProgram():
    Input = AskForDataSimple()
    print(CheckIfPalindrome(Input))

def AskForDataSimple():
    print("Please input the line to test.")
    In = input()
    return In

def CheckIfPalindrome(x):
    if x[::-1] == x:
        return True
    else:
        return False

Please note that this simpler version actually works:

x = input()

if x[::-1] == x:
    print(True)
else:
    print(False)
if "__name__" == "__main__":

Change this to

if __name__ == "__main__":

__name__ is a variable containing name of this module. You need these line so that your main logic would be used only if this file is executed directly, not when imported as a module by another code.

Still it won't work, because you need to define the function you call before these lines: move these lines to the end of the file.

Also, this

def CheckIfPalindrome(x):
    if x[::-1] == x:
        return True
    else:
        return False

can be replaced with

def CheckIfPalindrome(x):
    return x[::-1] == x

Move main function to bottom of file and try it

if __name__ == "__main__":
      StartProgram() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM