If the students.txt file was like this:
michael jackson:
Civil id: 102931023
Gender: male
In the show_student() function I knew only how to check if the student is in the file or not, but I couldn't access the student information.
How can I access to it?
Code
import csv
import sys
import pathlib
file_path = pathlib.Path("students.txt")
if file_path.exists():
pass
else:
file = open("students.txt", "a+")
def login():
username = input("Username: ")
password = input("Password: ")
if username == "a" and password == "b":
menu()
else:
print("Please try again.")
login()
def menu():
print("*" * 20 + " Main Menu " + "*" * 20)
print(" " * 20 + "A: Register student" + " " * 20)
print(" " * 20 + "B: Show students" + " " * 20)
print(" " * 20 + "C: Show specific student" + " " * 20)
print(" " * 20 + "D: Quit" + " " * 20)
print("*" * 20 + " Main Menu " + "*" * 20)
operation = input("Enter operation: ")
if operation.strip().lower() == "a":
register_student()
elif operation.strip().lower() == "b":
show_students()
elif operation.strip().lower() == "c":
show_student()
elif operation.strip().lower() == "d":
sys.exit()
else:
print("Invalid operation.")
menu()
def register_student():
student_civil_id = input("Student id: ")
student_first = input("Student first name: ")
student_last = input("Student last name: ")
student_gender = input("Student gender: ")
student_full = student_first + " " + student_last
with open("students.txt", "a+") as studentInfo:
info = [student_full + ": " + "\n Civil id: " + student_civil_id + "\n Gender: " + student_gender]
studentInfo.write("\n" + student_full + ": " + "\n Civil id: "
+ student_civil_id + "\n Gender: " + student_gender)
print("Student has been registered.")
def show_students():
with open("students.txt") as studentInfo:
print(studentInfo.read())
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
if student_name.strip().lower() in studentInfo.read():
print("Student exists.")
else:
print("Student not exists.")
login()
I guess, you have many students in students.txt file as:
michael jackson:
Civil id: 102931023
Gender: male
james smith:
Civil id: 165468798
Gender: male
With this file, you can find the index of the specific student, split the text starting from that index, and take the first 3 items from the returned list. At the end, you can use join() function while printing.
def show_student():
student_name = input("Student name: ")
with open("students.txt") as f:
text = f.read()
student_position = text.find(student_name.strip().lower())
if student_position != -1:
info = "\n".join(text[student_position:].split("\n")[:3])
print("Student information:")
print(info)
else:
print("Student does not exists.")
use a regular expression to match the block of information
import re
form = r'{}:\nCivil id: \d+\nGender: [a-z]+'
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
name = student_name.strip().lower()
pat = re.compile(form.format(name), re.MULTILINE)
try:
print(pat.findall(studentInfo.read())[0])
except:
print("Student does not exist.")
You could change your def to something like:
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
studentData = studentInfo.readLines()
if len(studentData) > 0 and student_name.strip().lower() in studentData[0]:
print(*studentData[1:])
else:
print("Student not exists.")
To make your life easier, you might want to look into creating structured data using json, xml, csv or something similar. How do you know that michael jackson: is a name?
Related
lstEmployees = []
lstNames = []
counter = 0
def export_employee():
for employee in lstEmployees:
with open("file.txt", "w") as output:
output.write(str(lstEmployees))
def search_uen():
uen = input("Enter employee UEN: ")
for employee in lstEmployees:
if uen == employee[1]:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
return employee
return -1
def edit_employee():
search = search_uen()
if search == -1:
print("Employee not found...")
else:
name = input("Enter the new name of the employee: ")
uen = input("Enter the new UEN of the employee: ")
phone = input("Enter the Phone number of the employee: ")
email = input("Enter the email of the employee: ")
salary = input("Enter the salary of the employee: ")
search[0] = name
search[1] = uen
search[2] = phone
search[3] = email
search[4] = salary
def add_employee():
global counter
while counter < 5:
print("----------------------------------------------------------\n")
print(" Number of employee ({0:d})" .format(counter))
print("----------------------------------------------------------\n")
name = input("enter employee name: ")
lstNames.insert(counter, name)
uen = input("enter employee UEN: ")
phone = input("enter employee phone number: ")
email = input("enter employee email: ")
salary = input("enter employee salary: ")
lstEmployees.append([name, uen, phone, email, salary])
if counter > 5:
break
else:
continue
def print_employee():
for employee in lstEmployees:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
def menu():
while True:
print('-------------------------------------------\n')
print('Welcome to the Employee Management System -\n')
print('-------------------------------------------\n')
print('[1] Add An Employee: \n')
print('[2] View All Employees: \n')
print('[3] Search Employees By UEN: \n')
print('[4] Edit Employees Information: \n')
print('[5] Export Employee Records: \n')
user_option = input("Please select an option ")
if user_option == "1":
add_employee()
elif user_option == "2":
print('\n' * 3)
print_employee()
print('\n' * 3)
elif user_option == "3":
found = search_uen()
if found == -1:
print("Employee not found...")
elif user_option == "4":
edit_employee()
elif user_option == "5":
export_employee()
else:
print("Please select valid option...")
if __name__ == "__main__":
menu()
i have no idea what to do here, on line its saying that the variable 'employee' is not used and i dont know why and when i switch the code to make the add_employee function look like this: (see image)code line 7 change
when i run the code i cant add employees and the string will always say 0 even after i have add details in.
other info: im using both latest version of pycharm and python sdk.
You're calling the main() function but there's no main function defined. I think you want to use menu().
Your if __name__ block should look like this:
if __name__ == "__main__":
menu()
Your export_employee function never uses the employee variable in the loop. Every time you just write out the entire list of employees. Below, we open the file before we iterate over the list.
def export_employee():
with open("file.txt", "w") as output:
for employee in lstEmployees:
output.write(str(employee))
I'm writing a program that prompts users to do some things, and one of those is add a user by prompting user details. The file.txt is as the image below, but I'm stack on how to actually make the user ID work. The next users added should take ID numbers 5, 6, 7, and so on.
When I run the programme, the ID assigned is random. Can you please advice?
The text file is as below: (I'm a beginner in this please be detailed)
file.txt
def new_user():
file = open('file.txt', 'r+')
lines = file.read()
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
count = len(line)
newcount = len(line)+1
newline=("\n" + str(newcount) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
Although I am not entirely sure if I understood your problem correctly, I am assuming that you would like to use newid in addUserDetail before writing the values back.
The newid inside the new_user function isn't actually taking an arbitrary value. It equals the number of characters in the file. This is because of the file.read() returns type str. This can be fixed by using the readlines() function.
The code for the same is as follows:
def new_user():
file = open('file.txt', 'r+')
lines = [i.strip() for i in file.readlines()]
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
newline = ("\n" + str(newid+1) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
I wrote an example for leveraging comma-separated-value (CSV) files for holding your data. This can be better than simply writing data with spaces because its easier to read back later. What do you do when the address itself has spaces?
Python has a handy csv module that can help with the details. So, here is your problem reworked. This isn't exactly the answer, but an alternate option.
import csv
import os
def new_user():
# removed id generation... let add the called routine that updated
# the database do that
addUserDetail()
def addUserDetail():
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
if not os.path.exists('file.txt'):
with open('file.txt', 'w'):
pass
with open('file.txt', 'r+') as file:
user_id = len(file.readlines()) + 1
writer = csv.writer(file)
writer.writerow([user_id, firstname, secondname, address1,
address2, postcode, telephonenumber])
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
The output from adding 2 users is
1,Jen,Dixon,1 A Street,Big City,99999,111-111-111
2,Bradly,Thompson,99 Elm,Small Town,222,9999
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
requestedTickets = ticketsWanted(userName)
def calculateCost():
ticketQuantity = requestedTickets
totalCost = ticketQuantity * TICKETPRICE
return totalCost
costOfTickets = calculateCost()
def confirm():
global requestedTickets
global costOfTickets
tickets = requestedTickets
totalCost = calculateCost()
print("Okay so that will be " + str(tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/N) : ")
while confirmationResponse == "n":
requestedTickets = ticketsWanted(userName)
costOfTickets = calculateCost()
print("Okay so that will be " + str(requestedTickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/N) : ")
confirm()
def finalStage():
print("Your order is being processed.")
finalStage()
This is a simple program that:
Asks a user how many tickets they want
Calculates the cost of the tickets
Then asks if it's okay to go ahead with the purchase
How could I change the way I'm doing things to not have to overwrite the requestedTickets and costOfTickets global variables?
(they're being overwritten in the confirm function, if a user replies with an "n" declining the confirmation of purchase.)
I'm trying to learn best practices.
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
def calculateCost(n_tickets):
totalCost = n_tickets * TICKETPRICE
return totalCost
def confirm(userName):
n_tickets = ticketsWanted(userName)
totalCost = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/n) : ")
while confirmationResponse == "n":
n_tickets = ticketsWanted(userName)
costOfTickets = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/n) : ")
def finalStage():
print("Your order is being processed.")
confirm(userName)
finalStage()
I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
I have to write a program for my Computer Logic class, and I can't figure out why this won't run. The error I keep getting is IndentationError: expected an indented block (<string>, line 3) Can someone please point me in the right direction? If there are any mistakes you find, please let me know. This code has to be able to run properly. Thanks.
while True:
cname = 'My Company'
drate = .17
maxhrs = 40
pdate = "9/1/2015"
orate = 1.5
lc = 'Y'
while(lc == 'Y'):
ename = raw_input("Enter employee's name.")
dcode = raw_input("Enter department code.(1 - Shipping 2 - Mngmt.)")
hworked = float(raw_input("Enter total hours worked."))
prate = float(raw_input("Enter your pay rate."))
inscost = float(raw_input("Enter the cost of insurance."))
city = float(raw_input("Enter your city code.(1 - Sumiton 2 - Hamilton)"))
st = raw_input("Enter your state")
sex = raw_input("Enter your sex.(M - Male F - Female)")
yrsemp = raw_input("Enter total years employed.")
print("Welcome to our company: ", cname)
print("Pay period date: ", pdate)
if(sex == 'M'):
sexword = 'Male'
else:
sexword = 'Female'
print("Employee name: ", ename, "Sex: ", sexword)
if(city == '1'):
cityn = 'Sumiton'
else:
cityn = 'Hamilton'
print("City: ", cityn, "State: ", state)
if(dcode == '1'):
dname = 'Shipping'
else:
dname = 'Management'
print("Department name: ", dname)
rpay = maxhrs * prate
print("Regular pay: ", rpay)
opay = [(maxhrs - hworked) * orate] * prate
print("Overtime pay: ", opay)
gross = rpay + opay
print("Gross before deduction: ", gross)
damt = drate * gross
print("Deduction amount: ", damt "Insurance cost: ", inscost)
npay = gross - (damt + icost)
print("Net pay: ", npay)
new = raw_input("Would you like to start over with a new person? yes/no")
if(new = 'yes')
restart = int(input("Press 1 to try again, 0 to exit. "))
if(restart == '1'):
continue
elif(restart == '0'):
break
else:
print("Invalid input. Please enter 1 to restart or 0 to exit.")
`
Your code is missing indentation after the first while. You need to indent the statements that will run within this loop, also do the same with the second while you have on line 9.
In Python, after a colon must indent(recommend 4 space). So the indent should be like this:
while True:
cname = 'My Company'
drate = .17
maxhrs = 40
pdate = "9/1/2015"
orate = 1.5
lc = 'Y'
while(lc == 'Y'):
ename = raw_input("Enter employee's name.")
dcode = raw_input("Enter department code.(1 - Shipping 2 - Mngmt.)")
hworked = float(raw_input("Enter total hours worked."))
prate = float(raw_input("Enter your pay rate."))
inscost = float(raw_input("Enter the cost of insurance."))
city = float(raw_input("Enter your city code.(1 - Sumiton 2 - Hamilton)"))
st = raw_input("Enter your state")
sex = raw_input("Enter your sex.(M - Male F - Female)")
yrsemp = raw_input("Enter total years employed.")
print("Welcome to our company: ", cname)
print("Pay period date: ", pdate)
if(sex == 'M'):
sexword = 'Male'
else:
sexword = 'Female'
print("Employee name: ", ename, "Sex: ", sexword)
if(city == '1'):
cityn = 'Sumiton'
else:
cityn = 'Hamilton'
print("City: ", cityn, "State: ", state)
if(dcode == '1'):
dname = 'Shipping'
else:
dname = 'Management'
print("Department name: ", dname)
rpay = maxhrs * prate
print("Regular pay: ", rpay)
opay = [(maxhrs - hworked) * orate] * prate
print("Overtime pay: ", opay)
gross = rpay + opay
print("Gross before deduction: ", gross)
damt = drate * gross
print("Deduction amount: ", damt "Insurance cost: ", inscost)
npay = gross - (damt + icost)
print("Net pay: ", npay)
new = raw_input("Would you like to start over with a new person? yes/no")
if(new = 'yes')
restart = int(input("Press 1 to try again, 0 to exit. "))
if(restart == '1'):
continue
elif(restart == '0'):
break
else:
print("Invalid input. Please enter 1 to restart or 0 to exit.")
(by the way, your code has a lot of problems...I can't even understand this is Python 3 or Python 2...)