我如何从另一个函数中的函数调用变量?-Python3

时间:2018-04-18 05:02:40

标签: python-3.x

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
)

这是我的错误:

  

追踪(最近一次调用最后一次):文件&#34; minicapstonev2.py&#34;,行   188,在       print(run())文件&#34; minicapstonev2.py&#34;,第185行,在运行中       距离=计算器(距离=无,步伐= pacetotal,时间= timetotal)

NameError:name&#39; pacetotal&#39;未定义

1 个答案:

答案 0 :(得分:0)

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

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()功能,但如果它与步速相似,则应该有效。

由于评论中的问题而进行编辑:

有关如何处理返回值和程序的一些变体:

# 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?
        ...