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

Python3中如何在一个函数中调用另一个函数内的变量?

Hey there! Let's tackle this variable access issue between your run() and pace() functions. The core problem here is that pacetotal is a local variable inside pace()—meaning it only exists within that function's scope and can't be accessed directly from outside. Here are a few clean, practical ways to fix this:

This is the most Pythonic approach, as it keeps your functions focused and avoids messy global state. Modify pace() to send its calculated value back to the caller, then capture that value in run():

def run():
    rundecision = input("What do you want to do? calculate distance(d),pace(p) time(t):")
    if rundecision in ['distance', 'd']:
        # Capture the value returned by pace()
        pacetotal = pace()
        # Assuming your time() function should also return timetotal
        timetotal = time()
        distance = calculator(distance=None, pace=pacetotal, time=timetotal)
        return str(distance) + paceunit
print(run())

def pace():
    while True:
        pacemin = input("Enter what pace you want to run/ you ran in :00(min):")
        pacesec = input("Enter what pace you want to run/ you ran in :00(sec):")
        # Add error handling to catch invalid number inputs
        try:
            pacemin_int = int(pacemin)
            pacesec_int = int(pacesec)
            # Calculate your pacetotal (adjust this logic to match your needs)
            pacetotal = pacemin_int * 60 + pacesec_int
            # Return the value to the run() function
            return pacetotal
        except ValueError:
            print("Whoops, please enter valid numbers for minutes and seconds!")

This method keeps variables contained to their functions, makes your code easier to debug, and follows best practices for function design.

2. Use a global variable (Quick but not ideal)

If you're working on a tiny script and want a quick fix, you can declare pacetotal as a global variable. Just note that global variables can make code harder to maintain as your program grows:

# Define the global variable outside both functions
pacetotal = 0

def run():
    # Declare we're using the global pacetotal variable
    global pacetotal
    rundecision = input("What do you want to do? calculate distance(d),pace(p) time(t):")
    if rundecision in ['distance', 'd']:
        pace()
        timetotal = time()
        distance = calculator(distance=None, pace=pacetotal, time=timetotal)
        return str(distance) + paceunit
print(run())

def pace():
    # Declare we're modifying the global pacetotal variable
    global pacetotal
    while True:
        pacemin = input("Enter what pace you want to run/ you ran in :00(min):")
        pacesec = input("Enter what pace you want to run/ you ran in :00(sec):")
        try:
            pacemin_int = int(pacemin)
            pacesec_int = int(pacesec)
            pacetotal = pacemin_int * 60 + pacesec_int
            break  # Exit the loop once valid input is received
        except ValueError:
            print("Please enter valid numbers for minutes and seconds!")

3. Wrap everything in a class (Great for larger programs)

If your running calculator is part of a bigger project, encapsulating variables and functions in a class keeps everything organized and avoids scope issues:

class RunningCalculator:
    def __init__(self):
        self.pacetotal = 0
        self.timetotal = 0
        self.paceunit = "sec/km"  # Adjust to your preferred unit

    def run(self):
        rundecision = input("What do you want to do? calculate distance(d),pace(p) time(t):")
        if rundecision in ['distance', 'd']:
            self.pace()
            self.time()
            distance = self.calculator(distance=None, pace=self.pacetotal, time=self.timetotal)
            return str(distance) + self.paceunit

    def pace(self):
        while True:
            pacemin = input("Enter what pace you want to run/ you ran in :00(min):")
            pacesec = input("Enter what pace you want to run/ you ran in :00(sec):")
            try:
                pacemin_int = int(pacemin)
                pacesec_int = int(pacesec)
                self.pacetotal = pacemin_int * 60 + pacesec_int
                break
            except ValueError:
                print("Invalid input—please enter numbers only!")

    def time(self):
        # Add your time input logic here, setting self.timetotal
        pass

    def calculator(self, distance=None, pace=None, time=None):
        # Add your distance calculation logic here
        if distance is None and pace and time:
            return time / pace  # Example formula, adjust as needed

# Run the calculator
calc = RunningCalculator()
print(calc.run())

A quick side note: Don't forget to add similar handling for your time() function—right now run() tries to use timetotal which is also stuck in time()'s local scope!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:33:10