在使用“绝对初学者第三版的 Python 编程”一书学习 Python 的过程中,并努力应对已经设定的挑战。
我必须创建一个数字猜测程序,玩家选择一个数字,程序尝试通过选择一个随机数来猜测它,然后使用更高或更低的问题来接近数字。我已经弄清楚了大部分,但我正在为更高或更低的循环而苦苦挣扎。我遇到的麻烦是我无法让程序不高于或低于倒数第二个猜测,即
我的号码是 78 台计算机选择 50 我说较高的计算机选择 80 我说较低的计算机可以选择 12(当我不希望它低于 50 时。
我正在使用 Python 3.1
这是代码的副本。
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
提前感谢大家可以提供的任何帮助。
盟友