Python猜数字游戏循环异常 始终复用首次输入值问题排查
问题描述
请多包涵,我是一名编程初学者。
以下是我编写的简易版本猜数字游戏代码,我知晓该程序存在更高效的实现方式,但希望能获得帮助,定位代码运行异常的原因:无论我输入h还是l,程序始终基于我第一次输入的字符执行循环逻辑,无法响应后续输入的新指令。
原实现代码:
high = 100 low = 0 guess = ((low + high) / 2) print("Please think of a number between" + str(high) + " and " + str(low)) answer = input("Is your secret number " + str(guess) + "?\n" "Enter 'h' to indicate the guess is " "too high. Enter 'l' to indicate the guess " "is too low. Enter 'c' to indicate I " "guessed correctly.") while guess != 0: if answer == "h": high = guess guess = ((low + high) / 2) input("Is your secret number " + str(guess) + "?\n" "Enter 'h' to indicate the guess is " "too high. Enter 'l' to indicate the guess " "is too low. Enter 'c' to indicate I " "guessed correctly.") elif answer == "l": low = guess guess = ((low + high) / 2) input("Is your secret number " + str(guess) + "?\n" "Enter 'h' to indicate the guess is " "too high. Enter 'l' to indicate the guess " "is too low. Enter 'c' to indicate I " "guessed correctly.") elif answer == "c": print("Game over. Your secret number was " + str(guess)) break else: print("Sorry, I did not understand your input." "Is your secret number " + str(guess) + "?\n" "Enter 'h' to indicate the guess is " "too high. Enter 'l' to indicate the guess " "is too low. Enter 'c' to indicate I " "guessed correctly.")
故障原因
核心问题只有一个:你在循环内调用input()获取用户新输入时,没有把返回值重新赋值给answer变量。
程序第一次进入循环前,answer只被赋值过一次,保存的是你第一次输入的内容。后续循环里你虽然调用了input()让用户输入新字符,但输入的内容没有存到answer里,判断逻辑永远拿第一次的输入值做比较,自然不会响应后续的新指令。
除此之外代码还有4个小问题:
- 初始提示的数字范围写反了,显示的是
between 100 and 0 - 非法输入分支只打印了提示,没有重新接收用户输入,会触发死循环
- 用普通除法
/计算猜测值会得到浮点数,猜整数场景下用整数除法//更合理,不会出现带小数点的猜测值 - 循环终止条件
guess != 0没有实际意义,当用户输入c时直接通过break退出循环即可,用while True写无限循环更简洁,也不会出现猜数字0时意外退出的问题
修正后代码
high = 100 low = 0 guess = (low + high) // 2 print(f"Please think of a number between {low} and {high}") answer = input(f"Is your secret number {guess}?\n" "Enter 'h' to indicate the guess is too high. " "Enter 'l' to indicate the guess is too low. " "Enter 'c' to indicate I guessed correctly.") while True: if answer == "h": high = guess guess = (low + high) // 2 answer = input(f"Is your secret number {guess}?\n" "Enter 'h' to indicate the guess is too high. " "Enter 'l' to indicate the guess is too low. " "Enter 'c' to indicate I guessed correctly.") elif answer == "l": low = guess guess = (low + high) // 2 answer = input(f"Is your secret number {guess}?\n" "Enter 'h' to indicate the guess is too high. " "Enter 'l' to indicate the guess is too low. " "Enter 'c' to indicate I guessed correctly.") elif answer == "c": print(f"Game over. Your secret number was {guess}") break else: answer = input("Sorry, I did not understand your input.\n" f"Is your secret number {guess}?\n" "Enter 'h' to indicate the guess is too high. " "Enter 'l' to indicate the guess is too low. " "Enter 'c' to indicate I guessed correctly.")
内容的提问来源于stack exchange,提问作者Trubulica
相关产品推荐
相关产品推荐

