Counting arguments in lists and printing lists

394 views Asked by At

I want users to enter random words/numbers/phrases. If they have entered more then 5 then they get an error message and if the enter 5 or less then I print out the list vertically. I don't know what code to use so that it does not count the white spaces. As well, I want to count the number of words/numbers, NOT the amount of characters. If you could just take a look at my code and give some help, that would be great!

myList = [] 

myList = raw_input("Enter words,numbers or a phrase (a phrase should be entered between two quotations)...")

if len(myList) > 5:
print('Error')

else:
#print output
for variable in L:
    print variable
2

There are 2 answers

0
Sash Sinha On

Try something like this using str.split() to return a list of the words in the string using the default delimiter of a space character:

myList = []

while(True):
    myList = raw_input("Please enter words or numbers: ")
    if(len(myList.split())) <= 5:
        break
    else:
        print("Error: You entered more than 5 arguments, Try again...")

for item in myList.split():
    print(item)

Try it here!

2
XzAeRo On

The working code for what you want is the following:

# I separate the input text by the spaces
data = raw_input("Enter something... ").split(" ")

# handle the data
if len(data) > 5:
    print("Only 4 or less arguments allowed!")
else:
    for variable in data:
        print(variable)

Now, this doesn't prevent the user from inserting other characters like !, $%"#$, so to handle that case, you should check for some of the answers in this question: Stripping everything but alphanumeric chars from a string in Python

Have fun!