我在函数中有一个函数,如何一次性打破它们?

时间:2016-12-13 09:41:31

标签: python function python-3.x

可能只是一个简单的修复,但我无法解决,

基本上这是我用十进制格式计算一天工作时间的一个小程序,(因为我必须这样做,因为我的工作时间表)工作完全正常,但我决定添加在一个功能中,如果我在任何时候重新启动整个程序重启。

我尝试在时间内调用时间但是重新开始但是在重新开始之后完成原始。我还尝试创建一个调用Time的Restart函数,然后调用Restart,但这也不起作用。

所以我想要突破它们并再次调用程序,这是否可能?

def Time():
    clear()
    def is_valid_hours():
        while True:
            h=input("Hour: ")
            if h=="restart": return "yes" #this line doesnt work (tried break)
            try:
                h=int(h)
                return h
            except:
                print("Please enter numbers!")
    def is_valid_Minutes():
        while True:
            h=input("Minute: ")
            if h=="restart": return "yes" # this is the other line (break tried)
            try:
                h=int(h)
                return h
            except:
                print("Please enter numbers!")
    print("Please use time in a 24hour clock format when using this calculator")
    print("Please enter arrival time:")
    arrivalTimeHours=is_valid_hours()
    arrivalTimeMinutes=is_valid_Minutes()

    print("Please enter length of lunch break: ")
    lunchBreakHours=is_valid_hours()
    lunchBreakMinutes=is_valid_Minutes()

    print("Please enter desired leave time: ")
    leaveTimeHours=is_valid_hours()
    leaveTimeMinutes=is_valid_Minutes()

    if arrivalTimeHours>0:
        arrivalTimeHours=arrivalTimeHours*60
    arrivalTime=arrivalTimeHours+arrivalTimeMinutes
    if lunchBreakHours>0:
        lunchBreakHours=lunchBreakHours*60
    lunchBreak=lunchBreakHours+lunchBreakMinutes
    if leaveTimeHours>0:
        leaveTimeHours=leaveTimeHours*60
    leaveTime=leaveTimeHours+leaveTimeMinutes

    totalTimeMinutes=leaveTime-(arrivalTime+lunchBreak)
    decimalTime=totalTimeMinutes/60
    print("Your decimal time is "str(decimalTime))
    newTime=input("Would you like to do a new time?: ")
    return newTime.lower()

newTime=Time()
while newTime=="yes" or newTime=="ye" or newTime=="y" or newTime=="yah" or newTime=="yeah" or newTime=="yh":
    newTime=Time()
input("Press enter to close")

修改 我也试过这样做,也没用。

def Time():
    clear()
    notQuitting=True
    while notQuitting==True:
        def is_valid_hours():
            while True:
                h=input("Hour: ")
                if h=="restart":
                    notQuitting=False
                    return "yes"
                try:
                    h=int(h)
                    return h
                except:
                    print("Please enter numbers!")
        def is_valid_Minutes():
            while True:
                m=input("Minute: ")
                if m=="restart":
                    notQuitting=False
                    return "yes"
                try:
                    m=int(m)
                    return m
                except:
                    print("Please enter numbers!")
         #rest of code

1 个答案:

答案 0 :(得分:1)

您可以使用自己的type alias Article = { pubDate: Date } articleDecoder : Decoder Article articleDecoder = decode Article |> required "pubDate" pubDateDecoder pubDateDecoder : Decoder Date.Date pubDateDecoder = string |> andThen (\s -> case Date.fromString s of Err e -> fail e Ok d -> succeed d ) 来实现此目的。只要确保你不要让他们没有被捕。

看看这个示例性实现:

Exception

示例输出:

import datetime

class RestartTimeException(Exception): pass # If user requests restart
class StopTimeException(Exception): pass    # If user requests stop

def take_time():
    def read_or_fail(prompt):
        while True: # As long as input is not valid or user does not abort...
            try:
                i = input(prompt).strip()
                if i == 'restart': # User wants to restart: raise.
                    raise RestartTimeException
                elif i == 'stop':  # User wants to abort: raise.
                    raise StopTimeException
                # Split input into hours and minutes and parse integer values (validity check)
                return tuple(int(p) for p in i.split(':')) 
            except (TypeError, ValueError):
                # On parsing failure inform user and retry
                print('  - Parsing error; re-requesting value.\n  - (Type \'stop\' to abort or \'restart\' to start over.)')

    # Read arrival time and make datetime object (ignore year, day, month)
    h, m = read_or_fail('> Arrival time (H:M): ')
    arr = datetime.datetime.strptime('{:d}:{:d}'.format(h, m), '%H:%M')

    # Read lunch break duration and make timedelta object
    h, m = read_or_fail('> Lunch duration (H:M): ')
    lun = datetime.timedelta(hours=h, minutes=m)

    # Read leaving time and make datetime object (ignore year, day, month)
    h, m = read_or_fail('> Leaving time (H:M): ')
    dep = datetime.datetime.strptime('{:d}:{:d}'.format(h, m), '%H:%M')

    # Calculate time difference as timedelta
    total = dep - arr - lun
    # Calculate difference in minutes (object only yields seconds)
    return total.seconds / 60.0

if __name__ == '__main__':
    do_new = True
    while do_new: # As long as the user wants to ...
        try:
            mins = take_time() # Get times, calculate difference
            print('  - MINUTES OF WORK: {:.2f}'.format(mins))
            do_new = input('> New calculation? ').strip().lower().startswith('y')
        except RestartTimeException:
            # Catch: User requested restart.
            print('  - Restart requested.')
        except (StopTimeException, BaseException):
            # Catch: User requested stop or hit Ctrl+C.
            try:
                print('  - Stop requested.')
            except KeyboardInterrupt:
                pass # Just for clean exit on BaseException/Ctrl+C
            do_new = False