为什么我不能得到输出

2024-09-29 19:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码用于检查用户名是否有效。即使调用该函数,也不会得到任何输出

"""
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() 

Tags: forifdefcheckhavegloballengthnum
2条回答

我用几个条目尝试了您的代码,至少在给定的情况下,它正确地输出了结果。
但是,问题是,嵌套条件if ucase>=1 and lcase>=6 and num==numcheck:
缺少else: 为了避免这种情况,最好在函数上只有一个退出点(return)

def main():
    valid=False # It will be remained as False unless all the conditions are met
    lencheck()
    if length==10:
        uppercase()
        lowercase()
        numeric()
        numcheck=length-(ucase+lcase)
        if ucase>=1 and lcase>=6 and num==numcheck:
            valid=True
    print("username %s" % ('valid' if valid else 'invalid'))
    return valid

另外,将其他函数中的所有or更改为and

问题在于:

if ucase>=1 and lcase>=6 and num==numcheck:

如果我们将qwertyuiop作为随机输入,那么num等于10,而numcheck等于-10,两者都不相等,因此程序不会在其中输入代码块。 由于它没有else块,因此程序退出main函数而没有任何输出

如果您想检查所提供的输入是否为数字,我建议您使用.isdigit,而且if (uname[x])>='0' or (uname[x])<='9':仅检查输入是否分别等于或大于或小于或等于0或9以及其他数字

def numeric():
    for x in range(length):
        if uname[x].isdigit():
            global num
            num=num+1

同样的情况也适用于uppercase()lowercase()

要检查大写字母,可以尝试以下操作:

#Ucase check
def uppercase():
    upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for x in range(length):
        if uname[x] in upperCase:
            global ucase
            ucase=ucase+1

#Lcase check
def lowercase():
    lowerCase = 'abcdefghijklmnopqrstuvwxyz'
    for x in range(length):
        if uname[x] in lowerCase:
            global lcase
            lcase=lcase+1

希望你在找这个

相关问题 更多 >

    热门问题