Writing files with limited user-prompt inputs - python-3.x

I need a code that prompts the user for a name and a number, but the maximum is 3. Then it will write the code to an empty text file, even though the names are only 2 or 3.
name = True
while name:
if name == "done entering":
name = False
break
else:
name = True
firstName1 = input("Enter your first Name: ")
lastName1 = input("Enter your last Name here: ")
studentID1 = input("Enter your id number: ")
firstName2 = input("Enter your first Name: ")
lastName2 = input("Enter your last Name here: ")
studentID2 = input("Enter your id number: ")
firstName3 = input("Enter your first Name: ")
lastName3 = input("Enter your last Name here: ")
studentID3 = input("Enter your id number: ")
break
inFile = open("studentInfo.txt", 'a')
inFile.write("Name: " + firstName1 + " " + lastName1)
inFile.write("\nStudentID: " + studentID1)
inFile.write("Name: " + firstName2 + " " + lastName2)
inFile.write("\nStudentID: " + studentID2)
inFile.write("Name: " + firstName3 + " " + lastName3)
inFile.write("\nStudentID: " + studentID3)
inFile.close()
print("\nDone! Data is saved in file: studentInfo.txt")
I copy-pasted my first code and it kind of works, but whenever I run it in the Python interpreter, there is a "y" before the "enter first names" and I can't enter 2 names only, it requires 3. And how can I make that shorter too... TY

I cannot reproduce the "y" before the "enter first names" behavior. Perhaps a
copy and paste issue in your environment.
To enter less than 3 entries then you need something to limit to 3 and can
allow less than 3. This may need different data handling like using a list.
Create a list to store the 3 groups of entries. A list has length, so use
the length of the list as the while statement. The loop will end after 3 groups
of entries.
Break from the loop if the first name entry is empty as that implies no more
input. Continue the loop if other items are empty so the user can redo the group.
Append the group of entries into the list at end of each loop.
These conditions of break or continue may be changed if preferred.
When the loop ends, if the list is empty then end the script as nothing to do.
Writing the file can be done with a for loop. Use a formatted string so the
group can be written as one group. Formatting allows for further alignment etc.
studentInfo = []
while len(studentInfo) < 3:
firstName = input("Enter your first Name: ")
if firstName == '':
break
lastName = input("Enter your last Name here: ")
if firstName == '':
continue
studentID = input("Enter your id number: ")
if studentID == '':
continue
studentInfo.append([firstName, lastName, studentID])
print()
if not studentInfo:
exit()
fileName = "studentInfo.txt"
inFile = open(fileName, 'a')
for firstName, lastName, studentID in studentInfo:
inFile.write("Name: {} {}\n"
"StudentID: {}\n"
.format(firstName, lastName, studentID)
)
inFile.close()
print("Done! Data is saved in file: " + fileName)

Related

What while loop condition will I use to detect the input all lowercase?

What while loop condition will I use to detect the input all lowercase?
FirstName = input("Enter your First Name: ")
LastName = input("Enter your Last Name: ")
while FirstName.lower() and LastName.lower():
print("Your First and Last Name should be typed in a lowercase letter")
FirstName = input("Enter your First Name: ")
LastName = input("Enter your Last Name: ")
print("Welcome")
Thank you for your help! Your help will be appreciated.
It always helps me to start out being very explicit in code about my intentions. Your intention is to keep looping until the user enters all lower case letters for their first and last names, so while not all_lower_case_entered keep looping. Inside your loop, your intention is to collect the user data and check to see if full_name.islower(). If not, then print your error message, if so, set all_lower_case_entered to True.
Example:
all_lower_case_entered = False
while not all_lower_case_entered:
first_name = input("Enter your first Name: ")
last_name = input("Enter your last Name: ")
full_name = first_name + last_name
if not full_name.islower():
print("Your first and last names should be typed in all lowercase letters.")
else:
all_lower_case_entered = True
print("Welcome")

Compare user input string to text file python

I have a text file filled with sample usernames and I would like to compare it to a user input to see if there is a match. If content matches it will return "This is a match" and if not it will return "That is not a match."
filename = 'UserNames.txt'
with open(filename) as f_obj:
nameLists = f_obj.read()
name = input("Enter a username: ")
if name in nameLists:
print(name + " is a match" )
else:
print( name + "is not a match")
This worked to a degree but will return is a match if the user entered something similar. Ex: text file has blizz1730, user enters blizz. It comes out as a match
You can split the words with spaces and compared with each word to find the match.
name = 'blizz'
nameLists='wla asdnfas blizz1730'
if name in nameLists.split():
print(name + " is a match" )
else:
print( name + " is not a match")
output:
blizz is not a match

