|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为什莫有红色警告,还能正确运行??
- symbols = r'''`!@#$%^&*()_+-=/*{}[]\|'";:/?,.<>'''
- chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
- nums = '0123456789'
- space = ' '
- def myfun(str1,str2):
- length1 = len(str1)
- if length1 ==0:
- print('您输入的第1个字符串为空!')
- length2 = len(str2)
- if length2 ==0:
- print('您输入的第2个字符串为空!')
- str1_sym_count = 0
- str1_cha_count = 0
- str1_num_count = 0
- str1_spa_count = 0
- for each in str1:
- if each in symbols:
- global str1_sym_count
- str1_sym_count +=1
- if each in chars:
- global str1_cha_count
- str1_cha_count +=1
- if each in nums:
- global str1_num_count
- str1_num_count +=1
- if each in space:
- global str1_spa_count
- str1_spa_count +=1
- print('第1个字符串中 其他字符:{0} 英文字母:{1} 数字:{2} 空格:{3}'.format(str1_sym_count ,str1_cha_count,str1_num_count,str1_spa_count))
- str2_sym_count = 0
- str2_cha_count = 0
- str2_num_count = 0
- str2_spa_count = 0
- for each in str2:
- if each in symbols:
- global str2_sym_count
- str2_sym_count +=1
- if each in chars:
- global str2_cha_count
- str2_cha_count +=1
- if each in nums:
- global str2_num_count
- str2_num_count +=1
- if each in space:
- global str2_spa_count
- str2_spa_count +=1
- print('第2个字符串中 其他字符:{0} 英文字母:{1} 数字:{2} 空格:{3}'.format(str2_sym_count ,str2_cha_count,str2_num_count,str2_spa_count))
- str1 = input('请输入第1个字符串:')
- str2 = input('请输入第2个字符串:')
- myfun(str1,str2)
复制代码
出现错误的原因是在函数中定义了变量,然后声明为全局变量。首先次程序无需定义全局变量,其次如果需定义全局变量要先在主程序中给变量赋值,再在函数中使用前先声明为全局变量。python能够容忍这个错误,所以提示错误,但能够正常运行。
举个简单的例子:
- def a():
- x = 3
- global x
- print(x)
- x = 5
- a()
- print(x)
复制代码
以上跟楼主的错误提示一样。
修改一下
- def a():
- global x
- x = 3
- print(x)
- x = 5
- a()
- print(x)
复制代码
|
-
|