将变量附加到循环列表
Append variable to list in loop
如果号码不在之前的列表中,我想将“输入号码”附加到“list_of_already_entered_numbers”。因此,您不应该说出相同的数字 2 次。我添加了“打印”以显示列表仍然是空的?即使“附加”应该在每次迭代期间将数字添加到列表中。别介意 10 次迭代。那么如何将数字附加到列表中以便每次迭代更新列表?
def ask_number():
a = 0
while a < 10:
list_of_already_entered_numbers = []
print("this is the list: " + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in list_of_already_entered_numbers:
print("the number is already in the list")
else:
list_of_already_entered_numbers.append(number)
a+=1
ask_number()
像这样在循环外声明列表:
def ask_number():
a = 0
list_of_already_entered_numbers = []
while a < 10:
print("this is the list: " + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in list_of_already_entered_numbers:
print("the number is already in the list")
else:
list_of_already_entered_numbers.append(number)
a+=1
ask_number()
您可以尝试仅将询问部分分解为它自己的函数。这样可以更轻松地自行尝试,并确保您获得预期的结果:
from typing import List
def enter_number(previous_numbers: List[int]) -> List[int]:
print("These numbers have been guessed: {previous_numbers}" + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in previous_numbers:
print("That number has already been entered")
else:
previous_numbers.append(number)
return previous_numbers
def ask():
previous_numbers = []
for _ in range(10):
previous_numbers = enter_number(previous_numbers)
ask()
通过这种方式,您封装了起始状态,并可以确保每次迭代都完全按照您的预期进行。
如果号码不在之前的列表中,我想将“输入号码”附加到“list_of_already_entered_numbers”。因此,您不应该说出相同的数字 2 次。我添加了“打印”以显示列表仍然是空的?即使“附加”应该在每次迭代期间将数字添加到列表中。别介意 10 次迭代。那么如何将数字附加到列表中以便每次迭代更新列表?
def ask_number():
a = 0
while a < 10:
list_of_already_entered_numbers = []
print("this is the list: " + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in list_of_already_entered_numbers:
print("the number is already in the list")
else:
list_of_already_entered_numbers.append(number)
a+=1
ask_number()
像这样在循环外声明列表:
def ask_number():
a = 0
list_of_already_entered_numbers = []
while a < 10:
print("this is the list: " + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in list_of_already_entered_numbers:
print("the number is already in the list")
else:
list_of_already_entered_numbers.append(number)
a+=1
ask_number()
您可以尝试仅将询问部分分解为它自己的函数。这样可以更轻松地自行尝试,并确保您获得预期的结果:
from typing import List
def enter_number(previous_numbers: List[int]) -> List[int]:
print("These numbers have been guessed: {previous_numbers}" + str(list_of_already_entered_numbers))
number = int(input("Type a number:"))
if number in previous_numbers:
print("That number has already been entered")
else:
previous_numbers.append(number)
return previous_numbers
def ask():
previous_numbers = []
for _ in range(10):
previous_numbers = enter_number(previous_numbers)
ask()
通过这种方式,您封装了起始状态,并可以确保每次迭代都完全按照您的预期进行。