Python数字猜谜游戏中如何比较用户输入与随机函数返回值
报错根本原因
guess not defined报错:high_low函数的作用域内没有定义guess变量,你调用new_guess()后没有将返回的用户猜测值赋值给变量,循环内直接调用guess自然找不到对应变量。- 函数实例对比报错:你把
random_int、new_guess这两个函数名直接作为参数传入high_low,全程没有调用函数获取返回值,相当于拿两个函数对象做大小对比,自然触发类型不支持的报错。
其他需要修正的逻辑问题
new_guess函数中input()返回的是字符串类型,没有转换为整数,和数字对比会触发类型错误- 全局变量
attempts在函数内修改需要加global声明,否则会报局部变量未初始化错误 win函数不需要while循环,判断用户是否重开的input()没有赋值给变量直接判断,Y/N是字符串需要加引号包裹main函数中调用random_int(1000)、new_guess()后没有存储返回值,直接丢弃了生成的随机数和用户第一次输入的猜测值
修正后完整代码
# Python 数字猜谜游戏 from random import randrange def random_int(size): return randrange(1, size+1) def new_guess(): guess = int(input("请输入你的猜测(1到1000之间):")) return guess def high_low(target_num, guess_num, attempts): if guess_num > target_num: print("你猜的数字太大了,再试一次。") attempts += 1 return False, attempts elif guess_num < target_num: print("你猜的数字太小了,再试一次。") attempts += 1 return False, attempts else: attempts += 1 return True, attempts def win(attempts): if attempts >= 2: print(f"恭喜你猜对了!你一共用了{attempts}次机会。") else: print(f"恭喜你猜对了!你一共用了{attempts}次机会。") restart = input("你想要再玩一次吗?(Y/N):").strip().upper() if restart == "Y": main() else: exit() def main(): target = random_int(1000) attempts = 0 while True: guess = new_guess() is_win, attempts = high_low(target, guess, attempts) if is_win: break win(attempts) if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Fuji
相关产品推荐
相关产品推荐

