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

Spyder IDE中if else计算结果未显示在变量浏览器的解决方法求助

Fix for Your Spyder Variable Browser Issue

Hey there, let's sort out why your calculated values aren't showing up in Spyder's Variable Explorer and get your code working properly!

First, let's break down the issues in your original code:

  • Naming Conflict: You've got a variable s and a function named s—this confuses Python and makes it hard for Spyder to track the variable correctly.
  • You're Not Calling the Function: Your final print(s) is just printing the function object itself, not actually running the function on your a and b arrays.
  • Function Doesn't Handle Arrays: Your a and b are numpy arrays (from .values), but your current function is written to handle single numbers—it'll throw an error if you pass arrays directly.

Here's the fixed code:

import pandas as pd
import numpy as np  # For efficient vectorized operations

# Load your data
p = pd.read_excel('Data1.xlsx')
p.head()

# Extract your arrays
a = p.iloc[:12,0].values
b = p.iloc[:12,1].values

c = 200.00
d = 150.00

# Rename function to avoid variable name conflict
def calculate_s(x, y):
    # Use numpy's where for vectorized conditional logic (works on entire arrays)
    return np.where(x + y < c, c, np.where(x + y > d, d, x + y))

# Calculate result and assign to a variable (this will appear in Spyder's explorer)
s = calculate_s(a, b)

# Verify the output
print(s)

Why this works for Spyder's Variable Explorer:

  • No Naming Conflicts: The function is now calculate_s, so the variable s is a distinct array that Spyder can easily track.
  • Actual Calculation Execution: We call calculate_s(a, b) and assign the output to s—this variable will pop up in the Variable Explorer as soon as the code runs.
  • Array-Friendly Logic: Using np.where handles the entire array at once, returning a numpy array that Spyder recognizes and displays neatly.

If you prefer a loop-based approach (for clearer step-by-step logic):

If you want to stick with explicit loops instead of numpy, here's an alternative version:

# Rename function to avoid conflict
def calculate_single_s(x, y):
    if x + y < c:
        return c
    elif x + y > d:
        return d
    else:
        return x + y

# Loop through each pair of values in a and b
s = []
for x, y in zip(a, b):
    s.append(calculate_single_s(x, y))

# Convert to numpy array (optional, but Spyder displays arrays better than lists)
s = np.array(s)

print(s)

Either way, once you run the code, the s variable will show up in Spyder's Variable Explorer with all your calculated values!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:33:25