如何计算while循环中的用户输入以停止10个输入?

时间:2013-12-01 11:23:04

标签: python python-2.7 python-2.x

我最近开始为我的课程创建一个Python程序。 我有很多程序的主要骨架,但我创建了一个while循环,我需要它在用户输入十个单词/定义时停止。 我已经了解了stackoverflow,我尝试的一切都没有真正起作用。 无论如何,希望一些乐于助人的人可以帮助我。

def teacher_enter_words():
    done = False
    print 'Hello, please can you enter a word and definition pair.'

    while not done:
            word = raw_input('\nEnter a word: ')
            deff = raw_input('Enter the definition: ')
            # append a tuple to the list so it can't be edited.
            words.append((word, deff))
            add_word = raw_input('Add another word? (y/n): ')
            if add_word.lower() == 'n':
                    print "Thank you for using the Spelling Bee program! The word(s) and definition(s) will now appear when a student logs in.\n"
                    done = True

2 个答案:

答案 0 :(得分:3)

def enterWords(maxWords):
  done = False
  words = []
  while len(words) < maxWords and not done:
    word = raw_input('\nEnter a word: ')
    deff = raw_input('Enter the definition: ')
    words.append((word, deff))
    add_word = raw_input('Add another word? (y/n): ')
    if add_word.lower() == 'n':
      print "Thank you for using the Spelling Bee program! The word(s) and definition(s) will now appear when a student logs in.\n"
      done = True
  return words

答案 1 :(得分:0)

首先,您需要在当前声明words列表。

您可以使用words检查len()的尺寸,如果您有10个字,则可退出 循环。

这也可以在不使用done变量的情况下完成,您可以将while循环条件设置为len(words) < 10,这样您就可以节省done的使用

def teacher_enter_words():
    done = False
    print 'Hello, please can you enter a word and definition pair.'

    words = []

    while not done:
            word = raw_input('\nEnter a word: ')
            deff = raw_input('Enter the definition: ')
            # append a tuple to the list so it can't be edited.
            words.append((word, deff))
            if len(words) == 10:
                print "Hi you have 10 words!!!"
                break
            add_word = raw_input('Add another word? (y/n): ')
            if add_word.lower() == 'n':
                    print "Thank you for using the Spelling Bee program! The word(s) and definition(s) will now appear when a student logs in.\n"
                    done = True

    print words
相关问题