Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python - If-clause: Changing a variable even when not called

My if-clauses that check if the chars-variable is "letters" or "Letters" ("numbers" or "Numbers") doesn't work like I want it to... It changes the chars-variable even when the clause is not called. I already tried a few things but nothing seems to work. (Testing prints added)

(I do not want to do anything illegal with this programm. I just want to learn about the itertools-module.)

Code:

import itertools, sys

chars = input("Chars:" + " ")
max_length = input("Max length:" + " ")
password = input("Password:" + " ")

max_length = int(max_length)

print() #
print("Chars test:", chars) #

if chars == "letters" or "Letters":
    chars = "abcdefghijklmnopqrstuvwxyz"
    print("Chars test:", chars) #
print("Chars test:", chars) #
if chars == "numbers" or "Numbers":
    chars = "0123456789"
    print("Chars test:", chars) #
print("Chars test:", chars) #

print()

input("Press enter to start...")

print()

length = (max_length + 1) - max_length

while length <= max_length:
    results = itertools.product(chars, repeat = length)
    for result in results:
        result = "".join(result)
        if result != password:
            print("Password not found yet:", result)
        else:
            print()
            print("Password found:", result)
            print()
            input("Press enter to exit...")
            sys.exit()
    length = length + 1

print()
print("Couldn't find the password.")

# = Remove when solved.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
if chars == "letters" or "Letters":

is not doing what you think it does. It is True, if

chars == "letters"

or

"Letters"

Since "Letters" is always True in Python, the if clause is always True, too.

Do this:

if chars in ("letters", "Letters"):

and

if chars in ("numbers", "Numbers"):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...