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
相关产品推荐
相关产品推荐

