You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过控制台输入自定义运算表达式并在Python循环中执行?

How to Dynamically Execute User-Inputted Operations in Python

Hey there! The issue with your modified code is that just writing operation in the loop doesn't actually run the code stored in that string variable—it just references the variable without executing its content. Let's fix this so you can input operations like y = x/2 and have them work as expected.

The Root Problem

When you use input() to get the operation, it's stored as a plain string. Python doesn't automatically execute string content as code unless you explicitly tell it to. Your original code hardcoded y = x/2, which is a valid Python statement, but when you replace that with the operation variable, you need a way to run that string as code.

Solution: Use exec() to Run the String as Code

Python's built-in exec() function lets you execute string-based Python code. Here's how to adjust your code to make it work:

operation = input("operation: ")
y = 0
axis_x = list(range(10))
axis_y = []
for x in axis_x:
    # Execute the user-inputted operation string
    exec(operation)
    print(y)
    axis_y.append(y)

How It Works

When you enter y = x/2 in the console, exec(operation) will run that exact line of code during each iteration of the loop. Since x is defined in the loop's scope, the operation will use the current value of x to calculate y correctly.

Alternative: Use eval() for Expressions

If you prefer to input just the expression (like x/2 instead of y = x/2), you can use eval() instead, which evaluates an expression and returns its result:

operation = input("operation (expression): ")
y = 0
axis_x = list(range(10))
axis_y = []
for x in axis_x:
    y = eval(operation)
    print(y)
    axis_y.append(y)

Now you can input x*3 or x**2 directly, and it will compute y without needing to write the full assignment.

Important Note: Security Risks

Be aware that exec() and eval() can execute arbitrary Python code. If this program is going to be used by someone else, it's a major security risk—users could input malicious code that harms your system. This approach is safe only if you're the one using the program or you fully trust the input source.

内容的提问来源于stack exchange,提问作者dežko123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:43:15