问题1。
此问题提供了使用while True
循环的练习。写一个名为的函数
twoWords
获取并返回用户的两个单词。第一个词是a
指定的长度,第二个单词以指定的字母开头。
函数twoWords
有两个参数:
length
,即第一个单词的长度firstLetter
,这是第二个字的第一个字母。第二个单词可以以大写或小写的实例开头
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]
答案 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'))