Python Forum
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
Reply
#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)
Reply
#3
@GOTO10 With isalpha() I don't need number_list! Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read csv file with inconsistent delimiter gracenz 2 1,149 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Inconsistent loop iteration behavior JonWayn 2 955 Dec-10-2022, 06:49 AM
Last Post: JonWayn
  ValueError: Found input variables with inconsistent numbers of samples saoko 0 2,433 Jun-16-2022, 06:59 PM
Last Post: saoko
  Loop Dict with inconsistent Keys Personne 1 1,579 Feb-05-2022, 03:19 AM
Last Post: Larz60+
  Inconsistent counting / timing with threading rantwhy 1 1,720 Nov-24-2021, 04:04 AM
Last Post: deanhystad
  Inconsistent behaviour in output - web scraping Steve 6 2,446 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Found input variables with inconsistent numbers of samples: [1000, 200] jenya56 2 2,807 Sep-15-2021, 12:48 PM
Last Post: jenya56
  Packages inconsistent warning during hdbscan install Led_Zeppelin 0 1,885 Aug-31-2021, 04:10 PM
Last Post: Led_Zeppelin
  HELP TabError: inconsistent use of tabs and spaces in indentation blackjesus24 2 3,517 Jan-30-2020, 10:25 AM
Last Post: blackjesus24
  Python function returns inconsistent results bluethundr 4 3,138 Dec-21-2019, 02:11 AM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020