You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:输入无效值触发if后如何终止代码,停止后续执行?

解决Python输入无效值后终止程序的问题

方法一:用sys.exit()直接终止程序

导入sys模块,在输入无效时调用sys.exit(),程序会立刻停止,不再执行后续代码:

import sys
import random

# 假设rock、paper、scissors是已定义的图片变量
images = [rock, paper, scissors]

person = int(input("What do you chose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

if person >=3 or person < 0:
    print("You typed an invalid number,please choose 0,1 or 2")
    sys.exit()  # 终止程序

# 仅输入有效时执行以下代码
print(images[person])
computer = random.randint(0, 2)
print("Computer chose:")
print(images[computer])

方法二:把有效逻辑全部放入else块

将原本在else外的代码移到else内部,输入无效时只会执行提示,不会触发后续逻辑:

import random

images = [rock, paper, scissors]

person = int(input("What do you chose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

if person >=3 or person < 0:
    print("You typed an invalid number,please choose 0,1 or 2")
else:
    print(images[person])
    computer = random.randint(0, 2)
    print("Computer chose:")
    print(images[computer])

为什么循环+break没起作用?

break只能跳出当前所在的循环结构,你原代码里没有循环,所以break根本无法生效。如果想实现让用户重新输入直到有效,可以用循环改写:

import random

images = [rock, paper, scissors]

while True:
    person = int(input("What do you chose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
    if 0 <= person <=2:
        break  # 输入有效,跳出循环
    print("You typed an invalid number,please choose 0,1 or 2")

# 循环结束后执行后续逻辑
print(images[person])
computer = random.randint(0, 2)
print("Computer chose:")
print(images[computer])

内容的提问来源于stack exchange,提问作者Cornelbn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:25:11