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

如何在Python中循环使用算术运算符实现批量计算?

问题:如何循环执行算术运算符计算?

用户尝试通过以下代码,实现输入任意整数后,循环执行该整数与固定数字的+、-、*、%运算:

num_input = input("Please enter a number: ")
num = int(num_input)

# 定义算术运算符列表
operations = ['+','-', '*','%']

print(f"You entered: {num_input}")
print("The mathematical operations applied to your number and 15 are:")

# 初始化存储结果的列表
results = []

# 遍历运算符并计算结果
for operand in operations:
    op= [operand.strip() for operand in operations]
    result = (num) op 20     
    results.append(result)

# 遍历结果并打印
for i, (operator, operand) in enumerate(operations):
    print(f"{num} {operator} {operand} = {results[i]}")

遇到的问题:字符串形式的运算符(如'*')无法直接参与计算,尝试赋值给op后出现语法错误:

Cell In[103], line 16
result = (num) op 20
^
SyntaxError: invalid syntax

解决方案

方法1:用字典映射运算符到对应函数

Python的operator模块提供了与算术运算符对应的内置函数,我们可以用字典将字符串运算符映射到这些函数,实现循环计算:

import operator

num_input = input("Please enter a number: ")
num = int(num_input)
fixed_num = 20

# 建立字符串运算符到运算函数的映射
op_map = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '%': operator.mod
}

print(f"You entered: {num_input}")
print(f"The mathematical operations applied to your number and {fixed_num} are:")

results = []
for op_symbol, op_func in op_map.items():
    result = op_func(num, fixed_num)
    results.append((op_symbol, result))

# 打印所有运算结果
for op_symbol, result in results:
    print(f"{num} {op_symbol} {fixed_num} = {result}")

方法2:使用eval()动态计算(注意安全风险)

如果能确保输入是完全可信的,可以用eval()将构造的表达式字符串转为可执行代码,但禁止用于处理不可信的用户输入(存在代码注入风险):

num_input = input("Please enter a number: ")
num = int(num_input)
fixed_num = 20
operations = ['+','-', '*','%']

print(f"You entered: {num_input}")
print(f"The mathematical operations applied to your number and {fixed_num} are:")

results = []
for op in operations:
    # 构造运算表达式字符串,用eval执行计算
    expr = f"{num} {op} {fixed_num}"
    result = eval(expr)
    results.append((op, result))

# 打印所有运算结果
for op, result in results:
    print(f"{num} {op} {fixed_num} = {result}")

原代码错误说明

  1. 循环内的op= [operand.strip() for operand in operations]完全多余,每次循环都会重新生成整个运算符列表,没有实际作用;
  2. Python无法直接将字符串变量解析为运算符,必须通过函数映射或动态执行的方式转换处理。

内容的提问来源于stack exchange,提问作者Rstudyer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:03:25