You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现用户输入'end'时终止循环并统计各类型字符数量

问题根因
  • 判断输入为end的逻辑位置错误:你将判断放在了遍历输入字符串单个字符的for循环内,循环变量entry是单个字符,永远不可能匹配3个字符长度的'end',因此终止逻辑永远不会触发。
  • 即使判断触发,内层for循环的break只能跳出for循环,无法终止外层的while True死循环。
修复方案

拿到用户输入后首先判断是否为'end',匹配则直接跳出外层while循环,再执行后续的字符统计逻辑,修复后的代码如下:

upper_total = 0
lower_total = 0
alpha_total = 0
num_total = 0
white_total = 0
while True:
    user_string = input("Enter a string: ")
    # 新增输入终止判断,放在字符遍历逻辑之前
    if user_string == 'end':
        break
    for entry in user_string:
        if entry.isupper():
            upper_total += 1
        if entry.islower():
            lower_total += 1
        if entry.isalpha():
            alpha_total += 1
        if entry.isdigit():
            num_total += 1
        if entry.isspace():
            white_total += 1
    print("Capital Letters: ", sum(1 for entry in user_string if entry.isupper()))
    print("Lowercase Letters: ", sum(1 for entry in user_string if entry.islower()))
    print("Letters: ", sum(1 for entry in user_string if entry.isalpha()))
    print("Numbers: ", sum(1 for entry in user_string if entry.isdigit()))
    print("White space: ", sum(1 for entry in user_string if entry.isspace()))
    print('Upper total: ', upper_total)
    print('lower total: ', lower_total)
    print('alpha total: ', alpha_total)
    print('num total: ', num_total)
    print('white space total: ', white_total)

内容的提问来源于stack exchange,提问作者steelehater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:54:03