[英]Python - If statement: Elif or Else are not working for a password generating code
我正在尝试运行此代码但没有成功。 它应该是一个基本的密码生成器,可让您在生成 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)
即使我输入 D 或 d 或其他数字,它也只生成 8 个字符。 有人知道它为什么会这样吗?
正如其他人指出的那样,您错误地使用了“逻辑或”运算符,并为您提供了解决方案。 但是,使用“或”是不必要的,因为在这种情况下,您可以只使用“下”(或“上”)方法,因为它只是将字符串转换为小写。 所以它看起来像:
if scelta.lower() == 's':
#...
elif scelta.lower() == 'd':
#...
else: # also include an else, in case input doesn't match any defined cases
#...
您使用or
运算符的方式是错误的。 or
是一个逻辑运算符,如果至少有一个操作数为真,则返回True
。 在您的情况下, or
运算符的"S"
操作数为真,因此始终选择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":
和
elif scelta == "D" or scelta == "d":
您没有正确使用“或”语句,请记住 if 语句的每个部分都是独立的,您不能在不定义变量的情况下再次使用该变量。 :)
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.