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
Related
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
I was trying to check if the username entered is equal to the second index of item in the list, and I tried to use !=, but it still keeps letting the same username to be registered. What's the problem with the code ?
Registering username :
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name != user[1]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
Editted:
The results of != and == seems to be different, the == works.
Login username :
user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name == user[1]:
break # break out for loop
else:
print("Unregistered username")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Logged in as",name)
You're very close!
What you're trying to do: break out of the loop if there are any names in user_list that match the new name.
What it's currently doing: breaking out of the loop if there are any names in user_list that don't match the new name.
I.e., if you enter Daniel, since Daniel != Raymond, you will break early.
Instead, what you should do is break if the newly entered name is not present in a list of names:
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
if name in [user[1] for user in user_list]: # existing names list
print("This username has been registered")
name = input("Please try another username : ")
else:
break
print("Username registered as",name)
This code below will sort a lot of things out. In your code, even if we fix the indentation mistake with the else which should be moved into the for loop, the code won't work if we type Raymond. So I have provided an example which checks if the entered usr is in all the names in your user_list.
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name not in [lst[-1] for lst in user_list]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
I'm trying to make a simple phone book where if you put type in
1: you add a contact to a dictionary, if
2 you lookup the dictionary based on the inputted name (key) if
3 you lookup the dictionary based on the inputted number (value)
When I run a key lookup based on value (input 3) it returns the else function 'this is invalid' regardless of whether or not it is true.
Can someone decipher this?
#Input contact name
if button == 1:
name = input('Please enter the contact name:')
if name in contacts:
print("The name you entered already exists in the address book --> %s:%s"\
%(name,contacts[name]))
flag = input("Whether to modify user information (YES/NO):")
if flag== 'YES':
tel = input('Please enter the users contact phone number:')
contacts.update({name:tel}) #Update dictionary
print("Contacts have been updated!")
else:
continue
else:
contacts[name] = input('Please enter the contact phone number:')
print("Contact has been saved!")
#Search by contact name
if button == 2:
name = input('Please enter the contact name:')
if name in contacts:
print("%s : %s "%(name,contacts[name]))
else:
print('The name you entered is no longer in the address book! ')
#Search by contact number
if button == 3:
numba = input('Please enter the contact number:')
lookup = []
for key,value in contacts.items():
if(value == numba):
lookup.append(key)
print('Name(s) matching number is',lookup)
else:
print('This is invalid')
Try this:
if button == 3:
numba = input('Please enter the contact number:')
lookup = []
for key,value in contacts.items():
if(value == numba):
lookup.append(key)
if lookup: # True if len(lookup) != 0
print('Name(s) matching number is', lookup)
else:
print('This is invalid')
Probably a bit of a stretch, but I made it work like this:
numba = input('Please enter the contact number: ')
lookup = []
for key,value in contacts.items():
if(numba == key):
lookup.append(value)
print('Name(s) matching number is', lookup)
if(int(numba) > len(contacts.items())):
print('This is invalid')
I need to take multiple inputs from user and exit from the loop when the user hits the enter key.
this is what i am trying to do.
while True:
data = input("Enter name age and score:\t").split(",")
if data==' ':
break
else:
continue
try this
data = input("Enter name age and score:")
while data.strip() != '':
data = input("Enter name age and score:")
Just check for bool value:
while True:
data = input("Enter name age and score:\t")
if not data:
break
else:
continue