How to repeat an action in python to make my code simpler

Viewed 77

Im trying to make my code repeat the action of picking a random symbol in a string multiple times. The code below essentially repeats a letter picked 6 times like this "DDDDDD" instead of the desired result of "DYBDdsf" for example. Im trying to create a password gen for my first project. The user input is an arbitrary number for now as I'm still in the process of learning Tkinter.

import string

string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!@#$%^&*()'

userInput = 6

print((random.choice(string.ascii_letters))* userInput)
6 Answers

First, don't redefine string.ascii_letters. Just use is as is. Then you can use random.choices() instead of choice() to pick a number, k of random choices. With that you can join them into a string:

import string
import random 

userInput = 6
pw = "".join(random.choices(string.ascii_letters, k=userInput))
print(pw)
# sRVhZl

If you want to append the ascii letters you can add other symbols like:

userInput = 6
alphabet = string.ascii_letters + '!@#$%^&*()'

print("".join(random.choices(alphabet, k=userInput)))
# qkfpH$

You can actually use a function from the random library pretty close to what you have.

print((random.choices(string.ascii_letters, k=userInput)))

This will essentially pick from the string.ascii_letters and choose userInput amount of characters to append the print screen. I hope this helps.

You can select several ítems of a list with random.choices(). the k value indicates the number of selected items. In your print you need to write

random.choices(string.ascii_letters, k=6)

You are getting the same letter 6 times because you are multiplying the result of choosing a random letter by 6. Instead, you can use a loop:

import string
import random

string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!@#$%^&*()'

userInput = 6

for i in range(0, userInput):
    print(random.choice(string.ascii_letters))

You can use list comprehension:

import string
import random

print(''.join([random.choice(string.ascii_letters + '!@#$%^&*()') for i in range(6)]))

Output:

kh)qlE
import string

string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!@#$%^&*()'

userLetterInput = 6
userSymbolInput = 2

letterResult = "".join(random.choices(string.ascii_letters, k=userLetterInput))

symbolResult = "".join(random.choices(string.number_symbols, k=userSymbolInput))

print("".join(letterResult + symbolResult))

UraeXS)@
Related