0

Why for loop is not working in a block of Function ?

import random def password_gen(amount = 5,length = 8): upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lower = upper.lower() sp = "!ÂŁ$%^&*()[]#" digits = 1234567890 password = upper + lower + sp + str(digits) for times in range(amount): result = random.sample(password,length) # sample generator a list password_generator = "".join(result) # join will convert a list into a string return password_generator length = 50 amount = 5 print(password_gen())

31st Jan 2021, 1:09 AM
Balraj Singh
4 Answers
+ 2
Balraj Singh I'm really sorry if my previous code is wrong, I did not pay attention to your code's purpose. Anyway.. 1) It is concatenating the list, and because as I said I was wrong, yeah it really is wrong because what I did was printing password with 50 lengths which is suppose to be 8 lengths each (based on default parameter). But to solve this anyway, just change += by result.append() then use list comprehension instead of join (which wont work with list containing list). 2.) Here are different methods I'd thought of (without using print inside function): ● Using yield to create a generator which will be iterated to print. ● Using list.append. https://code.sololearn.com/cm9iRnPlx4dv/?ref=app https://code.sololearn.com/cU9zHy4FKpTs/?ref=app
1st Feb 2021, 9:34 AM
noteve
noteve - avatar
+ 4
That is because your return keyword is inside the for loop, therefore your function will terminate right after the first iteration. To fix: 1. Your "password_generator" and return keyword should be outside the for loop, so it will still continue to next iterations. 2. Create an empty list "result" and concatenate there your random samples. If this is wrong, please clarify or if you have more questions, please feel free to ask. Thanks! EDIT: This is wrong as I did not pay attention that you need different passwords with certain length. To solve this, append each password instead of concatenate and use list comprehension to return each password. Or you can just print inside function. Or use "yield" to return multiple values, i.e. generator. https://code.sololearn.com/cwP6qTrf1ySZ/?ref=app
31st Jan 2021, 1:18 AM
noteve
noteve - avatar
+ 1
Thank You for reply. i have some doubts - 1) why did you add empty ‘result’ list. i think it’s needed. random choice functiom will automatically make a list so we dont need to give an empty list. Tell me if i am wrong. 🐍😊 2) second is about amount of password - if indent return outside the loop then it will print only last value (according to rules ). and i tried also i did not work that i was expecting. # notes if i use return it only gives one password but if i use print function it works like i want
1st Feb 2021, 7:59 AM
Balraj Singh
+ 1
Thanks Again 😊. it is working now.
1st Feb 2021, 4:42 PM
Balraj Singh