python 3.6 basics: Create a program that captures user input and uses variables to store the addresses to be printed

Please help :)
Write a program to collect input from the user for two complete addresses (name, street number, street name, city, state, and zip code) from the command-line prompt. You will first need to create variables to store the addresses in the variables, and then create the appropriate built-in functions to capture the input from the addresses from the user. The street number and zip must be represented in the system as numerical values. Create a program that captures user input and uses variables to store the addresses to be printed.
I know I need to use eval(input()) to convert the characters to numerical values.
I have this as an outline in python for mac currently, just need to enter the information but I am stuck on what "\n" means. as well as where to enter the information.
#user input for first address
print ("\nEnter first address")
name1 = input("Name: ")
streetName1 = input("Street Name: ")
streetNumber1 = input("Street Number: ")
city1 = input("City: ")
#user input for first address
print ("\nEnter first address")
name1 = input("Name: ")
streetName1 = input("Street Name: ")
streetNumber1 = input("Street Number: ")
city1 = input("City: ")
state1 = input("State: ")
zip1 = input("Zip Code: ")
#user input for first address
print ("\nEnter second address")
name2 = input("Name: ")
streetName2 = input("Street Name: ")
streetNumber2 = input("Street Number: ")
city2 = input("City: ")
state2 = input("State: ")
zip2 = input("Zip Code: ")
print both address
print ("\nFirst address is :")
print ("Name", name1)
print ("Street Name", streetName1)
print ("Street Number", streetNumber1)
print ("City", city1)
print ("State", state1)
print ("Zip Code", zip1)
print ("\nSecond address is :")
print ("Name", name2)
print ("Street Name", streetName2)
print ("Street Number", streetNumber2)
print ("City", city2)
print ("State", state2)
print ("Zip Code", zip2)
Python 3.x does not evaluate, you need to use int() at the time of getting and storing the user input like below:
streetNumber1 = int(input("Street Number: "))
zip1 = int(input("Zip Code: "))

newbie python - adding 'cilent' into the txt file

I'm working on a registration in my school project, and one part of it is about registartion. I have to input client in form of
username
password
name
lastname
role
so he can be registered and appended into the txt file,
but i also have to make "username" be the unique in file (because I will have the other cilents too) and "password" to be longer than 6 characters and to possess at least one number.
Btw role means that he is a buyer. The bolded part I didn't do and I need a help if possible. thanks
def reg()
f = open("svi.txt","a")
username = input("Username: ")
password = input("Password: ")
name = input("Name of a client: ")
lastname = input("Lastname of a client: ")
print()
print("Successful registration! ")
print()
cilent = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
print(cilent,file = f)
f.close()
You need to add some file parsing and logic in order to accomplish this. Your jobs are to:
1: Search the existing file to see if the username exists already. With the formatting as you've given it, you need to search each line up to the first '|' and see if the new user is uniquely named:
name_is_unique = True
for line in f:
line_pieces = line.split("|")
test_username = line_pieces[0]
if test_username == username:
name_is_unique = False
print("Username already exists")
break
2: See if password meets criteria:
numbers=["0","1","2","3","4","5","6","7","8","9"]
password_contains_number = any(x in password for x in numbers)
password_is_long_enough = len(password) > 6
3: Write the new line only if the username is unique AND the password meets your criteria:
if name_is_unique and password_contains_number and password_is_long_enough:
print(cilent,file = f)
Edit: You may also have to open it in reading and writing mode, something like "a+" instead of "a".

Searching Names and phonenumbers

mine is homework question in response to the previous Question i posted on this site:
i redid the code to the following:
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", 201-333-3333",'201-725-3444", "201-555-1222", "201-444-4656"]
name = raw_input("Enter person's name:")
found = false
for i in range(0, len(people)):
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumber[i])
else:
print ("No matching name was found.")
My question is how do i tell the program to check if Karen's phone number is the 201-222-2222? And Yes this is a homework assignment. I changed the names and the phone numbers in my acutal program.
When i run this program and type any character all the names and phone number show up that's where i'm having difficutly...
EDITED: Question isn't clear to me.
The following code my help.
1.) First it ask for name then check if it exist in the people list.
2.) Then if it exist it saves it in variable called abc.
3.) After loop is finished it prints the abc which is the name you entered and that person phone number.
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", "201-333-3333","201-725-3444", "201-555-1222", "201-444-4656"]
name = input("Enter person's name:")
abc = "" # Will store the name and phone number
found = False
for i in range(0, len(people)):
if people[i].lower() == name.lower(): #checks if input name match + use method to lower all char
abc = people[i]+" Has the number "+phonenumbers[i]
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumbers[i]) # missing letter "s"
else:
print ("No matching name was found.")
print("\n"+abc)
Result

Resources