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

Python函数参数传递报错(NameError):如何实现函数输出转后续输入?

解决Python代码中的NameError及参数传递问题

你的问题核心是没有接收函数返回的变量,直接调用后续函数时自然找不到未定义的变量。具体修正步骤如下:

  1. 调用user_input()时,必须把它返回的两个值赋值给变量,这样后续才能使用:

    weather_type, num_data_points = user_input()
    
  2. 调用call_API()时,传入上面的变量,同时把返回的DataFrame保存到df变量:

    df = call_API(weather_type, num_data_points)
    
  3. 调用clean_data()时传入df,并保存返回的数组到data_array:

    data_array = clean_data(df)
    
  4. 最后调用plot_data()时,传入保存好的三个变量即可:

    plot_data(data_array, weather_type, num_data_points)
    

修正后的完整代码

import pandas as pd
import numpy as np

def user_input():
    
    while True:
        weather_type = input("Which weather type (temperature, humidity, pressure, or rainfall)? ")
        if weather_type in ["temperature", "humidity", "pressure", "rainfall"]:
            break
        else:
            print("Error: Please enter 'temperature', 'humidity', 'pressure', or 'rainfall'.")

    while True:
        try:
            num_data_points = int(input("Number of data points (maximum of 8000): "))
            if num_data_points < 1 or num_data_points > 8000:
                print("Error: Number of data points must be between 1 and 8000.")
            else:
                break
        except ValueError:
            print("Error: Please enter an integer value for number of data points.")

    return weather_type, num_data_points

def call_API(weather_type, num_data_points):
    api_url = f"https://api.thingspeak.com/channels/12397/fields/{4 if weather_type == 'temperature' else 3 if weather_type == 'humidity' else 5 if weather_type == 'rainfall' else 6}.csv?results={num_data_points}"
    df = pd.read_csv(api_url)
    return df

def clean_data(df):
    data_array = df.iloc[:, 1].to_numpy()  # Extracting the data column and converting to numpy array
    return data_array

def plot_data(data_array, weather_type, num_data_points):
    import matplotlib.pyplot as plt
    
    plt.plot(np.arange(num_data_points), data_array)
    plt.xlabel("Data Points")
    plt.ylabel(f"{weather_type.capitalize()}")
    plt.title(f"Plot of {weather_type.capitalize()}")
    plt.show()

# 修正后的调用流程
weather_type, num_data_points = user_input()
df = call_API(weather_type, num_data_points)
data_array = clean_data(df)
plot_data(data_array, weather_type, num_data_points)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:51:30