Jyzavi
Jyzavi

Reputation: 11

Trouble with eval of a sentence as input in python

I am in a class teaching python and am a beginner at any sort of coding. I keep running into this problem and I can't find anything in my text book or additional handouts explaining what I'm doing wrong. Here is an example taken from one of the exercises that I am having trouble with. The task is to write a program that takes a sentence given by the user and rearrange the words to get "yoda speak". This is what I have.

def main():

    print("Enter a sentence and have it translated into Yoda speak!")

    sentence= eval(input("Enter your sentence: "))
    word_list=sentence.split()

    yoda_words= word_list[2:]+word_list[0:2]

    yoda_says= yoda_words.join()

    print("Yoda says: ", yoda_says)

main()

However why I try to run the program I get this:

Enter a sentence and have it translated into Yoda speak!

Enter your sentence: Jane ran fast

Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 4.0\src\debug\tserver_sandbox.py", line 14, in File "C:\Program Files (x86)\Wing IDE 101 4.0\src\debug\tserver_sandbox.py", line 5, in main File "", line 1, in ? Syntax Error: Jane ran fast: , line 18

I think the problem comes from me using the whole eval(input()) command wrong. Could someone please explain what I am doing wrong?

Upvotes: 0

Views: 373

Answers (3)

Levon
Levon

Reputation: 143032

I would replace your input statement with the following (see note 1):

sentance= input("Enter your sentence: ")

Also, try this for your join:

' '.join(yoda_words)

(note 1) As pointed out by @Boud below, better to use input (instead of raw_input with Python 2.x) with Python 3.x (see for example What's the difference between raw_input() and input() in python3.x?)

I currently don't have access to Python 3.x - really should install it.

Upvotes: 2

Raymond Hettinger
Raymond Hettinger

Reputation: 226376

The eval is unnecessary. Remove it and all should work fine. That just leaves fixing the spelling of "sentance" :-)

Upvotes: 2

Edvard Pedersen
Edvard Pedersen

Reputation: 773

eval runs Python code, e.g. eval("1+1") returns 2, this is not what you want. This is the reason you get the syntax error on "Jane ran fast", Python is trying to execute Jane ran fast.

Remove the eval and you'll be fine.

Upvotes: 4

Related Questions