检查raw_input是否为字典

时间:2015-12-01 12:10:41

标签: python if-statement dictionary raw-input

我查看了stackoverflow来解决我的问题但是从关于循环和检查的所有解释我不明白为什么我的代码不起作用。 所以我想构建一个字典(对于Python btw来说是全新的),我读到我还可以检查输入是否在dicitonary模块中,但实际上这不是我想要做的。我只想查看raw_input是否在字符串中包含至少一个数字(如果字符串仅包含数字),并且输入字符串的长度是否至少为2。 如果输入通过了那些检查,它应该继续(这个词典的其余部分将在以后出现。现在我只想了解我的检查错误) 这是我的代码,非常感谢帮助!

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()

编辑:现在可以完美地使用以下代码:

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()

1 个答案:

答案 0 :(得分:0)

您需要将输入original传递给check()函数:

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()

除此之外,您的代码中还存在一些语法错误。由于您使用print()而不是print,我假设您使用的是Python3。但是,要读取用户输入,您使用raw_input()这是在Python2中的方法,并在Python3中成为input()。我修好了。我修复的另一件事是print()分支中else语句的字符串格式。您可以查看string format mini-language