if 语句在 while 循环中部分工作

时间:2021-06-14 20:37:42

标签: python

所以我正在做一项练习来练习 Python(对不起,伙计们,只是在学习)。练习是要求在 while 循环中进行。所以我做了,不幸的是,它不能完全工作,我不知道为什么,因为我做的类似练习工作正常(在 while 循环中以及使用键盘)。

import keyboard
    
while True:
    if keyboard.is_pressed('1'):
        try:
            speed_1 = int(input('What was your speed an hour? '))
            time_1 = int(input('For how long have you been driving? Please input your time in minutes. '))
            distance_1 = (speed_1 / 60) * time_1
            print('Distance you have traveled is ' + str(round(distance_1, 2)) + ' km.')
            break
        except ValueError:
            print('You need to use numbers.')
    elif keyboard.is_pressed('2'):
        try:
            distance_2 = int(input('How far do you want travel? Enter in km. '))
            time_2 = int(input('How long do you have to get there? Enter in minutes. '))
            speed_2 = time_2 / distance_2 * 100
            print('You need to drive ' + str(round(speed_2, 2)) + ' km/h to get there on time.') 
            break
        except ValueError:
            print('You need to use numbers.')
    elif keyboard.read_key() != '1' and keyboard.read_key() != '2':
        break

如您所见,这是一个基本的速度、距离计算器。如果我按一个它会起作用,如果我按 2 它根本不起作用..只是卡住什么都不做,按任何其他键都可以正常工作..它会关闭一个程序。我做错了什么?有任何想法吗?我知道这可能不值得浪费我的时间,因为它只是锻炼,但我试图找出为什么我不能这样做,以及为什么除了按 2 之外它还能正常工作.

编辑: 刚刚意识到,如果我按 2 什么都不会发生,但是如果我在按 2 后按 1 或任何其他按钮,它将继续执行 if 或关闭程序。

1 个答案:

答案 0 :(得分:0)

很少有方法,我确实做到了。以前它可能不起作用,好像语句与 keyboard.is_pressed 结合起来不太好。它可能会使用 100% 的 CPU 或只是卡住(根据我在网上找到的信息)。

import keyboard

print('If you want me to tell you how far you traveled, press 1.')
print('If you want to find out how fast you need to drive to get somewhere on time, press 2. ')

def on_1():
    try:
        speed_1 = int(input('What was your speed an hour? '))
        time_1 = int(input('For how long have you been driving? Please input your time in minutes. '))
        distance_1 = (speed_1 / 60) * time_1
        print('Distance you have traveled is ' + str(round(distance_1, 2)) + ' km.')
    except ValueError:
        print('You need to use numbers.')
    
def on_2():
    try:
        distance_2 = int(input('How far do you want travel? Enter in km. '))
        time_2 = int(input('How long do you have to get there? Enter in minutes. '))
        speed_2 = distance_2/ time_2 * 60
        print('You need to drive ' + str(round(speed_2, 2)) + ' km/h to get there on time.')
    except ValueError:
        print('You need to use numbers.')

keyboard.add_hotkey('1', on_1)
keyboard.add_hotkey('2', on_2)

while True:
    try:
        if keyboard.wait('1'):
            break
        elif keyboard.wait('2'):
            break
    finally:
        break

这是一个实际有效的代码。发布以防万一将来其他人会遇到类似的问题。 另外,我修复了“2”的计算。之前没有意识到我已经反过来做了。

相关问题