#第二题
english=0
number=0
space=0
other=0
x=input("请输入字符:")
while i in x:
if('A'<i<'Z' or 'a'<i<'z'):
english+=1
elif('0'<i<'9'):
number+=1
elif(i==' '):
space+=1
else:
other+=1
print('英文字符{},数字字符{},空格字符{},其它字符{}'.format(english,number,space,other))
与for自动对元素进行遍历不同,用while你需要自己控制i变量的值的增加1,和循环终止条件。
而且你判断'A'<x[i]<'Z'都是用的 < 这样子是判断的范围就不包含'A'和'Z',应该改成 <=
'A'<=x[i]<='Z'
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
#第二题
english=0
number=0
space=0
other=0
x=input("请输入字符:")
i = 0
while i < len(x):
if('A'<=x[i]<='Z' or 'a'<=x[i]<='z'):
english+=1
elif('0'<=x[i]<='9'):
number+=1
elif(x[i]==' '):
space+=1
else:
other+=1
i += 1
print('英文字符{},数字字符{},空格字符{},其它字符{}'.format(english,number,space,other))
for i in x是对x中的元素进行遍历,用while不能这样写
可以通过下标对字符串进行遍历访问
修改后如下:
有帮助望采纳~
# 第二题
english = 0
number = 0
space = 0
other = 0
x = input("请输入字符:")
s = 0
while s < len(x):
i = x[s]
if('A' < i < 'Z' or 'a' < i < 'z'):
english += 1
elif('0' < i < '9'):
number += 1
elif(i == ' '):
space += 1
else:
other += 1
s += 1
print('英文字符{},数字字符{},空格字符{},其它字符{}'.format(english, number, space, other))
for循环可以,while循环也可以的,通过列表下标访问。
while s < len(x):
统计有现成的方法,不用对字符串中每个字符进行判断。
代码如下:
import string
s = input('请输入一个字符串:\n')
letters = 0 # 统计字母个数
space = 0 # 统计空格个数
digit = 0 # 统计数字个数
others = 0 # 统计其他字符个数
i = 0
while i < len(s):
oneword = s[i] # 获取每个位置的值
i += 1
if oneword.isalpha(): # 判断是否是字母
letters += 1
elif oneword.isdigit(): # 判断是否为数字
digit += 1
elif oneword.isspace(): # 判断是否为空格
space += 1
else:
others += 1
print("[%s]中字母个数=%d,数字个数=%d,空格个数=%d,其他字符个数=%d" % (s,letters,digit,space,others))