Home > Software engineering >  Taking online python course and need to make a password, aka the input, more complex
Taking online python course and need to make a password, aka the input, more complex

Time:10-29

I'm currently in the process of learning python and having a lot of trouble with the syntax. The problem I'm currently working on is asking me to make a simple password/input more complex. So far I'm trying to use a for loop to cycle through all the letters and see if they need to be changed, as in m -> M. I want each loop to add the resulting character onto a new variable(new_pass) and basically put the characters together to make the new password. That's the thought anyways. The sample input I'm working off is the word 'mypassword', which in turn should output 'Myp@$$word!' per the if/elif statements below. Currently I'm getting an error at line 6 "invalid syntax". Thanks in advance if you can help me out!

word = input()
password = ''
new_pass = ''

for letter in word:
    if letter == i
        letter = 1
    elif letter == a:
        letter = @
    elif letter == m:
        letter = M
    elif letter == B:
        letter = 8
    elif letter == s:
        letter = $
    else:
    new_pass = new_pass   letter

print(new_pass)

CodePudding user response:

First, you must have quotes around your strings. For example, instead of letter = @, you must do letter = '@'.

Secondly, it is a better approach to use a dictionary of replacement letters and loop over the list checking for the replacements.You can do it like this:

word = input()

replacements = {'i': '1', 'a': '@', 'm': 'M', 'B': '8', 's': '$'}
new_pass = ''
for letter in word:
    if letter in replacements:
        new_pass  = replacements[letter]
    else:
        new_pass  = letter

print(new_pass)

You can also do this with a list comprehension if you like:

word = input()

replacements = {'i': '1', 'a': '@', 'm': 'M', 'B': '8', 's': '$'}
new_pass = ''.join([replacements[l] if l in replacements else l for l in word])

print(new_pass)

CodePudding user response:

About the syntax error:

To define a new scope ( the internals ) of an if or a loop you use : at the end and indent the code below.

Also you want to compare string to another string like this:

    if letter == 'i':
        ...
  • Related