Alfred H. Alfred H. - 1 month ago 19
Python Question

Creating a function that makes a list of integers

I am trying to create a function that takes in a sentinel value (an integer), and returns a list of integers. The function prompts the user to create a list of integers, using the provided sentinel value as the number the user enters to
exit the creation of the list. For answers please make it as simple as possible refrain from using any technique that is too advanced as I am still learning Python and do not want to jump too far ahead...

def createIntList():
createlist = []
while myInt != addNum: #having problems around here!!
myInt = input("What do you want the sentinel to be?")
addNum = input("Please enter a number, ", myInt, "to stop: ")
createlist.append(addNum)
return createlist

Answer

this is really what iter is for , which can take as its first argument a function that takes no arguments and returns a value, and for its second argument a sentinal value that tells it when to stop

def get_int(prompt="Enter a number:"): 
    return input(prompt)

sentinal = input("Enter your sentinal:")
print( list(iter(get_int,sentinal)) )

alternatively you could write a method to accept the data until your sentinal is reached...

def input_until(prompt,sentinal):
   a = []
   while True:
       tmp = input(prompt)
       if tmp == sentinal: return a
       a.append(tmp)

the smallest change you could make to your existing code is

def createIntList():
    createlist = []
    #define both variables before your loop
    myInt = input("What do you want the sentinel to be?")
    addNum = None
    while myInt != addNum: #having problems around here!!
        #dont ask each time for a new sentinal...
        addNum = input("Please enter a number, "+ str(myInt)+ " to stop: ")
        createlist.append(addNum) # append your values inside the list...
    return createlist