Python开发猜数字游戏时循环无限输出Higher/Lower如何解决?
问题原因
- 死循环核心原因:
while循环内部没有新增输入来更新guess变量,程序一直使用首次输入的猜测值做判定,永远不会匹配目标数字,导致持续输出提示。 - 数值比较逻辑错误:判断两个整数是否相等不能用
is not,is/is not是用来判断对象内存地址是否一致的运算符,数值比较应该用!=。 - 业务逻辑分支错误:猜数字的全部逻辑应该包裹在用户同意玩游戏(e值为yes)的分支内,否则即使用户选择不玩,程序还是会要求输入猜测数字、进入循环。
- 判定顺序错误:
while循环的进入条件是guess不等于randnum,因此循环内部永远不会触发guess == randnum的分支,猜对后的提示逻辑应该放在循环结束后。
修复后的完整代码
import random print("Answer all questions with 'yes' or 'no' and press ENTER") print('Hello I am Jim the computer') z = input('How are you? ') if z.lower() in ['good', 'great']: print("That's great!") else: print("Oh. That's sad. I hope you feel better.") a = input("what's your name? ") print(a + "? Thats a nice name.") b = input('Do you own any pets? ') if b.lower() == 'yes': print("That's cool. I love pets!") else: print("That's a shame, you should get a pet. ") c = input("Do you like animals? ") if c.lower() == 'yes': print("Great! Me too!") else: print("Oh that's sad. They're really cute. ") d = input("Do you want to see a magic trick? ") if d.lower() == "yes": input("Ok! Think of a number between 1-30. Do you have it? ") print("Double that number.") print("Add ten.") print("Now divide by 2...") print("And subtract your original number!") y = input("Was your answer 5? ") if y.lower() == 'yes': print("Yay i got it right! I hope you like my magic trick.") else: print("Oh that's sad. I'll work on it. I really like magic tricks and games.") else: print("Ok. Maybe next time. I love magic tricks and games!") e = input("Do you want to play a game with me? ") if e.lower() == "yes": randnum = random.randint(1,100) print("I am thinking of a number between 1 and 100...") guess = int(input()) while guess != randnum: if guess < randnum: print("Higher.") if guess > randnum: print("Lower.") guess = int(input()) print("Nice guess " + a + "! Bye, have a nice day!") else: print("oh well see you next time" + a + '.')
内容的提问来源于stack exchange,提问作者MG195
相关产品推荐
相关产品推荐

