【问题标题】:How do i call out variable from a function in another function?-Python3如何从另一个函数中的函数中调出变量?-Python3
【发布时间】:2018-04-18 05:02:39
【问题描述】:
def run():
    rundecision=input("What do you want to do? calculate distance(d),pace(p) time(t):")

if rundecision in ['distance', 'd']:
    pace()
    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):")#user pace in min
        pacesec=input("Enter what pace you want to run/ you ran in :00(secs):")#user pace in sec
        try:
            pacemin=int(pacemin)
            pacesec=int(pacesec)
            if  0 <= pacemin <= 59 and 0 <= pacesec <=59:
                pacetotal=(to_seconds(pacemin,'min')) + (to_seconds(pacesec,'s'))
                pacetotal=int(pacetotal)
                return pacetotal
                break
)

这是我的错误:

Traceback(最近一次调用最后一次):文件“minicapstonev2.py”,行 188,在 打印(运行())文件“minicapstonev2.py”,第 185 行,运行中 距离=计算器(距离=无,步速=总步数,时间=总时间)

NameError: name 'pacetotal' 未定义

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您必须将函数的返回值分配给您可以使用的变量:

    if rundecision in ['distance', 'd']:
        pacetotal = pace() # pace returns the seconds
        timetotal = time() # this should also return the value for your next computation
    distance=calculator(distance=None,pace=pacetotal,time=timetotal)
    return str(distance) + paceunit
    

    您没有提供time() 函数,但如果它与速度相似,则应该可以。


    因cmets中的问题而编辑:

    关于如何处理返回值和您的程序的一些变化:

    # Different ways to return something from a function
    def ModifyGivenDict(di , li):
        # do some calculations
        di["milesPerHour"] = 42
        li.append(999)
    
    def ReturnAValue(x):
        return x ** x
    
    def ReturnMultipleValues(x):
        return [x * u for u in range(20)]
    
    def ReturnTuple(x,y):
        return (x,y,x * y,x ** y,y ** x,"someValue")
    
    d = {"Round1": 496 }
    l = [2,3,4,5,"Hurray"]
    a = ModifyGivenDict(d,l)
    print(d)
    
    k = ReturnAValue(22)
    print(k)
    
    i = ReturnMultipleValues(22)
    print(i)
    
    h = ReturnTuple(4,7)
    print(h)
    
    
    # OOP aproach
    class Timings: 
        @staticmethod
        def toSeconds(text):
            """Understands up to '12:18:24.3545' - returns a floatvalue of seconds"""
            t = [0,0] + text.split(":") # prefix with 2 * 0 if only "22" or "1:22" is given
            t[-1] = float(t[-1])        # make last elements to float
            t[-2] = int(t[-2]) * 60       # make integer minutes into seconds
            t[-3] = int(t[-3]) * 60 * 60    # make integer hours into seconds
    
            return sum(t)
    
        @staticmethod
        def toMeters(distance):
            """Understands '255.23 meters'"""
            converterDict = {'mile':1609.34, 'mi':1609.34, 'km':1000, 'kilometer':1000, 
                             'y':0.9144, 'yard':0.9144, 'meter':1, 'm':1}
            dist,unit = distance.split(" ")
            dist = float(dist)
            unit = unit.rstrip("s").strip().lower()
            return dist * converterDict[unit]
    
        def __init__(self, name):
            self.name = name
            self.laps = {}
            self.lap = 0
    
        def addLap(self, minutesColonSeconds, distance):
            t = self.toSeconds(minutesColonSeconds)
            m = self.toMeters(distance)
            self.laps[self.lap] = {"time":t, "distance":m}
            self.lap += 1
    
        def printLaps(self):
            print("Results for " + self.name,sep="\t")
            print("{:<14} {:<14} {:<14} {:<14} {:<14} {:<14} {:<14}".format(
                  "lap","m","s","m/s", "total time", "total dist","speed"))
    
            tm = 0
            tt = 0
    
            # you could also use an orderedDict from collections
            for k in sorted(self.laps.keys()):
                m = self.laps[k]["distance"]
                t = self.laps[k]["time"]
                tm +=m
                tt += t
                print("{:<14} {:<14} {:<14} {:<14} {:<14} {:<14} {:<14}".format(
                       k,m,t,round(m / t,2), tt,tm,round(tm/tt,2)))
    
    
    def inputTime(text):
        while True:
            i = input(text)
            try:
                t = [0,0] + i.split(":")
                sec = float(t[-1])
                min = int(t[-2])
                hou = int(t[-3])
                if sec+min*60+hou*60*60 <= 0:
                    raise ValueError
                return i
            except (ValueError,EOFError):
                print("Wrong input! Use  '1:12:23.99' for hour:minute:second.partials")
    
    
    def inputDistance(text):
        while True:
            t = input(text)
            try:
                dis,un = t.split()
                dis = float(dis)
                return t
            except:
                print("Wrong input. Use: '23 km' - or: meter, mile(s), yard(s), m, mi, y")
    
    print("\nClassaproach\n\n")
    
    timing = Timings("Just Me")
    
    while True:
        dis = inputDistance("What distance did you cover?")
        tim = inputTime("In what time?")
        timing.addLap(tim,dis)
        timing.printLaps()
    

    输出(经过编辑以更适合此处):

    {'Round1': 496, 'milesPerHour': 42}
    341427877364219557396646723584
    [0, 22, 44, 66, 88, 110, 132, 154, 176, 198, 220, 242, 264, 286,
     308, 330, 352, 374, 396, 418]
    (4, 7, 28, 16384, 2401, 'someValue')
    
    Classaproach
    
    
    What distance did you cover?100 m
    In what time?12.02
    Results for Just Me
    lap       m              s          m/s        total time     total dist     speed
    0         100.0          12.02      8.32       12.02          100.0          8.32
    What distance did you cover?20 km
    In what time?2:0:01
    Results for Just Me
    lap       m              s          m/s        total time     total dist     speed
    0         100.0          12.02      8.32       12.02          100.0          8.32
    1         20000.0        7201.0     2.78       7213.02        20100.0        2.79
    What distance did you cover?5 mi
    In what time?1:1:1
    Results for Just Me
    lap       m              s          m/s        total time     total dist     speed
    0         100.0          12.02      8.32       12.02          100.0          8.32
    1         20000.0        7201.0     2.78       7213.02        20100.0        2.79
    2         8046.7         3661.0     2.2        10874.02       28146.7        2.59
    What distance did you cover?120 km
    In what time?1:02:00
    Results for Just Me
    lap       m              s          m/s        total time     total dist     speed
    0         100.0          12.02      8.32       12.02          100.0          8.32
    1         20000.0        7201.0     2.78       7213.02        20100.0        2.79
    2         8046.7         3661.0     2.2        10874.02       28146.7        2.59
    3         120000.0       3720.0     32.26      14594.02       148146.7       10.15
    What distance did you cover?
            ...
    

    【讨论】:

    • 是的,这非常有帮助,我花了 1.5 天(编程新手)试图自己解决。起搏器仍然给我一个错误。我是否必须将 paceunit 定义为独立函数才能按照我上面在 return 语句中的方式调用它。起搏单元是起搏功能的一部分
    • @ladel paceunit 是 'm' 代表米吗?当您的程序将任何输入转换为秒数(以及可能与其他基本单位的距离)时,我可能会对其进行硬编码......
    • 步速单位是用户可以输入的单位列表。它在速度()下定义为真:速度单位=输入(“输入你的跑步速度单位英里,米,码或公里:”)尝试:如果速度单位在['英里','米','公里','公里','y','yards','yard','meters','m']: break except: print("你的步速单位输入错误请输入这些单位之一。'mile','mi ','km','kilometer','y','yards','yard','meters','m'")#异常重新让用户输入正确的单位 return str(pacetotal)+ str(paceunit )
    • @ladel 查看我的编辑,复制它,添加打印语句以调试它并尝试“摸索”它:) - hth
    • 感谢您的帮助。将审查并使用您的代码。
    猜你喜欢
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2021-04-23
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多