我使用的是Walrus操作员。我让用户猜测一个介于0和10之间的数字。然后,他们的猜测被添加到一个充满他们猜测的列表中。但一旦他们输入了0,它就会打印出列表。
我遇到的问题是第一个猜测没有被列入名单。每次添加值时,我都尝试打印出列表,但列表中不包括第一个输入。如何让Walrus运算符将第一个值附加到我的列表中?
这是我的代码:
import traceback
def checkAnswerWalrus():
listOfGuesses = []
while (numberGuessed := int(input(f"Guess a number between 0 to 10 : "))) != 0:
listOfGuesses.append(numberGuessed)
print(listOfGuesses)
if numberGuessed == 0:
print(listOfGuesses)
return(True)
if __name__ == "__main__":
try:
numberGuessed = int(input(f"Guess a number between 0 to 10 : "))
checkAnswerWalrus()
except Exception as error:
traceback.print_exc()
finally:
print(f":)")
以下是示例输出;2〃;没有附加到列表中:
C:/Python3.8/python.exe c:/Users/mayab/Desktop/ict/python/misc/testWalrus.py
Guess a number between 0 to 10 : 2
Guess a number between 0 to 10 : 3
[3]
Guess a number between 0 to 10 : 4
[3, 4]
Guess a number between 0 to 10 : 5
[3, 4, 5]
Guess a number between 0 to 10 : 6
[3, 4, 5, 6]
Guess a number between 0 to 10 : 7
[3, 4, 5, 6, 7]
Guess a number between 0 to 10 : 0
[3, 4, 5, 6, 7]
:)
会询问第一个问题,并在try
部分中输入第一个数字,在该部分中,您不会将值附加到列表中。只需移除它,让checkAnswerWalrus()
完成整个工作。