Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 inconsistent map() behavior
#1
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
Quote
#2
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)
Quote
#3
@GOTO10 With isalpha() I don't need number_list! Thanks!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  HELP TabError: inconsistent use of tabs and spaces in indentation blackjesus24 2 381 Jan-30-2020, 10:25 AM
Last Post: blackjesus24
  Python function returns inconsistent results bluethundr 4 423 Dec-21-2019, 02:11 AM
Last Post: stullis
  inconsistent processing of list of tuples PyFool 4 828 Nov-05-2018, 05:24 PM
Last Post: PyFool
  [inconsistent output] subprocess.call to run cmd commands to get Kerberos ticket Yelin 2 1,614 Jun-08-2018, 09:02 AM
Last Post: Yelin

Forum Jump:


Users browsing this thread: 1 Guest(s)