简体   繁体   中英

Simple Python script not working

I am trying to learn Python. This is my first time writing Python script. All I am trying to do is take a string as an input and print it if it is not 'exit'. But it is showing various errors.

def main():
    while True:
        data = input('Please enter a string');
        if data == 'exit': 
            break
        else:
            print(data)

if __name__ == '__main__':
    main()

The errors were as follows. First time it said:

unexpected EOF while parsing

Second time it said:

nameerror: name 'asd' not defined

Your indentation is off. It should be:

def main():
    while True:
        data = input('Please enter a string');
        if data == 'exit': 
            break
        else:
            print(data)

if __name__ == '__main__':
    main()

Python takes indentation very seriously (in fact, that is how it knows what goes with an if-statement, function declaration, etc.)

Edit:

My post above was geared towards your question using Python 3.x (after all, that is the tag you gave). Since you are not using 3.x, but 2.x instead, then your function should be like this:

def main():
    while True:
        # Use raw_input instead so input is not evaluated
        data = raw_input('Please enter a string');
        if data == 'exit': 
            break
        else:
            print data

if __name__ == '__main__':
    main()

You'll get an error because the function "input" expects an intenger. Use raw_input to recover the text you type.

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