简体   繁体   中英

Why is KeyboardInterrupt not outputting an if-else loop?

So I have this code for a little game that I wanted to make, but the output with keyboardinterrupt isn't working. I'm kind of a noob in python, so I'm open to any suggestions to fix up my code.

Code:

"""
GAME
number 1-20 rapidly listing
if press Ctrl+C on 10, then win
if not, then lose and restart
"""

import time

print("Type Ctrl+C to stop")
print("If you land on 10, you win!")
time.sleep(2)
i_dict = {1: 14, 2: 13, 4: 11}
dict_num = 0
while True:

    try:
        for i in range(1, 21):
            print(i)
            time.sleep(0.07)
    except KeyboardInterrupt:
        i_dict[dict_num + 1] = i
        if i == 10:
            print("You Win! Nice Job!")
        else:
            print(f"You landed on {i}!")
        scores = input("Would you like to see your past scores?").lower()
        if scores == 'yes':
            for num, score in i_dict.items():
                print(f"{num}: {score}")
        restart = input("Would you like to try again? Answer with Yes or No: ").lower()
        if restart == 'yes':
            break

Output when I press Cntrl+C:

----------FINISHED----------
exit code: 2 status: 0

So instead of using the keyboard interrupt as import I switched it to use the keyboard module, install it if you don't have it already by doing pip install keyboard or pip3 install keyboard if you are running linux you may have to run python as sudo, if you're not on linux don't worry about it. Here's the somewhat improved code. Happy coding!

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
   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM