Home > Back-end >  Python: Let use re-enter input if not string and convert user input to lower case
Python: Let use re-enter input if not string and convert user input to lower case

Time:12-27

I'm new to python, I have a dataset I'm working with, a column consist of strings like (Blue, Red, Gold, White). I want the user to enter any of these values but I want to make the user input to be case insensitive and reject integer input, that is, if user input "bLue"/"blUe", it should accept the input and if the user enters "7"/"-4"/"0" it should prompt user to re-enter a string value.

def user():
    while True:
        try:
            print(f"Blue, Red, Gold, White, Black, Brown")
            user = input("Enter a color: ")
        except ValueError:
            print("Please enter a valid input")
            continue
        else:
            break
    return user

When a user enters a number like 3,2,-1,0 it just returns the number, I want it to reject the user input and tell the user to input a string instead , I also want the string input to be non-case sensitive. Thanks

CodePudding user response:

 def user():
    while True:
        colors = ["blue", "red", "gold", "white", "black", "brown"]
        print(", ".join(colors))
        user_input = input("Enter a color: ").lower()
        if user_input in colors:
            break
        else:
            print("Please enter a valid input")
    return user_input

I think you are making this more complicated than it needs to be. This should work for what you have described. Let me know if anything else needs to be changed.

CodePudding user response:

I hope, it works for your solution,

import re
def user():
    while True:
        print(f"Blue, Red, Gold, White, Black, Brown")
        user = input("Enter a color: ").lower()
        if len(re.findall('.?-?[0-9] ', user)) > 0:
            print("Please enter a valid input, don't pass an number value")
            continue
        if user not in ['blue', 'red', 'gold', 'white', 'black', 'brown']:
            print('Please only enter')
            continue
        else:
            break
    return user
user()

CodePudding user response:

You can do without use of try except.

def user():
    lis=['blue', 'red', 'gold', 'white', 'black', 'brown']
    while True:
        user_enter=input("Enter the colour: ").lower()
        if user_enter not in lis:
            print("Please provide valid colour input!!")
            continue
        else:
            break
    return user_enter
print("User provided the color: ",user())
  • Related