-1

My code is to find what position a word occurs in a list and I need it to not accept numbers as an input.

sentence = input("What is your sentence? ")
List1 = sentence.split(' ')
List1 = [item.lower() for item in List1]
word = input("What word do you want to find? ")
word = word.lower()
length = len(List1)

counter = 0

while counter < length:
    if word == List1[counter]:
        print("Word Found In Position ",counter)
        counter += 1
    elif word != List1[counter]:
        counter += 1
    else:
        print("That word is not in the sentence")

This is my current code. However, it still accepts numbers. I know that it is a similar question here: Asking the user for input until they give a valid response but I need it to fit with my existing code and I don't know how.

Community
  • 1
  • 1
  • 3
    There is no data type for this - what would be the purpose? You just need to check your input's characters and ensure there are no numbers before proceeding - if there are numbers you can throw an error of some sort, or demand new input. – miradulo Apr 17 '16 at 12:33

1 Answers1

0

Filter numbers from the list:

List1 = [s for s in List1 if not s.isdigit()]

Or raise an error if the length of:

[s for s in List1 if s.isdigit()]

is greater than 0.

EDIT

Added a better number check.

def isdigit(s):
    """Better isdigit that handles strings like "-32"."""
    try:
        int(s)
    except ValueError:
        return False
    else:
        return True

ADDED TO YOU CODE

while True:
    sentence = input("What is your sentence? ")
    List1 = sentence.split(' ')
    List1 = [item.lower() for item in List1]

    # Here is the check. It creates a new list with only the strings
    # that are numbers by using list comprehensions.
    #
    # So if the length of the list is greater then 0 it means there
    # are numbers in the list.
    if len([s for s in List1 if isdigit(s)]) > 0:
        print('You sentence contains numbers... retry!')
        continue

    word = input("What word do you want to find? ")
    word = word.lower()
    length = len(List1)

    counter = 0

    while counter < length:
        if word == List1[counter]:
            print("Word Found In Position ",counter)
            counter += 1
        elif word != List1[counter]:
            counter += 1
        else:
            print("That word is not in the sentence")
totoro
  • 2,469
  • 2
  • 19
  • 23