簡體   English   中英

如何在python中基於文本的應用程序中與其他函數交互時獲得經過的時間

[英]how to get the elapsed time while interacting with other functions in a text-based application in python

因此,我創建了一個記錄足球(足球)統計數據的項目。 到目前為止,它只記錄角球和任意球,但我想記錄兩隊之間的控球時間。 我的主要問題是,當我嘗試保留所有時間時,其他功能將不起作用。 這是我嘗試過的:

import time

fk_range = range(0, 1000)
fk_list = list(fk_range)
ck_range = range(0, 1000)
ck_list = list(ck_range)


def body():
    while True:
        choice = input("")
        if choice == "fk":

            first_number_fk = fk_list[0]
            fk_list.remove(first_number_fk)
            number_fk = fk_list[0]
            string_number_fk = str(number_fk)
            print("Free Kick(s)", string_number_fk)

        elif choice == "ck":

            first_number_ck = ck_list[0]
            ck_list.remove(first_number_ck)
            number_ck = ck_list[0]
            string_number_ck = str(number_ck)
            print("Corner Kick(s): ", string_number_ck)

        if choice == "home team":
            start_home = time.time()
            input()
            end_home = time.time()
        if choice == "away_team":
            start_away = time.time()
            input()
            end_away = time.time()
            elapsed_home = end_home - start_home
            elapsed_away = end_away - start_away

        elif choice == "q":
            print(elapsed_away)
            print(elapsed_home)

body()

這是行不通的,但這是我所知道的。 如果您不明白我的意思,請在下方評論,以便我更詳細地解釋。

鑒於(如您在注釋中所述)該代碼在循環中被反復調用,因此您有兩個問題。

  • elapsed_home是在'away_team'分支而非'home_team'分支中設置的。 修復起來很簡單,只需向上移動幾行即可。
  • 您所有的變量都在函數內部聲明-這意味着它們在函數外部不存在,並且在調用之間不存在。 您有三個(合理的)選項可以解決此問題:
    1. 全局聲明它們(在函數頂部,放置例如global elapsed_home
    2. 每次都將它們作為參數傳遞。 每次都將它們退還。
    3. 使用一個類來保存它們,使其成為該類上的方法而不是函數。

隨便你吧。

檢查這個

elapsed_home = 0
elapsed_away = 0
start_home = 0
start_away = 0
ball_home = False
ball_away = True # Assumimg that away team has the starting kick


def body():
    global elapsed_home, elapsed_away, start_home, start_away, ball_home, ball_away
    while True:
       choice = input("")
       ...
       ...
       if choice == "home team":
           if ball_home:
              continue:
           else:
              ball_away = False
              ball_home = True
              start_home = time.time()
              elapsed_away += time.time() - start_away
              print "away elapsed: " + str(elapsed_away)

       if choice == "away_team":
            if ball_away:
                continue
            else:
                ball_away = True
                ball_home = False
                start_away = time.time()
                elapsed_home += time.time() - start_home
                print "home elapsed: " + str(elapsed_home)
       ...
 # Initialize depending on who has the starting kick
 if ball_away:
     start_away = time.time()
 else:
     home_start = time.time()
 body()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM