print(eval("2 ** 8")) print(eval("1024 + 1024")) print(eval("sum([8, 16, 32])")) x = 100 print(eval("x * 2")) # Arithmetic operations code = compile("5 + 4", "", "eval") print(eval(code)) code = compile("(5 + 7) * 2", "", "eval") print(eval(code)) import math # Volume of a sphere code = compile("4 / 3 * math.pi * math.pow(25, 3)", "", "eval") print(eval(code)) x = 100 # A global variable print(eval("x + 100", {"x": x})) y = 200 # Another global variable print(eval("x + y", {"x": x, "y": y})) print(eval("x + y + z", {"x": x, "y": y, "z": 300})) print(eval("sum([2, 2, 2])", {})) print(eval("min([1, 2, 3])", {})) print(eval("pow(10, 2)", {})) x = 100 # A global variable y = 200 # Another global variable print(eval("x + y")) # Access both global variables x = 100 y = 100 print(eval("x != y")) print(eval("x < 200 and y > 100")) print(eval("x is y")) print(eval("x in {50, 100, 150, 200}")) def func(a, b, condition): if eval(condition): return a + b return a - b print(func(2, 4, "a > b")) print(func(2, 4, "a < b")) print(func(2, 2, "a is b")) # Arithmetic operations print(eval("5 + 7")) print(eval("5 * 7")) print(eval("5 ** 7")) print(eval("(5 + 7) / 2")) import math # Area of a circle print(eval("math.pi * pow(25, 2)")) # Volume of a sphere print(eval("4 / 3 * math.pi * math.pow(25, 3)")) # Hypotenuse of a right triangle print(eval("math.sqrt(math.pow(10, 2) + math.pow(15, 2))")) # Run the echo command import subprocess print(eval("subprocess.getoutput('echo Hello, World')")) # Launch Firefox (if available) # print(eval("subprocess.getoutput('firefox')")) print(eval("sum([5, 5, 5])", {}, {})) print(eval("__import__('math').sqrt(25)", {}, {})) input_string = """[ c for c in ().__class__.__base__.__subclasses__() if c.__name__ == "range" ][0](10)""" print(list(eval(input_string, {"__builtins__": {}}, {}))) def eval_expression(input_string): # Step 1 allowed_names = {"sum": sum} # Step 2 code = compile(input_string, "", "eval") # Step 3 for name in code.co_names: if name not in allowed_names: # Step 4 raise NameError(f"Use of {name} not allowed") return eval(code, {"__builtins__": {}}, allowed_names) print(eval_expression("3 + 4 * 5 + 25 / 2")) print(eval_expression("sum([1, 2, 3])")) def eval_expression(input_string): code = compile(input_string, "", "eval") if code.co_names: raise NameError(f"Use of names not allowed") return eval(code, {"__builtins__": {}}, {}) print(eval_expression("3 + 4 * 5 + 25 / 2")) from ast import literal_eval # Evaluating literals print(literal_eval("15.02")) print(literal_eval("[1, 15]")) print(literal_eval("(1, 15)")) print(literal_eval("{'one': 1, 'two': 2}")) print("Enter a math expression: 15 * 2") print(eval(input("Enter a math expression: "))) print("Enter a math expression: 5 + 8") print(eval(input("Enter a math expression: ")))