如何简化含多个or操作的if语句?Python终端游戏代码优化求助
优化终端游戏gold_room函数的数字输入判断
你的原始代码里判断输入是否包含数字的逻辑不仅冗长,还存在漏洞(比如输入"a1b"这类包含数字但非纯数字的内容也会被误判为有效输入)。下面给你两种简洁且更可靠的优化方案,同时解释为什么range()不适合这个场景:
方案1:使用字符串的isdigit()方法
字符串的isdigit()方法可以直接判断整个字符串是否由纯数字组成,是最适合新手的简洁方案:
def gold_room(): print("This room is full of gold. How much do you take?") choice = input("> ") if choice.isdigit(): how_much = int(choice) else: dead("Man, learn to type a number.") if how_much < 50: print("Nice, you're not greedy, you win!") exit(0) else: dead("You greedy bastard!")
方案2:使用try-except捕获转换异常
这种方法更健壮,能处理所有整数转换失败的情况(比如输入负数、小数、非数字字符等),适合需要严格校验的场景:
def gold_room(): print("This room is full of gold. How much do you take?") choice = input("> ") try: how_much = int(choice) except ValueError: dead("Man, learn to type a number.") if how_much < 0: dead("You can't take negative gold!") elif how_much < 50: print("Nice, you're not greedy, you win!") exit(0) else: dead("You greedy bastard!")
为什么range()在这里不适用?
你尝试用range()报错的核心原因是类型不匹配:range()生成的是整数序列,而input()获取的是字符串类型,直接用choice in range(...)会因为两种类型无法比较而报错。就算你想先把choice转成整数,也得先确保它能被成功转换,这就回到了最初的校验问题,所以range()并不适合用来判断输入是否为数字。
内容的提问来源于stack exchange,提问作者the_black_dragon
相关产品推荐
相关产品推荐

