[Python] Summary of eval / exec functions + How to write character strings with line breaks

[Python] Summary of eval / exec functions + How to write character strings with line breaks

The eval function and the exec function are one of the built-in functions. The character string given as an argument can be executed as an expression or statement.

  1. [eval function](#eval function)
  2. [exec function](#exec function)
  3. [Difference between exec and eval](Difference between #exec and eval)
  4. [Triple quotation marks (''')](# Triple quotation marks)
  5. [exec and triple quotes](#exec and triple quotes)

eval function

Executes the expression entered as a character string in the argument. The execution result is returned as a return value.

ʻEval ("expression") ` └ Error if it is a sentence └ Abbreviation for evaluation

python


a = eval("5*2")
print(a)

#output
10

**▼print** You can print inside eval, or you can print eval.

python


eval("print(5*2)")
print(eval("5*2"))

#output
10
10

### Use a variable assigned a character string as an argument

String assignment


l=[]
s=".extend('abc')"

#Strings do not require quotation marks
eval("l"+s)
print(l)

#output
['a', 'b', 'c']

Quotation marks are not required when you put a string variable in the argument of eval **.


### Use strings in expressions

When using a character string, use a symbol different from the surrounding symbol. ·"" in:"' '" ·"' '"in:"" ""

Use strings in eval


a = eval("'aaa'")
b = eval('"bbb"')

print(a)
print(b)

#output
aaa
bbb

Same symbol is error


eval(""aaa"")

#output
SyntaxError: invalid syntax

Error pattern

--When you enter a sentence --For non-character strings (numerical values, etc.)

If you enter a sentence


eval("a = 5*2")

#output
SyntaxError: invalid syntax

Other than character strings


eval(5*2)

#output
TypeError: eval() arg 1 must be a string, bytes or code object

Other than character string (key name specified)


eval(a=5)

#output
TypeError: eval() takes no keyword arguments

exec function

Executes the expression or statement of the character string entered in the argument.

ʻExec ('statement or expression')` └ Abbreviation for execute └ There is no return value for exec itself

Enter a statement as an argument


exec("a=5*2")
print(a)

#output
10

Use strings


exec("a = 'hello'")
print(a)

#output
hello

Multiple sentences


exec("a=2; b=5; c=a*b")
print(c)

#output
10

・ ";" Agrees with line feed


Enter an expression as an argument


l=[1,2,3]

exec("l.extend([4,5,6])")
print(l)

#output
[1, 2, 3, 4, 5, 6]

## Difference between exec and eval ** (1) exec can take a statement as an argument ** └ eval is an error

** (2) exec has no return ** └ exec can also take an expression as an argument like eval. └ exec itself exists (returns with return) └ eval itself does not exist (None)

exec itself has no value


exec("2+5") is None    #True
eval("2+5") is None    #False

Illustration


#Expressions in exec can be executed
exec("print(2*5)")

#exec itself has no return value(None)
print(exec("2*5"))

#output
10
None

## Triple quotes Multiple lines can be handled as character strings.

'''Code (with line breaks)''' └ Surround with 3 quotation marks └ If you start a new line immediately after''', the output will also be broken.

python


a='''
Hello,
It is a good weather today.
How is the weather there?
'''

print(type(a))
print(a)

#output
<class 'str'>

Hello,
It is a good weather today.
How is the weather there?

No line breaks

You can use backslashes to escape line breaks.

Line break escape


a='''\
Hello,
It is a good weather today.\
How is the weather there?
'''

print(a)

#output
Hello,
It is a good weather today. How is the weather there?

## exec and triple quotes You can execute the defined function processing by using a variable in which triple quotes are assigned to the argument of exec.

python


a ='''
#Function definition
def hello_func(name):
    print(f'Hello{name}Mr.')


#Function execution
name="Todoroki"
hello_func(name)
'''

exec(a)

#output
Hello Todoroki's

Because you can't pass arguments to a string function in an exec Described in triple quotes until function execution.


> Official page -[Built-in functions](# https://docs.python.org/ja/3/library/functions.html) ・ [Eval](# https://docs.python.org/ja/3/library/functions.html#eval) -[Exec](# https://docs.python.org/ja/3/library/functions.html#exec)

Recommended Posts

[Python] Summary of eval / exec functions + How to write character strings with line breaks
Summary of how to share state with multiple functions
[Python] How to make a list of character strings character by character
[Python] Summary of how to use split and join functions
[Python] Summary of how to use pandas
[Python2.7] Summary of how to use unittest
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Summary of how to write AWS Lambda
[Introduction to Python] How to write a character string with the format function
Summary of how to import files in Python 3
Summary of how to use MNIST in Python
How to specify attributes with Mock of python
Summary of how to read numerical data with python [CSV, NetCDF, Fortran binary]
[Python] How to draw a line graph with Matplotlib
How to write a list / dictionary type of Python3
[Python] Summary of how to specify the color of the figure
The 15th offline real-time I tried to solve the problem of how to write with python
Write to csv with Python
How to separate strings with','
How to install NPI + send a message to line with python
Display character strings without line breaks in python (personal memo)
Offline real-time how to write Python implementation example of E14
[python] Summary of how to retrieve lists and dictionary elements
How to enable Read / Write of net.Conn with context with golang
Comparison of how to use higher-order functions in Python 2 and 3
Summary of how to write .proto files used in gRPC
How to write offline real-time Solving E05 problems with Python
How to write offline real time I tried to solve the problem of F02 with Python
How to write a Python class
Python: How to use async with
[Hugo] Summary of how to add pages to sites built with Learn
Summary of character string format in Python3 Whether to live with the old model or the new model
exec, eval to execute [python] statement
[Python] Write to csv file with Python
Summary of how to use pandas.DataFrame.loc
[Introduction to Python] How to split a character string with the split function
Print with python3 without line breaks
Summary of how to use pyenv-virtualenv
Offline real-time how to write Python implementation example of E15 problem
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
Here's a brief summary of how to get started with Django
How to get started with Python
How to connect to Cloud Firestore from Google Cloud Functions with python code
10 functions of "language with battery" python
[Beginner] Extract character strings with Python
How to use FTP with Python
[Introduction to Udemy Python3 + Application] 12. Indexing and slicing of character strings
How to calculate date with python
Summary of how to use csvkit
How to write offline real time Solve F01 problems with Python
Summary of how to write if statements (Scala, Java, Rust, C language, C ++, Go language, PHP, Perl, Python, Ruby)
Summary of how to write increment / decrement (Scala, Java, Rust, C, C ++, Go, PHP, Perl, Python, Ruby, JavaScript)
The 16th offline real-time how to write problem was solved with Python
[Yahoo! Weather Replacement Version] How to get weather information with LINE Notify + Python
How to crop the lower right part of the image with Python OpenCV
How to write offline real time I tried to solve E11 with python
The 16th offline real-time how to write reference problem to solve with Python
[Python] How to change character string (str) data to date (strptime of datetime)
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Python] Summary of conversion between character strings and numerical values (ascii code)