Home > other >  How to use the same code but with different variables
How to use the same code but with different variables

Time:04-26

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?

CodePudding user response:

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!

CodePudding user response:

Create the list in a function (returning the list). Call the function with the number of integers required.

def get_ints(n):
  result = []
  while len(result) < n:
    try:
      v = int(input('Enter a number: '))
      result.append(v)
      print(f'Number {v} added')
    except ValueError:
      print('Integers only please')
  return result

Thus, if you want a list of 5 numbers then:

list_of_numbers = get_ints(5)

  
  • Related