Write a program that asks the user to put the password, first name, last name, and id. If any of that is invalid, program to continuously ask to provide the valid input. Here are the rules:
Password has to be at least 7 characters, must contain at least one uppercase letter, at least one lowercase letter, and at least 1 digit
First name and last name must contain only letters
ID must contain only digits
After you have input everything validly print them on the screen. As the password is sensitive info print only the first three characters and for the rest of the length, print '*'
password = 'Pass1234'
first_name = 'John'
last_name = 'Smith'
ID = '1234'
p = input('Input your password: ')
if (len(p)<6):
print('Invalid password. Must be at least 6 characters')
p = input('Input your password: ')
elif not p.islower():
print('Invalid password. Must have at least 1 lowercase character')
elif not p.isupper():
print('Invalid password. Must have at least 1 uppercase character')
if p == password:
print('Well done! This is a valid password')
password_list = list(password)
password_list[3] = '*'
password_list[4] = '*'
password_list[5] = '*'
password_list[6] = '*'
password_list[7] = '*'
edited_password = ''.join(password_list)
fn = input('Please enter your first name: ')
ln = input('Please enter your last name: ')
for f in fn:
if f.isdigit():
print('Invalid Name! Name should only contain letters')
fn = input('Please enter your first name: ')
for l in ln:
if l.isdigit():
print('Invalid Name! Name should only contain letters')
ln = input('Please enter your last name: ')
if fn == first_name or 'john' and ln == last_name or 'smith':
print('Well done! This is a valid name')
I = input('Please enter your ID: ')
if I.isupper():
print('Invalid ID! ID should only contain numbers')
I = input('Please enter your ID: ')
elif I.islower():
print('Invalid ID! ID should only contain numbers')
I = input('Please enter your ID: ')
elif I == ID:
('Well done! This is a valid ID')
print('Name:', first_name, last_name)
print('ID:', ID)
print('Password:', edited_password)
Output:
Input your password: Pass1234
Invalid password. Must have at least 1 lowercase character
Well done! This is a valid password
Please enter your first name: John
Please enter your last name: Smith
Well done! This is a valid name
Please enter your ID: 1234
Name: John Smith
ID: 1234
Password: Pas*****
How can I fix my program where it doesn't print the lowercase error message?
You can do something like this. The problem you had is you were checking to see if your entire password was lowercase instead of if at least 1 character was.
Of course you'll probably want to change your input variable from "p" to "password" instead of hard coding it at the top of the page.
p = input("Input your password: ")
upper = 0
lower = 0
number = 0
while True:
for x in p:
if x.isupper()==True:
upper+=1
elif x.islower()==True:
lower+=1
elif x.isalpha()==False:
number+=1
if len(p) < 7 or upper <= 0 or lower <= 0 or number <= 0:
print ('password not complex enough')
p = input('please enter password again ')
upper = 0
lower = 0
number = 0
else:
break
Related
I'm trying to make a task a little more efficient. I'm going to continue to research/edit while moving forward.
What the code currently does is ask for your first/last name it then outputs a username & password. Up to this point it works fine if there is a more efficient way to rewrite this also appreciated.
The only thing I still need to fix is looping entries(First_name and Last_name) so I can have multiple users added with a \n\n for easy reading/separation of each user. preferably with a exit command such such as "done"
I'm also going to be looking into how to create a new file that this information is stored in but this is the section I'm going to try to figure out.
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
In terms of trying to solve the issue.
I did try to create something in the ball park of..
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
while First_name != "done":
Last_name= input("Enter your last name: ")
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
this just repeated the first two lines without printing the Username/password. It also appeared to acknowledge when I typed done but slightly off from desired. Below I included how the code ran
Enter your First name: first
Enter your last name: last
Enter your last name: last
Enter your First name: done
Enter your last name: last
Username: DONELAST
Password: donelast1!
I get why its first, last, last, first last. I dont get how to make the while loop using "while Fist_name !='done': " without putting lines 1 and 2 before the loop. I tried removing the inputs at line 5 and 6 but then it just looped the username and password.
You can use a while loop and break it when the first name is done.
while True:
first_name = input("Enter your first name (done to exit): ")
if first_name.lower() == "done":
print("Done!")
break
last_name = input("Enter your last name: ")
Username = str(first_name) + str(last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
print("\n")
Output:
Enter your first name (done to exit): John
Enter your last name: Doe
Username: JOHNDOE
Password: JohnDoe1!
Enter your first name (done to exit): Alice
Enter your last name: Court
Username: ALICECOURT
Password: AliceCourt1!
Enter your first name (done to exit): done
Done!
Just set your variables to an empty string before the loop starts. Since an empty string is not equal to done your code will enter the loop and prompt the user:
First_Name = ''
Last_Name = ''
while First_name != "done":
Last_name= input("Enter your last name: ")
First_name = input("Enter your First name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
(1)Prompt the user to enter two words and a number, storing each into separate variables. Then, output those three values on a single line separated by a space. (2) Output two passwords using a combination of the user input. Format the passwords as shown below. (3) Output the length of each password (the number of characters in the strings).
The following is the code I am using to complete this program but I am running into an output error.
def userdetails():
words = input("Enter a word: ")
word2 = input("Enter a word: ")
numm = input("Enter a number: ")
pw1 = words+"_"+word2
pw2 = numm+words+numm
print("You entered: {} {} {}" .format(words,word2,numm))
print("First password:",pw1)
print("Second password:",pw2)
print("Number of characters in",pw1,":",len(pw1))
print("Number of characters in",pw2,":",len(pw2))
userdetails()
Input
yellow
Daisy
6
Your output
Enter a word: Enter a word: Enter a number: You entered: yellow Daisy 6
First password: yellow_Daisy
Second password: 6yellow6
Number of characters in yellow_Daisy : 12
Number of characters in 6yellow6 : 8
Your output does not contain
You entered: yellow Daisy 6
First password: yellow_Daisy
Second password: 6yellow6
I don't know what to do to get the rest of this correct for all the points needed can anyone help me?
I am unsure which part you are confused about. From the looks of it, the only line you are missing is print(words, word2, numm) which will complete part 1.
words = input("Enter a word: ")
word2 = input("Enter a word: ")
numm = input("Enter a number: ")
pw1 = words+"_"+word2
pw2 = numm+words+numm
print(words, word2, numm)
print(pw1)
print(pw2)
print(len(pw1), len(pw2))
Result
Enter a word: test
Enter a word: word
Enter a number: 10
test word 10
test_word
10test10
9 8
color = input()
flower = input()
number = input()
print('You entered: {} {} {}\n' .format(color,flower,number))
password1 = color+'_'+flower
password2 = number+color+number
print('First password:', password1)
print('Second password:', password2+'\n')
print('Number of characters in', password1+':',len(password1))
print('Number of characters in', password2+':',len(password2))
color = input()
word = input()
number = input()
print('You entered: {} {} {}\n' .format(color,word,number))
password1 = color+'_'+word
password2 = number+color+number
print('First password:', password1)
print('Second password:', password2+'\n')
print('Number of characters in', password1+':',len(password1))
print('Number of characters in', password2+':',len(password2))
#after multiple tests I was able to get the code formatted correctly. Thanks to stackoverflow. Thank you Tresa for the correct code. You saved me a headache. Just have to remember format, format, and more format
What I came up with was:
#FIXME (1): Finish reading another word and an integer into variables.
#Output all the values on a single line
favorite_color = input()
favorite_noun = input()
notfavorite_number = input()
print('You entered: {} {} {}\n' .format(favorite_color, favorite_noun, notfavorite_number))
#FIXME (2): Output two password options
password1 = [favorite_color, favorite_noun]
password2 = [notfavorite_number, favorite_color, notfavorite_number]
#strictly to add an underscore
underscore = '_'
#jonsnow
nothing = ''
#password modifications
password11 = underscore.join(password1)
password22 = nothing.join(password2)
print('First password:', password11)
print('Second password:', password22)
#FIXME (3): Output the length of the two password options
print('\nNumber of characters in', password11 + ':', len(password11))
print('Number of characters in', password22 + ':', len(password22))
Maybe it's too much, but it worked! ¯\(ツ)/¯
heres what I got
words = input()
word2 = input()
numm = input()
pw1 = words+"_"+word2
pw2 = numm+words+numm
print(f'You entered: {words} {word2} {numm}')
print(f'First password: {pw1}')
print(f'Second password: {pw2}')
print(f'Number of characters in {pw1}: {len(pw1)}')
print(f'Number of charecters in {pw2}: {len(pw2)}')
currently I am doing my assignment. The requirement is to test the format of Student ID. I wonder why is my while loop is not working properly..
My validation check is as below:
def isValidStudentIDFormat(stid):
# studentID must have a length of 9
if(len(stid) != 9):
# return the invalid reason
return "Length of Student ID is not 9"
# studentID must starts with a letter S
if(stid[0] != 'S'):
# return the invalid reason
return "First letter is not S"
# studentID must contains 7 numbers between the two letters
for i in range(1,8):
# anything smaller than 0 or bigger than 9 would not be valid.
# so does a character, will also be invalid
if((stid[i] < '0') or (stid[i] > '9')):
# return the invalid reason
return "Not a number between letters"
if((stid[8] < 'A') or (stid[8] > 'Z')):
# return the invalid reason
return "Last letter not a characer"
# return True if the format is right
return True
My function to insert a student record is below:
def insert_student_record():
#printing the message to ask user to insert a new student into the memory
print("Insert a new student \n")
fn = input("Enter first name: ")
#check if user entered space
#strip() returns a copy of the string based on the string argument passed
while not fn.strip():
print("Empty input, please enter again")
fn = input("Enter first name: ")
ln = input("Enter last name: ")
while not ln.strip():
print("Empty input, please enter again")
ln = input("Enter last name: ")
stid = input("Enter student id: ")
while not stid.strip():
print("Empty input, please enter again")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result == True
#append the student details to each list
#append first name
fName.append(fn)
#append last name
lName.append(ln)
#append student id
sid.append(stid)
#to check if the new student is in the lists
if stid in sid:
if fn in fName:
if ln in lName:
#then print message to tell user the student record is inserted
print("A new student record is inserted.")
However, I'm getting an infinite loop even if I key in the correct format for student ID. Anyone can help ?
You compare result == True when you should assign. Still, you don't check the new student id for validity, which could be done this way:
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
?
def validateStudentIDFormat(stid):
if len(stid) != 9:
raise RuntimeError("Length of Student ID is not 9")
if stid[0] != 'S':
raise RuntimeError("First letter is not S")
for char in stid[1:-1]:
if char.isnumeric():
raise RuntimeError("Not a number between letters")
if not stid[-1].isalpha():
raise RuntimeError("Last letter not a characer")
....
while True:
stid = input("Enter student id: ")
try:
validateStudentIDFormat(stid)
except RuntimeError as ex:
print(ex)
print("Invalid student id format. Please check and enter again.")
else:
break
I am trying to create a user login system program. I am trying to make sure the password must have at least 10 characters which I have done, but I'm having trouble making sure it has at least two numbers and only underscore as a special character. I have seen some solutions about numbers and I don't get them and they rarely have at least 2 digits.
Here is my code:
print("Welcome ")
print('')
print('New users should enter Sign to create an account')
print('')
print('')
username = input('Enter your Username: ')
if username == 'Sign':
while True:
usernames = ['Dave','Alice','Chloe']#A list that stores usernames
create_user = input('Enter your new username: ')
if create_user in usernames:
print('This user name has been taken .Try again')
continue
else:
break
usernames.append([create_user])
while True:
create_pass = input('Enter your your user password: ')
passwords = []#A list thst stores password
pass_len = len(create_pass)
if pass_len < 10:
print('Your password must be at least 10. Try again')
continue
else:
print('')
print('You are now a verified user.')
print('Run the application again to re-login.')
print('Thank You')
break
else:
password = input('Enter your password')
print('Visit www.bitly/p8?. to continue')
If you're not wanting to use regex, you could add some simple logic like this:
num_count = 0
for character in create_pass:
if character.isdigit():
num_count += 1
if num_count < 2:
print('You must have at least 2 numbers in your password')
This is how I'd do it. You can check for the underscore with in and use regex to search for the numbers.
import re
test = 'hisod2f_1'
underscore = '_' in test
twonums = len(re.findall(r'\d', test)) >= 2
if underscore and twonums:
# your logic
I have a program that asks the user's name:
while True:
try:
name = str(input("Please enter your name > "))
except ValueError:
print("Please enter a valid name")
continue
else:
break
I want to prevent the user from entering an integer, but with the code above integers are accepted in a string. How can I prevent the user from entering an integer in the string?
Firstly, do not cast str as input returns an str. Note from the docs
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that
After you get the input into name you can have a if condition.
name = str(input("Please enter your name > "))
if (re.search('\d',name)):
print("Sorry your name contains a number")
And don't forget to import re
break when trying to cast to an int if an exception is raised as it is not an int:
while True:
name = input("Please enter your name > ")
try:
int(name)
except ValueError:
break
print("Please enter a valid name")
str.digit might work also but will fail on negative input.
To check if any character is a digit use any:
while True:
name = input("Please enter your name > ")
if any(ch.isdigit() for ch in name):
print("Please enter a valid name")
else:
break
You could also create a set of accepted characters:
from string import ascii_letters
st = set(ascii_letters)
while True:
name = input("Please enter your name > ")
if not st.issuperset(name):
print("Please enter a valid name")
else:
break
Where you might want to add -, " " and any other potential characters.
You can use the string method isdigit() to check if the string is just integers.
name = input("Please enter your name: ")
if name.isdigit() == True:
print ("That's not a name!")
Likewise, you can also use the method isalpha() to check if the string is just text. However, if there's a space, it will return False.
name = input("Enter your name: ")
if name.isalpha() != True:
print ("That's not a name!")
Maybe:
if len(set(name) - set('1234567890')) < len(set(name)):
name = input("Please enter a valid name: ")