Home > Net >  I'm trying to make a user enter 10 names and make them into a list and remove the even words in
I'm trying to make a user enter 10 names and make them into a list and remove the even words in

Time:04-07

name1 = str (input("Please Enter a Name:"))

lista = []
lista.append(name1)
if name1 % 2 == 0:
    lista.remove(name1)

this is the part where my code messes up it says " TypeError: not all arguments converted during string formatting"

CodePudding user response:

lista = []
for i in range(10):
    lista.append(str(input("Please Enter a Name:")))

for name in lista:
    if len(name) % 2 == 0:
        lista.remove(name)

# driver code to test
print(lista)

Example input: a b cc d gg e ggg ff

Output: ['a', 'b', 'd', 'e', 'ggg']

However, this could be even more simplified, by checking the length of provided input as it's provided, and adding only odd-length words instead. Saves you one loop. Here's the code:

lista = []
for i in range(10):
    word = str(input("Please Enter a Name:"))
    if not len(word) % 2 == 0:
        lista.append(word)

# driver code to test
print(lista)

CodePudding user response:

The error here is that the % operator on a str is for formatting; the arguments to the operator (everything to the right of it) need to correspond to formatting directives inside the string. You're trying to use it as the int modulus operator, which doesn't work because it's a str.

If your intent is to filter based on whether the length of the string is odd or even, use the len() function on the string, as others have suggested:

odd_names = []
for _ in range(10):
    n = input("Please Enter a Name:")
    if len(n) % 2:
        odd_names.append(n)

Note that you don't need to convert the result of input() to a str, and that you can simply use len(n) % 2 to see if len(n) is odd (because 1 is true and 0 is false).

With a reasonably current version of Python you can do this all in a single easy list comprehension:

odd_names = [n for _ in range(10) if len(n := input("Please Enter a Name:")) % 2]
  • Related