我会重新安排一下你的代码,这样它就不会偏离你所做的太远。在from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
您可以在一个循环中组合这些代码,以避免重复代码:
^{pr2}$
也许,要打印您想要的结果,例如YNNY,如下所示:result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
如果您想要更简洁的代码,请使用Python的三元运算:result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
或者使用True == 1和{}作为索引:result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))