我正在尝试用python为下面的练习创建一个代码(供学校使用),我是stu

2024-04-24 23:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

创建一个程序来计算用户正确输入字母表所需的时间。它不会停止计时器,直到他们正确地键入它,如果他们犯了错误,它将显示一条消息,他们将不得不再次尝试键入它。一旦他们成功地输入了正确的字母表,它会告诉他们花了多长时间,然后问他们是否想再试一次,看看他们是否能打败上一次。你知道吗

我成功地完成了第一部分:

import time

starttime = time.time()

def ask_question1():
answer1= input("Type in the alphabet as fast as you can then press enter: ")
return answer1

if __name__=="__main__":
    answer1=ask_question1()
    while answer1 != "abcdefghijklmnopqrstuvwxyz":
        print("You made a mistake. ")
        answer1=input("Try again: ")

endtime=time.time()
print("It took you ",round(endtime-starttime, 2), " seconds")

但我不能让它再问一次问题,重复这个过程。你知道吗


Tags: 用户程序youinput键入timeas时间
3条回答

使用原始输入()而不是输入(),这将以字符串形式返回它。你知道吗

import time

starttime = time.time()

def ask_question1():
    return raw_input("Type in the alphabet as fast as you can then press enter: ")

if __name__=="__main__":
    while ask_question1() != "abcdefghijklmnopqrstuvwxyz":
        print("You made a mistake. ")

endtime=time.time()
print("It took you ",round(endtime-starttime, 2), " seconds")

似乎需要调用ask_question1而不是answer1=input("Try again: ")

  1. ask_question1函数不是必需的,您可以使用input 在Python3中或在Python2中raw_input

  2. 你不需要写"abcdefghijklmnopqrstuvwxyz",你可以用 ^Python 2中的{}或Python中的string.ascii_lowercase

  3. 你可以用while Truebrake创造一段时间 退出循环。

Python 2:

import time
import string

if __name__=="__main__":
    starttime = time.time()
    answer1 = raw_input("Type in the alphabet as fast as you can then press enter: ")
    while True:
        if answer1 != string.lowercase:
            print("You made a mistake. ")
            answer1 = raw_input("Try again: ")
        else:
            endtime = time.time()
            print("It took you " + str(round(endtime-starttime, 2)) + " seconds")
            break

Python 3:

import time
import string

if __name__=="__main__":
    starttime = time.time()
    answer1 = input("Type in the alphabet as fast as you can then press enter: ")

    while True:
        if answer1 != string.ascii_lowercase:
            print("You made a mistake. ")
            answer1=input("Try again: ")
        else:
            endtime=time.time()
            print("It took you ",round(endtime-starttime, 2), " seconds")
            break

相关问题 更多 >