Python Forum

Full Version: inconsistent map() behavior
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to use map() and range() to make a list of numbers that return as strings. I want to use it to make sure users don't enter numbers when they are supposed to enter letters. I wrote an if/else to test it but sometimes I'll enter
a number and it prints the error but sometimes it prints the number. Is it because it's in a While Loop? I have tried changing line 6 to if enter in str(number_list): but it doesn't make much difference.

number_list = map(str, range(0, 10))

while True:
    enter = input("Enter a letter. ")

    if enter in number_list:
        print("Error!")
    else:
        print(enter)
Output:
Enter a letter. 0 Error! Enter a letter. 9 9 Enter a letter. 8 Error! Enter a letter. 3 3
Since you are trying to make a list, use list() to convert your map object into a list:
number_list = list(map(str, range(0, 10)))
However, since your list only includes strings for single digits 0 through 9, entering a float (like 1.0) or any multi-digit number (11) would not produce the error warning. The code below will return an error for anything other than a single letter (upper or lower case is not considered):
while True:
    enter = input("Enter a letter. ")

    if not enter.isalpha() or len(enter)> 1:
        print('Error!')
    else:
        print(enter)
@GOTO10 With isalpha() I don't need number_list! Thanks!