Home > Mobile >  python password generator loop problem print error
python password generator loop problem print error

Time:11-23

I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It works however, when I use the end='' to print the characters on the same line a % shows up. I think it is there to show that it printed a no character. I would like the program to not print the % because later I will add other numbers and symbols.

I tried subtracting 1 from the range of number. What resulted was the same string with a % but 1 less than intended. I also tried creating a while loop that would print while the variable was less than the password number. It also printed the %.

Here is the code:

import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
    print(random.choice(letters), end='')

CodePudding user response:

The % print by your shell (may be zsh), it means the string not end by "\n". It's just a reminder from the shell. There is nothing wrong with you. You can just add a print() in the end of your code to print a "\n", and % will not show again.

CodePudding user response:

Try this

characters = list(string.ascii_letters   string.digits   "!@#$%^&*()")
def generate_random_password():
  ## length of password from the user
  length = 8

  ## shuffling the characters
  random.shuffle(characters)

  ## picking random characters from the list
  password = []
  for i in range(length):
    password.append(random.choice(characters))

  ## shuffling the resultant password
  random.shuffle(password)

  ## converting the list to string
  ## printing the list
  return "".join(password)

CodePudding user response:

Your script works absolutly fine in my side. see this https://onlinegdb.com/9EagkKVW1

If you feel like it's issue with end you can simply concat outputs to string and print at once like so.

import random
import string
letters=string.ascii_letters
pas =''
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
    pas  = random.choice(letters)
   
print(pas)

outputs #

How many characters do you want your password to be? 5
AvfYm

CodePudding user response:

we can use the random .sample() method. it requires 2 arguments:

- iterable of elements to use

- number of elements to take

the result does not contain duplicates.

import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
pas = ''.join(random.sample(letters, k=passwordnumber))
print(pas)
  • Related