如何将一个函数的使用输出/返回作为后续函数的输入/参数?

问题描述 投票:0回答:1
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(“NameError:名称 'weather_type' 未定义)”。

我认为weather_type是从user_input()函数返回的,然后传递给call_API()。我应该如何传递参数?

python function parameters
1个回答
0
投票

您从函数返回值,但不将这些值分配给任何变量。

这是更正后的代码:

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)
© www.soinside.com 2019 - 2024. All rights reserved.