簡體   English   中英

使用 while True 循環

[英]using a while True loop

問題1。

這個問題提供了使用while True循環的練習。 編寫一個名為twoWords的 function,它從用戶那里獲取並返回兩個詞。 第一個單詞具有指定的長度,第二個單詞以指定的字母開頭。

function twoWords有兩個參數:

  1. 一個 integer, length ,即第一個單詞的長度和
  2. 一個字符firstLetter ,它是第二個單詞的第一個字母。

第二個單詞可以以firstLetter的大寫或小寫實例開頭。 function twoWords應該返回列表中的兩個單詞。 twoWords的實現中使用while True循環和break語句。 以下是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]
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'))
def twoWord(length, firstLetter):
    while True:
       word1=(input("Enter a "+ str(length)+"-letter word please:"))
     
       if len(word1)==int(length):
           break
    while True:
       word2=input("Please enter the word beginning with "+firstLetter+" please:")
       if  word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
           break
    return word1, word2

打印(雙字(5,'b'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM