Python-If语句:Elif或Else不适用于密码生成代码

Python-If语句:Elif或Else不适用于密码生成代码,python,if-statement,Python,If Statement,我正在尝试运行此代码,但没有成功。它应该是一个基本的密码生成器,允许您在生成20个字符和8个字符之间进行选择 代码如下: import random def genpass(): print('this is a password generator biiaatch!') full_char_table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&\'()*

我正在尝试运行此代码,但没有成功。它应该是一个基本的密码生成器,允许您在生成20个字符和8个字符之间进行选择

代码如下:

import random
def genpass():
    print('this is a password generator biiaatch!')

full_char_table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"
alpha_char_table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


scelta = input('choose a password: S = simple one/8 characters; D = difficult one/20 characters: ') 
x = 0
if scelta == "s" or "S":
    lenght = 8
    _type = alpha_char_table
    password = ""
        
    for x in range(int(lenght)):
        password = password + _type[int(random.randrange(len(_type)))]
        
        x += 1
    print('the password is: ' + password)    
elif scelta == "D" or "d":
    lenght2 = 20
    _type2 = full_char_table
    password2 = ""
        
    for x in range(int(lenght2)):
        password2 = password2 + _type2[int(random.randrange(len(_type2)))]
        
        x += 1
    print('the password is: ' + password2) 
随机导入
def genpass():
打印('这是密码生成器biiaatch!')
完整字符表=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyz012456789!\”,“$%&\”()*+,-./:@[\\]^_`{|}~"
alpha_char_table=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyzo123456789”
scelta=input('选择密码:S=简单的1/8个字符;D=困难的1/20个字符:')
x=0
如果scelta==“s”或“s”:
长度=8
_类型=阿尔法字符表
password=“”
对于范围内的x(整数(长度)):
password=password+_type[int(random.randrange(len(_type)))]
x+=1
打印('密码为:'+密码)
elif scelta==“D”或“D”:
长度2=20
_类型2=完整字符表
password2=“”
对于范围内的x(int(lenght2)):
password2=password2+_type2[int(random.randrange(len(_type2)))]
x+=1
打印('密码为:'+密码2)

它只生成8个字符的1,即使我是数字D或D或其他什么。
有人知道它为什么会这样吗?

您使用
运算符的方式是错误的。
是一个逻辑运算符,如果至少有一个操作数为真,则返回
真“
运算符的
操作数为真,因此始终选择
if
的第一个分支。(这同样适用于
elif
“d”
操作数,但由于上述原因,从未选择分支。)

要查找大写或小写字母,(el)if命令应如下所示:

if scelta == "s" or scelta == "S":
# ...
elif scelta == "D" or scelta == "d":

您需要有以下行来替换if/elif语句:

if scelta == "s" or scelta == "S":

您没有正确使用'or'语句,请记住,如果该语句的每个部分都是独立的,您不能在不定义变量的情况下再次使用该变量。:)


祝你好运

正如其他人所指出的,您错误地使用了'logical or'运算符,并为您提供了解决方案。但是,使用'or'是不必要的,因为您可以只使用'lower'(或'upper')方法,因为在本例中,它只是将字符串转换为小写。所以它看起来像:

if scelta.lower() == 's':
    #...
elif scelta.lower() == 'd':
    #...
else: # also include an else, in case input doesn't match any defined cases
    #...

这回答了你的问题吗?
if scelta.lower() == 's':
    #...
elif scelta.lower() == 'd':
    #...
else: # also include an else, in case input doesn't match any defined cases
    #...