2016-12-13 36 views
0

可能是一個簡單的修復,但我只是不能解決它,我在一個函數中有一個函數,我該如何一次突破它們?

基本上這是一個小程序,爲我的時間表工作)完美的工作,但我決定添加一個功能,如果我在任何時候重新啓動整個程序時進入重新啓動。

我嘗試過在時間內調用時間,但這樣做會重新啓動,但在重新啓動後會完成原始操作。我也嘗試了一個重新啓動函數,它調用Time,然後調用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 
+0

'如果h.strip()== '重啓':提高MyException'? – jbndlr

+0

你正在使這件事變得比需要的複雜。你不需要嵌套的函數定義。請參閱[詢問用戶輸入,直到他們給出有效的響應](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) –

回答

1

您可以使用您自己的Exception s用於此目的。只要確定,不要讓它們不被捕獲。

看一看這個示範性實施方案:

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 

輸出示例:

> Arrival time (H:M): 8:17 
> Lunch duration (H:M): as 
    - Parsing error; re-requesting value. 
    - (Type 'stop' to abort or 'restart' to start over.) 
> Lunch duration (H:M): 0:37 
> Leaving time (H:M): 16:48 
    - MINUTES OF WORK: 474.00 
> New calculation? n 
相關問題