而循环测试用例需要帮助

2024-09-30 20:33:03 发布

您现在位置:Python中文网/ 问答频道 /正文

你能帮我解决这个问题吗。我被测试用例1和2卡住了

def upper_1():
    countCap = 0
    while True:
        word = input('Enter word or press Enter/Return key: ')
        if word == '':
            print("'0 words were entered'")
            break
        else:
            if word[0].isupper():
                countCap += 1
            
    if word != '':
        print('Words with first letter in upper case = ', str(countCap))

enter image description here

enter image description here


Tags: orkeytrueinputreturnifdef测试用例
1条回答
网友
1楼 · 发布于 2024-09-30 20:33:03

代码中有一些逻辑错误。一些小的修复可以:

def upper_1():
    countCap = 0
    words = False
    while True:
        word = input('Enter word or press Enter/Return key: ')
        if word == '':
            break  # always the end of the loop, even if words were entered
        words = True
        if word[0].isupper():
            countCap += 1
            
    if words:  # this is where you can check
        print('Words with first letter in upper case = ', str(countCap))
    else:
        print("0 words were entered")

或者稍微缩短一点:

def upper_1():
    countCap = words = 0  # [== False]
    while True:
        if not (word := input('Enter word or press Enter/Return key: ')):
            break
        words = True
        countCap += word[0].isupper()
            
    if words:
        print('Words with first letter in upper case = ', str(countCap))
    else:
        print("0 words were entered")

相关问题 更多 >