使用一段时间的True循环

时间:2016-10-08 00:37:18

标签: python while-loop

问题1。

此问题提供了使用while True循环的练习。写一个名为的函数 twoWords获取并返回用户的两个单词。第一个词是a 指定的长度,第二个单词以指定的字母开头。

函数twoWords有两个参数:

  1. 一个整数length,即第一个单词的长度
  2. 一个字符firstLetter,这是第二个字的第一个字母。
  3. 第二个单词可以以大写或小写的实例开头 firstLetter。函数twoWords应该返回列表中的两个单词。使用 while True实现中的break循环和twoWords语句。该 以下是执行twoWords的示例: print(twoWords(4, 'B'))

    A 4-letter word please two
    A 4-letter word please one
    A 4-letter word please four
    A word beginning with B please apple
    A word beginning with B please pear
    A word beginning with B please banana
    ['four', 'banana']
    

    这是我到目前为止所做的,但它一直在问我第一个问题 即使我有正确的单词长度。我做错了什么?

    def twoWords(length, firstLetter):
        wordLen = input('A 4-letter word please ')
        while len(wordLen) != int(length):
            wordlen = input('A 4-letter word please ')
        word = input('A word beginning with ' + firstLetter + ' please ')
        while word[0] != firstLetter:
            word = input('A word beginning with ' + firstLetter + ' please ')
        return[wordLen, word]
    

1 个答案:

答案 0 :(得分:0)

def twoWords(length,firstLetter):

    firstWord = "" 
    secondWord= ""

    while True:

        firstWord = input('A ' + str(length) + '-letter word please.')
        if length == len(firstWord):
            break
    while True:
        secondWord = input('A word beginning with ' + firstLetter+ ' please')
        if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
            break
    return [firstWord,secondWord]

print(twoWords(4,'B'))