Python 为什么键盘中断不输出if-else循环?
我有一个小游戏的代码,我想做,但是键盘中断的输出不起作用。我有点像python的noob,所以我愿意接受任何修改代码的建议 代码: 按下Cntrl+C时的输出:Python 为什么键盘中断不输出if-else循环?,python,keyboardinterrupt,Python,Keyboardinterrupt,我有一个小游戏的代码,我想做,但是键盘中断的输出不起作用。我有点像python的noob,所以我愿意接受任何修改代码的建议 代码: 按下Cntrl+C时的输出: ----------FINISHED---------- exit code: 2 status: 0 因此,我没有使用键盘中断作为导入,而是将其切换为使用键盘模块,如果您还没有键盘模块,请通过执行pip install keyboard或pip3 install keyboard来安装它。如果您运行的是linux,您可能必须像sud
----------FINISHED----------
exit code: 2 status: 0
因此,我没有使用键盘中断作为导入,而是将其切换为使用键盘模块,如果您还没有键盘模块,请通过执行
pip install keyboard
或pip3 install keyboard
来安装它。如果您运行的是linux,您可能必须像sudo一样运行python,如果您不在linux上,请不要担心。
下面是一些经过改进的代码。快乐编码
import keyboard
import time
print('Hit "F" to stop. ')
print("If you land on 10, you win!")
time.sleep(2)
print("Start!")
i_dict = {1: 14, 2: 13, 4: 11}
dict_num = 0
i = 0
while True:
if i != 21:
print(i)
time.sleep(0.07)
i += 1
if keyboard.is_pressed("f"):
i_dict[dict_num + 1] = i
if i == 10:
print("You Win! Nice Job!")
if i != 10:
print(f"You landed on {i}!")
i = 0
restart = input("Would you like to try again? Answer with Yes or No: ")
if restart.lower() == 'yes':
i = 0
elif restart.lower() == 'no':
print("Thanks for playing")
exit()
if i >= 21:
i = 0
我不能重复这个问题。我击中了两个
你在1上着陆代码>和你赢了!干得好代码>在单独的回合中。重新启动也起作用了。嗯,对我来说不起作用。可能是我的编辑器或计算机的问题?请注意,结尾处的pass
continue
break
语句顺序并不完全合理。它应该只是if
块中的一个中断
。“可能是我的编辑器或计算机的问题?”嗯,可能吧。这也解释了------------FINISHED------退出代码:2状态:0
输出。通过ipython和python,MacOS 10.14.6从控制台运行它。FWIW,代码中没有任何内容表明行为依赖于系统甚至版本。非常感谢!这真的很有帮助!
import keyboard
import time
print('Hit "F" to stop. ')
print("If you land on 10, you win!")
time.sleep(2)
print("Start!")
i_dict = {1: 14, 2: 13, 4: 11}
dict_num = 0
i = 0
while True:
if i != 21:
print(i)
time.sleep(0.07)
i += 1
if keyboard.is_pressed("f"):
i_dict[dict_num + 1] = i
if i == 10:
print("You Win! Nice Job!")
if i != 10:
print(f"You landed on {i}!")
i = 0
restart = input("Would you like to try again? Answer with Yes or No: ")
if restart.lower() == 'yes':
i = 0
elif restart.lower() == 'no':
print("Thanks for playing")
exit()
if i >= 21:
i = 0