如何建立一个while循环,当我到达程序中为自己设置的某个小时时停止(Python3)

2024-05-16 22:30:58 发布

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

Python 3.7版

我试着创建一个程序,在用户为自己设置之前向用户询问数学问题。 我希望代码是这样工作的:

while current_time != ending_time:
    #Do stuff

我的问题是如何设置current_timeending_time(我知道“dostuff”部分将如何工作)

所以,在小问题上:

1)我需要从哪个库导入哪个函数

2)如何要求用户输入停止练习的时间

3)如何设置一个变量来保存current_time


Tags: 函数代码用户程序timeending时间数学
2条回答

查看“时间”模块

import time

currentTime = time.time()

userInput = input("How long to practice?")

# Do some checks and math on userInput to get endTime.

while currentTime < endTime:
    currentTime = time.time()

以你喜欢的方式获取用户输入(可能使用input()?),并在结束时进行数学运算,并按照你的预期进行循环,但不使用相等的比较,因为如果使用浮点或纳秒,它永远不会是100%相同的

使用日期时间模式

from datetime import datetime, timedelta,date
start=datetime.now().time()
delta = timedelta(hours = 1) # hours will be user input
end=(datetime.combine(datetime.now(),start) + delta).time()
while start<=end:
    print('you got time :)')
# continue 

相关问题 更多 >