我是学习Python的新手,我正在构建一个非常简单的猜数游戏。用户猜测1-100之间的数字,并且给出关于他们的猜测是否太低或太高的反馈。当他们正确猜出数字时,程序会告诉他们他们采取了多少猜测。我需要帮助的是:告诉用户他们猜到重复号码的时间是否已经输入。我还想排除最终猜测计数中的任何重复猜测。最简单的方法是什么?
到目前为止,这是我的游戏:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
答案 0 :(得分:0)
跟踪猜测的数字,只有在用户没有猜到我们猜测的数字中已有数字时才会增加:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
你也有一些关于你的排序的逻辑,比如在循环外猜测,这可能意味着如果用户第一次猜到你就没有进入循环。
答案 1 :(得分:0)
这就是你应该如何编写代码。
UDPClient