此代码用于检查用户名是否有效。即使调用该函数,也不会得到任何输出
"""
for the password to be valid;
must have only 10 characters
have at least 1 uppercase letters
must have 6 lowercase letters
others must be numeric
"""
ucase=0
lcase=0
num=0
#length check
def lencheck():
global length
length=len(uname)
#Ucase check
def uppercase():
for x in range(length):
if uname[x]>='A' or uname<='Z':
global ucase
ucase=ucase+1
#Lcase check
def lowercase():
for x in range(length):
if uname[x]>='a' or uname[x]<='z':
global lcase
lcase=lcase+1
#numeric check
def numeric():
for x in range(length):
if (uname[x])>='0' or (uname[x])<='9':
global num
num=num+1
#main program
def main():
lencheck()
if length==10:
uppercase()
lowercase()
numeric()
numcheck=length-(ucase+lcase)
if ucase>=1 and lcase>=6 and num==numcheck:
print ("username valid")
valid=True
return valid
else:
valid=False
print("username invalid")
return valid
uname=str(input("enter username:"))
main()
我用几个条目尝试了您的代码,至少在给定的情况下,它正确地输出了结果。
但是,问题是,嵌套条件
if ucase>=1 and lcase>=6 and num==numcheck:
缺少
else:
为了避免这种情况,最好在函数上只有一个退出点(return)另外,将其他函数中的所有
or
更改为and
问题在于:
如果我们将
qwertyuiop
作为随机输入,那么num
等于10,而numcheck
等于-10,两者都不相等,因此程序不会在其中输入代码块。 由于它没有else
块,因此程序退出main
函数而没有任何输出如果您想检查所提供的输入是否为数字,我建议您使用
.isdigit
,而且if (uname[x])>='0' or (uname[x])<='9':
仅检查输入是否分别等于或大于或小于或等于0或9以及其他数字同样的情况也适用于
uppercase()
和lowercase()
要检查大写字母,可以尝试以下操作:
希望你在找这个
相关问题 更多 >
编程相关推荐