如何通过控制台输入自定义运算表达式并在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

