[英]using a while True loop
問題1。
這個問題提供了使用while True
循環的練習。 編寫一個名為twoWords
的 function,它從用戶那里獲取並返回兩個詞。 第一個單詞具有指定的長度,第二個單詞以指定的字母開頭。
function twoWords
有兩個參數:
length
,即第一個單詞的長度和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.