#๐ project due in like 2 hours, need help making 3 functions
452 messages ยท Page 1 of 1 (latest)
@spice agate
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Do you have code you've written thus far?
No starting from scratch
jk yeah
'Function 1: Password Generation'
def password_generation():
passw = input("Please create a password: ")
errorms = password_verification(passw)
for errorm in errorms:
print(errorm)
if not errorms:
print("Strong password")
'Function 2: Password Verification'
def password_verification(passw):
errors = []
specchars = r"""~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/"""
passw = input("Please create a password: ")
if len(passw) < 12:
errors.append("Not enough chars")
if not any(char.isupper() for char in passw):
errors.append("This password needs at least one uppercase letter.")
if not any(char.islower() for char in passw):
errors.append("This password needs at least one lowercase letter.")
if not any(char.isdigit() for char in passw):
errors.append("This password needs at least one number.")
if not any(char in specchars for char in passw):
errors.append("This password needs at least one special character (such as:"+specchars)
return errors
password_verification(passw)
'Function 3: MFA and One time password'```
these are the directions for the functions
The principle of single responsibility applies here. A function designed to assess the strength of a password should have a parameter for that password, not accept it via input within the function. Asking for that input may occur elsewhere.
Similarly, the result of that function should not be printed within the function, it should return it.
To be then printed elsewhere.
-
Password Generation:
make random secure password of 12 chars, must include uppercase letters, lowercase letters, numbers, and special characters. -
Password Verification:
make a function that checks the strength of a password. The function should ensure that the password meets the criteria above.
give feedback on password strength (e.g., weak, moderate, strong). -
multi factor authentication, (MFA) with OTP: make MFA using a one-time password (OTP) system. make a 6-digit OTP and send it to the user (for simplicity, display it in the console). prompt user to enter the OTP and verify it. make sure the OTP expires after a short duration (e.g., 60 seconds).
oh
yeah for the first one its actually supposed to generate a password, not ask for input
so i guess ill have to change that
!d secrets
Added in version 3.6.
Source code: Lib/secrets.py
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets...
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement...
i'd import that, or just use x.random?
There are a number of tools within those libraries you may avail yourself of.
See their documentation for specifics.
As to OTP, I'm not sure if you're supposed to implement the algorithm yourself or not.
I once had a look at it and it's nontrivial.
i guess it would be similar to function 1 but its just digits
!pypi pyotp comes up with a brief search
and then i make it disappear within 60 seconds
It doesn't need to disappear within 60 seconds, but it does need to expire within 60 seconds.
Though if you did want to make it disappear, then that might be something for ANSI control codes.
yeah i guess i mean expire actually
It sounds like they might just want you to demonstrate equality testing and the use of a datetime or other similar library.
and a while loop
hmm
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation...
!d time
This module provides various time-related functions. For related functionality, see also the datetime and calendar modules.
Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
An explanation of some terminology and conventions is in order...
Mm.
im kinda more familiar with java
but they have equivalents kinda so im trying to go off that the best i can i guess
and similarities
If you're comfortable with it, regex may be suitable to aspects of your project, but I wouldn't suggest it unless you're already familiar with it.
!d re
Source code: Lib/re/
This module provides regular expression matching operations similar to those found in Perl.
Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes). However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a bytes pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.
i dont think i am
idk if have the time to look to deep into it since i got less than 2 hours to turn it in
Do you have any more questions at this stage?
The main thing you need to figure out is what the functions you're writing should take in via their parameters and what they're returning.
Then you need to figure out how you're then acquiring the information you're feeding to the parameters then what you're doing with the returns.
Acquire information, information in, process, information out, display.
yeah i think i get it but i feel like im just confused for somethings
let me try to work on it a bit and see though
Okiedoke.
thank you for your help
is something like this a start?
import random
passw = ""
passw.join(random.choice('abcde') for _ in range(3))
print(passw)```
for function 1
i got the "passw.join(random~" stuff from online
You're not actually reassigning passw, there.
You might like to look at random.choices.
ohhh
ahhh okay i see
i see
i looked at it for a bit and looked up random.choices and saw that i'd put it in the print statement
!e ```py
import random
passw = ""
print(passw.join(random.choice('abcde') for _ in range(3)))```
Are you using the passw variable for anything other than the next line?
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError).
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate)). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
nah just the generated passw
!e py import random population = ['apples', 'pears', 'oranges'] k = 7 choices = random.choices(population, k=k) print(choices)
well i guess i might reuse that variable in different functions
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['apples', 'apples', 'oranges', 'oranges', 'pears', 'apples', 'oranges']
!e```py
import random
passw = ""
print(passw.join(random.choice('abcde') for _ in range(3)))```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
eab
so if i change it a bit
Also remembering that your objective is to write a function.
What should that function accept in terms of parameters, if any?
What is that function returning?
I'll often use join like py ''.join(...)
!e```py
import random
passw = ""
print(passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') for _ in range(12)))```
probably not as tight and clean as it could be lol i guess but idk
:white_check_mark: Your 3.13 eval job has completed with return code 0.
rpz6w2LC8xEi
random.choice and random.choices are two different functions.
oh right this would be in the function, so i guess it might be different
One is suited for making a single choice, the other is suited to making multiple at once.
If that's what you want to go with, that'll do.
!e ```py
import random
def password_generation():
passw = input()
return passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') for _ in range(12))
password_generation()```
:x: Your 3.12 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | password_generation()
004 | File "/home/main.py", line 4, in password_generation
005 | passw = input()
006 | ^^^^^^^
007 | EOFError: EOF when reading a line
I feel as though you're panicking a little at this point.
The purpose of the input function is to ask the user for text input. The purpose of str.join is to use a string as glue to join together an iterable of strings.
or i mean i guess its alright but its gonna hurt my grade if i dont turn this in soon i guess
oh
!e py print('*'.join('abcdefg'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
a*b*c*d*e*f*g
!e py import string print(string.ascii_lowercase)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
abcdefghijklmnopqrstuvwxyz
!d string
Source code: Lib/string.py
import random
def password_generation():
passw = input("Enter any key to generate a Secure Password: ")
print (passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') for _ in range(12)))
password_generation()```
how do i add special characters to this again
Either type them in manually as you've been doing, or use the string library for a preprepared set of them.
passw = input("Enter any key to generate a Secure Password: ")```This line doesn't belong within this function.
Not do you need to assign a variable to it.
oh i can just say input
Nor should you be printing within the function.
Principle of single responsibility.
Each function should have one task
import random
def password_generation():
passw = input("Enter any key to generate a Secure Password: ")
print (passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890r"""~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/"""') for _ in range(12)))
password_generation()```
You have three tasks in this function. Asking the user to enter in something, generating the password, and printing the password.
All you want this function to do is return the password.
I'll say again. The purpose of str.join is to take an iterable of strings and join them together with the glue that you're giving it.
!e py print('*'.join('MASH'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
M*A*S*H
I'll often use py ''.join(...)
The function as written asks the user to press any key to proceed. The input function returns upon enter. You're also assigning a variable to it, one you use in str.join.
So if the user typed in some string...
!e py user_input = 'blah' print(user_input.join('abc'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ablahbblahc
You're going to have a weird password.
i see
yeah i noticed that too in fact typing typing and checking it in the compiler
so it should look like this
import random
passw = input("Press enter to generate a Secure Password: ")
'''Function 1 Pass Gen'''
def password_generation(passw):
print (passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') for _ in range(12)))
password_generation(passw)q```
idky the special chars arent displaying right though
Docstrings' conventional location is within the function directly under the def
i guess the input could say "enter or a key" since it does that kind of weird password making if an actual key other than a blank one is entered like u said
oh
so i should move it under the def
yeah makes sense, i think i do see it a lot like that
okay now the special chars
Is there something about these examples that I can explain in a different way?
idky i had it in a diff code i was doing yesterday but now its like i cant get it
no i think i get it quite well now
i see that join combined with random makes a scrambled new password
password_generation(passw)
passw = input("Press enter to generate a Secure Password: ")
random.choices
wait im confused
is that how it should be
ohhh nvm i get it
the order
For this project, you can use either random.choices or random.choice, but they way you'd use them would be slightly different, depending.
Because you'd need to include the special characters in your population string.
The pool from which you are choosing.
You've got lowercase and uppercase and digit characters.
But no special characters.
~`!@#$%^&*()_-+={[}]|:;"'<,>.?/
this one givs me an error it seemes
when i copy paste it
Oh, I get you.
Well, yes, you can either escape certain characters with a backslash, or you can use the string library, as above suggested.
!e py print('~`!@#$%^&*()_-+={[}]|:;"\'<,>.?/')
:white_check_mark: Your 3.12 eval job has completed with return code 0.
~`!@#$%^&*()_-+={[}]|:;"'<,>.?/
ohhh right the backslash
i think one of the people helping me yesterday said to use that too iirc
thank you so much man
well 39 minutes left
lets see if i can do functions 2 and 3 in time
hopefully
3 seems kinda easier cuz i can just do the same thing for 1
but just digits
It's doable.
You've just got to keep your head.
If you periodically post works in progress as you go, I can comment.
I'll make an effort to communicate effectively.
oh alright sorry i meant to post what i got
Anything a function needs to run should go in via a parameter except for constants. Any information that function is generating should be returned, not printed. A function can display information, but only if that is its specific and sole purpose.
import random
'Function 1L Password Generator'
def password_generation(passw):
print ("Your Secure Password is: "+passw.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`!@#$%^&*()_-+={[}]|:;"\'<,>.?/') for _ in range(12)))
passw = input("Press enter [or a key] to generate a Secure Password.\nEntering a key other than 'enter' will add it in the password's generator algorithm: ")
password_generation(passw)```
thats 1, pretty much done i guess
that L shouldnt be there, mistake
There are problems with this, but let's move on to the next function.
It will at least do a thing.
It will achieve a result that may well satisfy the user, but from an operational and structural perspective, there are some issues.
'Function 3: Multi-Factor Authentication with One-Time-Password'
def multifactorauthen_otp(passw):
print ("Your One-Time-Password is: "+passw.join(random.choice('1234567890') for _ in range(6)))
otpassw = input("\nPress ONLY enter to generate a 6 digit pin: ")
multifactorauthen_otp(otpassw)
they're all on one thing but ill just post 3 so it doesnt look too cluttered and confusing
def func():
"""Docstrings go here."""
...```
Conventionally written with three double quotes.
oh yeah i mean like that
oh
should i move it or just change the quotes to """
or do both
Which you can do with #
ohhhhhhhhhh right
i forgot i could do comments with that
java its different so ive forgotten
# This is the so and so function.
def func():
...```If you're going to do that sort of thing.
This function doesn't need a parameter.
Or at least not as you've written it.
You're assigning otpassw to the user input. You needn't.
Same as like with above.
oh ok
Look at the requirements for function 3.
wait but the user is supposed to interact with it
so them putting the input is just like a prompt thing for them to generate it
otherwise yeah i'd just display it
also for function 3 the user does have to verify the otp
so ill have to whoa Goku
but yeah ill have to still add a prompt in the function
ord and chr??
Please don't?
dont what use ord and chr or add an input prompt
id look into it but i dont have as much time
Anyway, what have you got letft?
You've got to use some kind of time or datetime library, I think.
now i gotta add a prompt to verify it first
That's one part, yes.
#Function 3: Multi-Factor Authentication with One-Time-Password
def multifactorauthen_otp(passw):
print ("Your One-Time-Password is: "+passw.join(random.choice('1234567890') for _ in range(6)))
verifyp = input("Verify the OTP: ")
if verifyp = passw
print("Your OTP has been verified").```
13 mins left
might be ggs
still gonna try though
is that good
oh should i not?
i guess i would rather have it so entering any key would make that fixed number generate
That's why I was going on about str.join before.
i see
yeah i was tryna work to finish it, sorry if it seemed like i was being hard headed and ignoring u on that
oh
== for equality checking
right right
= is for assignment
don't forget colon :
''.join(...)
wait
otherwise it'd be str.join('', ...)
That's why I was saying you seemed panicked.
yeah cuz i legit fully read what u said multiple times
but it just didnt really hit me until now LMFAOOO
wow
Come on. Time-constraints.
The time library is probably simpler, but datetime is probably more idiomatically appropriate.
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation...
oh right
when i looked it up before, i also saw an "expire" code
i would use that?
I don't see that listed in the documentation.
from _datetime import
waittt
oh wait nvm
i scrolled in the doc a bit
so i guess i could use this
duration = timedelta(seconds=11235813)```
!e py import datetime now = datetime.datetime.now() print(now)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
2025-05-06 03:57:11.916421
hmm so whats better
import datetime or
from datetime import timedelta
so i could logically compare it to seconds?
welp thats a bunch of points off
arghhhhhhhh i shouldve came back to this earlier
Either is fine.
Deadline expired?
yeah its probably late now but oh well ill just still finish it
so when i import
it'd look like this?
Panic brain is stupid brain.
import random, datetime
YOu can do that, yes.
LOL yeah but its like my body insists i do things close to the last minute
Would you like me to stick around until you finish? Otherwise I'll just check back in occasionally.
Given you'e post-deadline.
That's not the right syntax.
oh lemme fix it
ill show u function 2 and if u think its good then thats it, theres only like 1 other thing i'd have to do
Mhm
Shall I notify an undertaker?
lol
datatime.datetime instances can have datetime.timedelta instances added to them.
datetime.datetime instances are logically comparable to one another.
> < == etc
LOL ohhhhh
so would u write that like
otpexpire == datetime.datetime.now(seconds = 60)?
orrrrrrr uhhh
!d datetime.datetime.now
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time) timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) subclass, and the current date and time are converted to *tz*โs time zone...
thanks
.
oh im dumb id just use that
!e py import datetime now = datetime.datetime.now() then = now + datetime.timedelta(seconds=30) print(now) print(then) print(then > now)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2025-05-06 04:19:18.185959
002 | 2025-05-06 04:19:48.185959
003 | True
This isn't a suggestion for what you'd include in your code.
ok i think i understand that a lot more now
This is just showing you a practical demonstration of my above
oh
A demonstration to be understood, not copied, is what I mean.
You may find that through understanding you want to do some of this.
You may not. You may do something different.
now is just a variable name I've chosen
datetime.datetime.now is a thing in the library
datetime.datetime.now() is a datetime.datetime instance that represents the time at the call.
You may want to call that more than once.
okay so i got this now
#Function 3: Multi-Factor Authentication with One-Time-Password
import random, datetime
def multifactorauthen_otp(passw):
print ("Your One-Time-Password is: "+''.join(random.choice('1234567890') for _ in range(6)))
verifyp = input("\nVerify the OTP: ")
if verifyp == passw:
print("Your OTP has been verified.")
else:
print("Your OTP could not be verified.")
passw = datetime.datetime(passw)
expireotp = passw + datetime.timedelta(seconds=20)
if expireotp>passw:
print("Your OTP has expired.")
```
i know it got some error
s
What's going on with the parameter, there?
You're reusing the variable.
Also, maybe a while loop.
oh i thought i could use the otp variable for the time variable
guess not
ahhhh true
What are you comparing the user input against?
What do you need to compare it against?
Descriptive naming conventions.
Good practice.
Have variables that are descriptive of the things they are assigned to.
yeah thats why i thought to use "passw", as it would be the otp at that time before expiring
Is it a password?
i guess i could just make a new variable saying "otp" though
no its the variable for the current time comparison
.
yeah
import random, datetime
#Function 3: Multi-Factor Authentication with One-Time-Password
def multifactorauthen_otp(passw):
print ("Your One-Time-Password is: "+''.join(random.choice('1234567890') for _ in range(6)))
verifyp = input("\nVerify the OTP: ")
if verifyp == passw:
print("Your OTP has been verified.")
else:
print("Your OTP could not be verified.")
otpassw = datetime.datetime.now()
expireotp = otpassw + datetime.timedelta(seconds=20)
if expireotp>otpassw:
print("Your OTP has expired.")
this runs
althoughhhhh idky with the verification part
even if u put like the wrong number it still says its verified
and if u put the right one it says it isnt
i tried using if not which does better but i think that one isnt 100% accurate when i was running it for tests multiple times
You have two checks that you need to perform. What are they?
uhhh enter the otp and verify it?
Entering the otp isn't a check.
Verifying it for correctness is one.
Yes.
Are you comparing it for correctness?
Where are you keeping the otp code?
Where are you then using that to compare against?
ohhhh ur right
passw in there doesnt have anything that really makes it equal i think
hmmmm
wait huh
wait the otp would be in passw
Is it?
passw = input("Press any key to generate a Secure Password: ")
password_generation(passw)
otpassw = input("\nPress any key to generate a 6 digit pin: ")
multifactorauthen_otp(passw)
cuz thats the call
In ten or so minutes, yes. But also, you don't appear to be thinking very clearly.
Usually this is a result of fatigue.
I am suggesting that there may be little point for you to continue at this point. Pushing through may be a valid option if you're making progress.
i mean i feel like im so close to finishing though
Rest may be ultimately more enabling to future productivity.
Whereas putting off rest isn't netting you good result and will rob future productivity.
You do not need to assign a variable to input unless you're going to use what the user types in.
If you do use what they typed in, make sure you need to.
If you generate the otp code, you will need to have some way to refer to it.
As it stands, you print it but do not store it in your code.
ohhhh
i see what u mean
i have to make it equal something
i was thinking it would work from the call but i forgot its generated
have to actually make it
You will want to assign a variable to the otp code so that you can then print it and also compare things against it later.
yeahhh
It's like cramming the night before an exam into the night. You get tired, you're not absorbing information very much, then by the time the exam swings around, you've also killed your recall for the things you do know, because you're tired.
Long term, rest is a better strategy.
To get over a deadline, yeah, you can push a bit.
So long as there is rest afterward.
But push push push all the time is not a productive strategy.
You get more and better work done with rest, long term.
Maintain thyself.
Hmmmm
thanks a lot man
i learned a lot from you
now i just need to check function 2 i guess
import random, datetime
#Function 1: Password Generator'
def password_generation(passw):
print ("Your Secure Password is: "+''.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`!@#$%^&*()_-+={[}]|:;"\'<,>.?/') for _ in range(12)))
#Function 3: Multi-Factor Authentication with One-Time-Password
def multifactorauthen_otp(passw):
passw = ''.join(random.choice('1234567890') for _ in range(6))
print ("Your One-Time-Password is: "+passw)
verifyp = input("\nVerify the OTP: ")
if verifyp == passw:
print("Your OTP has been verified.")
else:
print("Your OTP could not be verified.")
otpassw = datetime.datetime.now()
expireotp = otpassw + datetime.timedelta(seconds=20)
if expireotp>otpassw:
print("Your OTP has expired.")
passw = input("Press any key to generate a Secure Password: ")
password_generation(passw)
otpassw = input("\nPress any key to generate a 6 digit pin: ")
multifactorauthen_otp(passw) ```
import random, datetime, time
#Function 1: Password Generator
def password_generation(passw):
print ("Your Secure Password is: "+''.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`!@#$%^&*()_-+={[}]|:;"\'<,>.?/') for _ in range(12)))
#Function 2: Password Verification
def password_verification(passw):
if(len(passw)<8):
print("Weak password. Please use more characters.")
elif(len(passw)>=12):
print("Moderate password. A bit more characters will make this a strong password.")
elif(len(passw)>=16):
print("Strong password")
#Function 3: Multi-Factor Authentication with One-Time-Password
def multifactorauthen_otp(passw):
passw = ''.join(random.choice('1234567890') for _ in range(6))
print ("Your One-Time-Password is: "+passw)
verifyp = input("\nVerify the OTP: ")
if verifyp == passw:
print("Your OTP has been verified.")
else:
print("Your OTP could not be verified.")
otpassw = datetime.datetime.now()
expireotp = otpassw + datetime.timedelta(seconds=20)
if expireotp>otpassw:
print("Your OTP will expire in 20 seconds.")
time.sleep(20)
print("Your OTP has expired.")
spassw = input("Press any key to generate a Secure Password: ")
password_generation(spassw)
passwv = input("Press any key to input a password, and it's strength will be tested: ")
password_verification(passwv)
otpassw = input("\nPress any key to generate a 6 digit pin: ")
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.