如何将一个函数的输出作为下一个函数的输入参数?
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()
user_input()
call_API(weather_type, num_data_points) # NameError: name 'weather_type' is not defined
clean_data(df)
plot_data(data_array, weather_type, num_data_points)
我在Jupyter Notebook里运行这个代码,但总是出现一个错误,提示“NameError: name 'weather_type' is not defined”(名字错误:'weather_type'这个名字没有定义)。
我以为weather_type是从user_input()这个函数返回的,然后再传给call_API()。我应该怎么传递这个参数呢?
1 个回答
1
你从函数里返回了一些值,但你并没有把这些值赋给任何变量。
下面是修正后的代码:
import numpy as np
import pandas as pd
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() # <-- note the weather_type, num_data_points
df = call_API(weather_type, num_data_points) # <-- df =
data_array = clean_data(df) # <-- data_array =
plot_data(data_array, weather_type, num_data_points)