编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。 ①在程序中用全局变量。编译和运行程序,分析结果。讨论为什么要用全局变量。 ②能否不用全局变量,修改程序并运行之。
时间: 2024-02-11 20:09:21 浏览: 62
好的,我来回答你的问题。
以下是使用全局变量的解决方案:
```python
count_alpha = 0
count_num = 0
count_space = 0
count_other = 0
def count_chars(s):
global count_alpha, count_num, count_space, count_other
for char in s:
if char.isalpha():
count_alpha += 1
elif char.isdigit():
count_num += 1
elif char.isspace():
count_space += 1
else:
count_other += 1
s = input("请输入一个字符串:")
count_chars(s)
print("字母个数:", count_alpha)
print("数字个数:", count_num)
print("空格个数:", count_space)
print("其他字符个数:", count_other)
```
使用全局变量的好处是可以在函数内部直接对变量进行修改,不需要使用返回值。但是,全局变量可能会导致代码可读性和维护性变差,因为在代码的其他部分也可以访问和修改这些变量。
下面是不使用全局变量的解决方案:
```python
def count_chars(s):
count_alpha = 0
count_num = 0
count_space = 0
count_other = 0
for char in s:
if char.isalpha():
count_alpha += 1
elif char.isdigit():
count_num += 1
elif char.isspace():
count_space += 1
else:
count_other += 1
return count_alpha, count_num, count_space, count_other
s = input("请输入一个字符串:")
count_alpha, count_num, count_space, count_other = count_chars(s)
print("字母个数:", count_alpha)
print("数字个数:", count_num)
print("空格个数:", count_space)
print("其他字符个数:", count_other)
```
在不使用全局变量的解决方案中,我们将变量定义在函数内部,使用返回值将统计结果传递给主函数。这样做的好处是可以避免全局变量可能导致的问题,但是需要注意函数内部变量的作用域。
阅读全文