Search code examples
pythonif-statementdictionaryraw-input

Check raw_input for dictionary


I looked on stackoverflow to solve my problem but from all explanations about loops and checks I don't understand why my code isn't working. So I want to build a dictionary (totally new to Python btw) and I read that I can also check if the input is in the dicitonary module but that is actually not what I want to do here. I just want to see if the raw_input contains at least one number in the string (not if the string only contains numbers) and if the length of the input string is at least 2. If the input passes those checks it should move on (the rest of this dictionary will come later. For now I only want to understand what I did wrong with my check) Here's my code, help would be very much appreciated!

def check():
    if any(char.isdigit() for char in original):
        print ("Please avoid entering numbers. Try a word!")
        enter_word()
    elif len(original)<1:
        print ("Oops, you didn't enter anything. Try again!")
        enter_word()

    else:
        print ("Alright, trying to translate:")
        print ("%s") %(original)

def enter_word():
    original = raw_input("Enter a word:").lower()
    check()

enter_word()

Edit: Works now perfectly with the following code:

def check(original):
    if any(char.isdigit() for char in original):
        print "Please avoid entering numbers. Try a word!"
        enter_word()
    elif len(original) < 1:
        print "Oops, you didn't enter anything. Try again!"
        enter_word()
    else:
        print "Alright, trying to translate:"
        print "{}".format(original)

def enter_word():
    original = raw_input("Enter a word:").lower()
    check(original)

enter_word()

Solution

  • You need to pass the input original to your check() function:

    def check(original):
        if any(char.isdigit() for char in original):
            print("Please avoid entering numbers. Try a word!")
            enter_word()
        elif len(original) < 1:
            print("Oops, you didn't enter anything. Try again!")
            enter_word()
        else:
            print("Alright, trying to translate:")
            print("{}".format(original))
    
    def enter_word():
        original = input("Enter a word:").lower()
        check(original)
    
    enter_word()
    

    In addition to this, you had some syntax errors in your code. Since you used print() instead of print I assume you are using Python3. However, to read user input you used raw_input() which was the way to do in Python2 and became input() in Python3. I fixed this. Another thing I fixed was the string formatting of the print() statement in the else branch. You might take a look at the string format mini-language.