Python函数参数传递报错(NameError):如何实现函数输出转后续输入?
解决Python代码中的NameError及参数传递问题
你的问题核心是没有接收函数返回的变量,直接调用后续函数时自然找不到未定义的变量。具体修正步骤如下:
调用
user_input()时,必须把它返回的两个值赋值给变量,这样后续才能使用:weather_type, num_data_points = user_input()调用
call_API()时,传入上面的变量,同时把返回的DataFrame保存到df变量:df = call_API(weather_type, num_data_points)调用
clean_data()时传入df,并保存返回的数组到data_array:data_array = clean_data(df)最后调用
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
相关产品推荐
相关产品推荐

