-3

I am trying to run this code without success. It is supposed to be a basic password generator that let you choose between generating a 20-characters one and a 8-char one.

Here is the code:

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) 

It generates only the 8-chars one, even if I digit D or d or whatever. Does anybody know why it behaves like this?

user229044
  • 232,980
  • 40
  • 330
  • 338
  • 2
    Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Fynn Becker Jul 14 '20 at 12:06

3 Answers3

1

As other people have pointed out, you are using the 'logical or' operator incorrectly, and have given you a solution. However, using an 'or' is unnecessary as you can just use the 'lower' (or 'upper') method, as it just converts a string to lowercase, of strings in this case. So it would look like:

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

The way you are using the or operator is wrong. or is a logical operator which returns True if at least one of the operands is true. In your case, the "S" operand of the or operator is true, so the first branch of if is always chosen. (The same applies to the "d" operand of elif but the branch is never chosen because of the above reason.)

To look for both uppercase or lowercase letter, the (el)if commands should look like this:

if scelta == "s" or scelta == "S":
# ...
elif scelta == "D" or scelta == "d":
Melebius
  • 6,183
  • 4
  • 39
  • 52
0

You need to have the following lines to replace your if / elif statement:

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

and

elif scelta == "D" or scelta == "d":

You haven't used the 'or' statement correctly, remember that each part of the if the statement is separate and you can't just use the variable again without defining it. :)

Good luck!

Minirobbo
  • 61
  • 1
  • 8