一个程序中存在名称错误,而另一个程序则存在语法错误



所以一开始,我需要创建一个程序,用户在其中输入一个字符,如果是Int,那么应该会弹出一个错误。。。如果它的Str,那么它应该进一步分为辅音和元音。然而,这并不能解决问题(而且不起作用(,因为用户可以输入特殊字符,这些字符只会被过滤为辅音

Z = (input("Enter a character: "))
if type(Z) == int:
print(Z, "is a numeral")
else: 
if (Z=='A' or Z=='a' or Z =='E' or Z=='e' or Z=='I'or Z=='i'
or Z=='O' or Z=='o' or Z=='U' or Z=='u'):
print(Z, "is a Vowel")
else:
print(Z, "is a Consonant")

所以,在这之后,我试图创建一个包含所有字母的列表,然后我认为它会起作用。。。我错了

my=input('Enter a character:')
list=[a,A,b,B,c,C,d,D,e,E,f,F,g,G,h,H,i,I,j,J,k,K,l,L,m,M,n,N,o,O,p,P,q,Q,r,R,s,S,t,T,u,U,v,V,w,W,x,X,y,Y,z,Z]
if my in list:
if (my=='A' or my=='a' or my=='E' or my=='e' or my=='I'or my=='i'
or my=='O' or my=='o' or my=='U' or my=='u'):
print(my, "is a Vowel")
else:
print(my, "is a Consonant")
else:
print ('HAHAHA')

这显示了这个错误

Traceback (most recent call last):
File "C:UsersveertDesktopPythonVowelOrConsonant#1.py", line 2, in <module>
list=[a,A,b,B,c,C,d,D,e,E,f,F,g,G,h,H,i,I,j,J,k,K,l,L,m,M,n,N,o,O,p,P,q,Q,r,R,s,S,t,T,u,U,v,V,w,W,x,X,y,Y,z,Z]
NameError: name 'a' is not defined

请帮帮我伙计们

上述列表值应为String类型。所以你需要在"如下所示。

my=input('Enter a character:')
list=["a","A","b","B","c","C","d","D","e","E"]
if my in list:
if (my=='A' or my=='a' or my=='E' or my=='e' or my=='I'or my=='i'
or my=='O' or my=='o' or my=='U' or my=='u'):
print(my, "is a Vowel")
else:
print(my, "is a Consonant")
else:
print ('HAHAHA')

当您添加list=[a,a,b,b,….]时,Python解释器会尝试搜索变量a,a,b等的值。这里没有预定义。因此,它返回NameError。

可能是这样的吗?

vowels = ['A','a','E','e','I','i','O','o','U','u'],
consonants = ['B','b','C','c','D','d','H','h','J','j','K','k','L','l','M','m','N','n','P','p','Q','q','R','r','S','s','T','t','V','v','W','w','X','x','Y','y','Z','z']
inp = input('Please enter a character > ')
if inp not in vowels and inp not in consonants:
print(f'{inp} is not in the alphabet')
if inp in vowels:
print(f'{inp} is a vowel')
if inp in consonants:
print(f'{inp} is a consonant')

为了便于阅读,我将元音和辅音分开,试图将比较运算符缩短到只有几个。

所有输入的Cater:

alphaneumeric = {
'vowel': ['A','a','E','e','I','i','O','o','U','u'],
'consonant': ['B','b','C','c','D','d','H','h','J','j','K','k','L','l','M','m','N','n','P','p','Q','q','R','r','S','s','T','t','V','v','W','w','X','x','Y','y','Z','z'],
'number': ['1','2','3','4','5','6','7','8','9','0'],
'symbol': ['!','@','#','$','%','^','&','*','(',')','[',']','{','}','<','>','.',',',''','"',':',';','-','=','/','\','~','`']
}
inp = input('Please enter a chacter > ')
for key, lst in alphaneumeric.items():
if inp in lst:
print(f'{inp} is a {key}')
break # return immediately

最新更新