簡體   English   中英

如何在python中的另一個def函數中運行一個def函數?

[英]How do I run one def function inside of a different def function in python?

我正在嘗試在代碼功能內運行計時器。 我需要在用戶開始輸入之前先啟動計時器,然后在用戶正確輸入字母后停止計時器。 這是我的代碼:

import time
timec = 0
timer = False

print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed")
timer = True
attempt = input("The timer has started!\nType here: ")

while timer == True:
    time.sleep(1)
    timec = timec +1


if attempt == "abcdefghijklmnopqrstuvwxyz":
    timer = False
    print("you completed the alphabet correctly in", timec,"seconds!")
else:
    print("There was a mistake! \nTry again: ")

問題是它不會讓我輸入字母。 在此代碼的先前嘗試中(我沒有),我已經能夠輸入字母,但是計時器不起作用。 任何幫助表示贊賞

import time

start = time.time()
attempt = input("Start typing now: ")
finish = time.time()

if attempt == "abcdefghijklmnopqrstuvwxyz":
    print "Well done, that took you %s seconds.", round(finish-start, 4)
else:
    print "Sorry, there where errors."

慎重考慮你是董

  1. 您要求輸入用戶輸入的字符串
  2. timer等於True ,您睡眠一秒鍾並增加計數。 在此循環中,您無需更改timer

顯然,一旦用戶停止輸入字母並按Enter,就開始無限循環。 因此,似乎什么也沒發生。

正如其他答案所建議的那樣,最好的解決方案是在提示用戶輸入字母之前將時間保存下來,並將其與完成后的時間進行比較。

您可以執行以下操作:

import datetime

alphabet = 'abcdefghijklmnopqrstuvwxyz'

print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"')
init_time = datetime.datetime.now()
success_time = None

while True:
    user_input = input('The timer has started!\nType here: ')
    if user_input == alphabet:
        success_time = datetime.datetime.now() - init_time
        break
    else:
        continue

print('you did it in %s' % success_time)

暫無
暫無

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

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