Home > OS >  Append variable to list in loop
Append variable to list in loop

Time:12-04

I want to append the "input number" to the "list_of_already_entered_numbers" if the number is not in the list before. You should therefore not be able to state the same number 2 times. I added "print" to show that the list is still empty? even though "append" should add the number to the list during each iteration. Never mind the 10 iterations. So how do I append the number to the list so that the list is renewed each iteration?

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()

CodePudding user response:

Declare the list outside of the loop like this:

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()

CodePudding user response:

You might try breaking out only the asking portion into it's own function. This makes it easier to try by itself, and ensure that you are getting the expected result:

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()

In this manner you encapsulate the starting state and can ensure each iteration is doing exactly what you expect.

CodePudding user response:

I don’t see any append has taken place here … But for your question: You could simply use another loop on top of your main loop and define the list in the first loop.

  • Related