-1

I am currently doing miniscript that is sending documents to a specific path based on a code I enter.

The code is basic, but I get an error which I really don't understand.

When I run the following code:

en = "English"
source = eval(input("Source language?\n"))
print (source)

If I hit 'en' I get English without any errors.

But if I run the same without input:

en = "English"
eval(en)

I get "name 'English' is not defined".

Basically, I want to use some of eval() functions in my code without the input() function. Where I am wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    It is not the same. It would be the same if you did `eval("en")`. Doing `eval(en)` is equivalent of doing `eval("English")` which fails because Python doesn't know how to evaluate that... – Tomerikoo Dec 23 '21 at 15:40
  • 1
    I don’t understand exactly what you trying to do, but in the latter case if you replace eval with print, it should work. – rv.kvetch Dec 23 '21 at 15:41
  • 3
    Does this answer your question? [Difference between eval("input()") and eval(input()) in Python](https://stackoverflow.com/q/55144515/6045800) – Tomerikoo Dec 23 '21 at 15:42
  • Or [What does Python's eval() do?](https://stackoverflow.com/q/9383740/6045800) – Tomerikoo Dec 23 '21 at 15:44

2 Answers2

1

Usually there is never any need to use eval in Python:

languages = {'fr': 'french', 'gr': 'greek', 'en': 'english'}
source = languages.get(input("Source language?\n"), 'Undefined language!')
print(source)

Out:

Source language?
gr
greek
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0

eval expects a string as its argument. By passing it en, you're giving it the string "english". Instead, you probably want

eval("en")

However, using eval is generally bad practice. I'd look into alternative ways of doing what you're after.

RoadieRich
  • 6,330
  • 3
  • 35
  • 52