A. Gunter
A. Gunter

Reputation: 112

Creating a list of five numbers

I'm trying to have Python prompt the user to pick five numbers and store them in the system. So far I have:

def main():
    choice = displayMenu()
    while choice != '4':
        if choice == '1':
            createList()
        elif choice == '2':
            print(createList)
        elif choice == '3':
            searchList()
        choice = displayMenu()

    print("Thanks for playing!")


def displayMenu():
    myChoice = '0'
    while myChoice != '1' and myChoice != '2' \
                  and myChoice != '3' and myChoice != '4':
         print ("""Please choose
                        1. Create a new list of 5 integers
                        2. Display the list
                        3. Search the list
                        4. Quit
                        """)
         myChoice = input("Enter option-->")

         if myChoice != '1' and myChoice != '2' and \
            myChoice != '3' and myChoice != '4':
             print("Invalid option. Please select again.")

    return myChoice 

#This is where I need it to ask the user to give five numbers 

def createList():
    newList = []
    while True:
        try:
            num = (int(input("Give me five numbers:")))
            if num < 0:
                Exception

            print("Thank you")
            break
        except:
            print("Invalid. Try again...")

    for i in range(5):
        newList.append(random.randint(0,9))
    return newList

Once I run the program it allows me to choose option 1 and asks the user to enter five numbers. However if I enter more than one number it says invalid and if I only enter one number it says thank you and displays the menu again. Where am I going wrong?

Upvotes: 1

Views: 1202

Answers (3)

Dmitry Shilyaev
Dmitry Shilyaev

Reputation: 733

Use raw_input() instead of input().

With Python 2.7 input() evaluates the input as Python code, that is why you got error. raw_input() returns the verbatim string entered by the user. In python 3 you can use input(), raw_input() is gone.

    my_input = raw_input("Give me five numbers:")  # or input() for Python 3
    numbers = [int(num) for num in my_input.split(' ')]
    print(numbers)

Upvotes: 1

Carles Mitjans
Carles Mitjans

Reputation: 4866

numbers = [int(x) for x in raw_input("Give me five numbers: ").split()]

This will work assuming the user inputs the numbers separated by blank spaces.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

@DmitryShilyaev has properly diagnosed the problem. If you want to read 5 numbers in a single line, you could use split to split the string that input returns, and convert each element of that list to an int.

Upvotes: 0

Related Questions