问题描述
我尝试了这些代码来整理元音和辅音。但是我发现在第一个代码中我得到了错误的输出而第二个是正确的。有什么区别?
#First code
a = input()
if ord(a.upper()) in range(65,91):
if a in 'AEIoU':
print('Vowel')
else:
print('Consonant')
else:
print('nothing')
#Second code
a = input().upper()
if ord(a) in range(65,91):
if a in 'AEIoU':
print('Vowel')
else:
print('Consonant')
else:
print('nothing')
解决方法
第一个版本应该是:
if a.upper() in 'AEIOU':
...否则小写输入字母在此比较中仍将是小写并失败。
附带说明,该 ord/range 业务应替换为 a.isalpha()
。
a = input()
if ord(a.upper()) in range(65,91):
if a.upper() in 'AEIOU':
print('Vowel')
else:
print('Consonant')
else:
print('Nothing')
第一个程序一定是这样的。您需要将 a.upper()
与 'AEIOU' 进行比较以获得正确的结果。
试试:
#First code
a = input()
a = a.upper()
if ord(a) in range(65,91):
if a in 'AEIOU':
print('Vowel')
else:
print('Consonant')
else:
print('Nothing')
或:
#First code
a = input()
if ord(a.upper()) in range(65,91):
if a.upper() in 'AEIOU':
print('Vowel')
else:
print('Consonant')
else:
print('Nothing')
字符串变量是不可变的。因此,你应该总是使用upper()来大写,或者使用a=a.upper()。
,在第一种情况下,您正在比较不匹配的输入(可能是)的小写值和作为 else 块的一部分打印的 'Consonant'
。
#First code
a = input()
if ord(a.upper()) in range(65,91):
if a in 'AEIOU': #here a is in lower case
print('Vowel')
有趣的是,如果您输入 A
作为输入,两个代码块将产生相同的结果。
但在第二种情况下,您在开始时将输入值转换为大写,然后再在 If
块中进行比较
#Second code
a = input().upper()
if ord(a) in range(65,91):
if a in 'AEIOU': #here it is in uppercase
print('Vowel')
这就是为什么将“元音”作为 If
块的一部分打印的原因。