Search code examples
pythonlistvariablesnumbersvalueerror

How to use the same code but with different variables


I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.

Something like this:

numbers = []
num1 = input("Enter the first number: ")
try:
    check = int(num1)
    numbers.append(num1)
    print("The number {} has been added.".format(num1))
except ValueError:
    print("Please, enter a number")

I have to do the same for several numbers, but the variables are different, like here:

num2 = input("Enter the next number: ")
try:
    check = int(num2)
    numbers.append(num2)
    print("The number {} has been added.".format(num2))
except ValueError:
    print("Please, enter a number")

Is there any way to create a code that does always the same process, but only changing the variable?


Solution

  • If you are trying to continue adding numbers without copying your code block over and over, try this:

    #!/usr/bin/env python3
    
    while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
        num2 = input("Enter the next number: ")
        try:
            check = int(num2)
            numbers.append(num2)
            print("The number {} has been added.".format(num2))
        except ValueError:
            print("Please, enter a number")
    

    Hopefully this is helpful!