So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')
Related
I am new to Python and I have been stuck trying out a "simple banking program".
I have got everything right except for this bit:
If the user types S then:
Ask the user for the account number.
Search the array for that account number and find its position in the accountnumbers array.
Display the Name, and balance at the position found during the above search.
Originally it was just supposed to be through accounts 1-5, but now I am having trouble coming up with a way to search the account numbers if they are any number, not just 1 - 5. For example
The user makes his account numbers 34, 445, 340,2354 and 3245. Completely random account numbers with no order.
Here is what I have so far
names = []
accountNumbers = []
balance = []
def displaymenu():
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choiceInput()
def choiceInput():
choice = str(input("Please enter your choice: "))
if (choice == "P"):
populateAccount()
elif (choice == "S"):
accountNumb = int(input("Please enter the account number to search: "))
if (accountNumb > 0) and (accountNumb < 6):
print("Name is: " + str(names[accountNumb - 1]))
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
elif (accountNumb == accountNumbers):
index = names.index(accountNumb)
accountNumb = index
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
else:
print("The account number not found!")
elif (choice == "E"):
print("Thank you for using the program.")
print("Bye")
raise SystemExit
else:
print("Invalid choice. Please try again!")
displaymenu()
def populateAccount ():
name = 0
for name in range(5):
Names = str(input("Please enter a name: "))
names.append(Names)
account ()
name = name + 1
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
def balances ():
balances = int(input("Please enter a balance: "))
balance.append(balances)
displaymenu()
I have tried to use indexes and have not been able to find a solution.
Replace the following line of code
if (accountNumb > 0) and (accountNumb < 6):
with
if (accountNumb > 0) and (accountNumb < len(accountNumbers)):
My mistake. I messed up when appending the account number:
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
I appended
accountNumbers
not
accountNumber
the code should be
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumber)
balances()
also the searchArray function I made was:
def searchArray(accountNumbers):
x = int(input("Please enter an account number to search: "))
y = accountNumbers.index(x)
print("Name is: " + str(names[y]))
print(str(names[y]) + " account has a balance of: " + str(balance[y]))
rookie mistake , shouldnt be using such similar object names.
I don't know how but it seems that my ages keep getting mixed up within the while loop. It also doesn't include one of the names. The loop works within the IDE but I can't get it to write correctly into the text file.
def main():
friendsfile = open('friends.txt', 'w')
name = str(input('Enter first name of friend or Enter to quit : '))
while name != '':
age = int(input('Enter age of this friend : '))
name = str(input('Enter first name of friend or Enter to quit : '))
friendsfile.write(name + '\n')
friendsfile.write(str(age) + '\n')
friendsfile.close()
print('File was created')
main()
When I enter the names Justin with age 13, Scott with age 20, and Lucy with age 14 I get this written to the file.
Scott
13
Lucy
20
14
The problem is that the name variable gets updated before you print it. This should work:
while name != '':
age = int(input('Enter age of this friend : '))
friendsfile.write(name + '\n')
friendsfile.write(str(age) + '\n')
name = str(input('Enter first name of friend or Enter to quit : '))
It stores the first employee, but when I try to add another employee I am unable to view the additional employees entered. Below is the method for viewing employee record. Thanks for any help!
Employee Class
class Employee
attr_accessor :employee, :role, :location
def initialize(employee, role, location)
#employee = employee
#role = role
#location = location
end
def employee_change(new_emp)
#employee = new_emp
end
def role_change(new_role)
#role = new_role
end.
def location_change(new_loc)
#location = new_loc
end
end
Main Menu
def main_menu
puts "Welcome to the Employee Portal"
puts "Please select an option below: "
puts "---------------------"
puts "1. Create New Employee Record."
puts "2. View an existing record."
puts "3. Modify an existing record."
puts "4. Exit Portal"
option = gets.chomp.to_i
if option == 1
create_record
main_menu
elsif option == 2
view_record
elsif option == 3
modify
elsif option == 4
puts "Thank you for using the Employee Portal"
exit
else
puts "Not a valid option. Please try again."
main_menu
system("clear")
end
end
Create New Employee (Option 1 from Main Menu)
def create_record
puts "Create New Employee Record, click 'Enter' to begin"
puts "Enter Employee Information: "
employee = gets.chomp.capitalize
puts "Enter Employee's Role: "
role = gets.chomp.capitalize
puts "Enter Employee's Current Work Location: "
location = gets.chomp.capitalize
puts "\n"
new_record = Employee.new(employee, role, location)
#record.push(new_record)
puts "New Employee Record has been created."
puts "Name: #{employee}"
puts "Role: #{role}"
puts "Location: #{location}"
system("clear")
main_menu
end
View Employee (Option 2 from Main Menu)
def view_record
puts "Enter Employee Name to view record: "
name = gets.chomp.capitalize
system("clear")
#record.each do |a|
if a.employee == name
puts "\n"
puts "Employee Information "
puts "--------------------"
puts " Name : #{a.employee}"
puts " Role(s) : #{a.role}"
puts " Location(s) : #{a.location}"
puts " Type 'Exit' to return to the Main Menu "
else
puts "That is not a valid entry, please try again."
view_record
main_menu
end
end
end
Modify Employee (Option 3 from Main Menu)
def modify
system("clear")
puts "Enter employee name to modify existing record: "
name = gets.chomp.capitalize
#record.each do |r|
if r.employee == name
puts "Employee found."
puts "Select an option to modify."
puts "-----------------------------------"
puts "1.) Modify employee's name."
puts "2.) Modify employee's role."
puts "3.) Modify employee's location."
puts "4.) Return to Main Menu"
puts "\n"
option = gets.chomp.to_i
if option == 1
change_employee
elsif option == 2
change_role
elsif option == 3
change_location
elsif option == 4
main_menu
else
puts "Invalid selection. Please try again."
modify
end
end
end
end
Change Employee (Option 1 from Modify)
def change_employee
puts "Enter new employee name: "
new_emp = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.employee_change(new_emp)
puts "#{r.employee} has been updated to #{r.employee}"
end
end
end
Change Employee Role (Option 2 from Modify)
def change_role
puts "What is #{r.employee}\'s new role?: "
new_role = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.role_change(new_role)
puts "#{r.employee}\'s new role is #{r.role}"
end
end
end
Change Employee Location (Option 3 from Modify)
def change_location
puts "What is #{r.employee}\'s new location?: "
new_loc = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.location_change(new_loc)
puts "#{r.employee} has been transfer to new location, #{r.location}."
end
end
end
Run the Program
#record = []
system("clear")
main_menu
The problem is with your view_record method. If you change it to look something like:
def view_record
puts "Enter Employee Name to view record: "
name = gets.chomp.capitalize
system("clear")
if a = #record.detect { |rec| rec.employee == name }
puts "\n"
puts "Employee Information "
puts "--------------------"
puts " Name : #{a.employee}"
puts " Role(s) : #{a.role}"
puts " Location(s) : #{a.location}"
puts " Type 'Exit' to return to the Main Menu "
else
puts "That is not a valid entry, please try again."
view_record
end
end
It works properly.
The problem was that you were calling the if...else statement on every record in #record. So if you create 2 Employees the first one named "John" and the second named "Jane". When you go to view "Jane", you call the else portion for "John", since he's the first record and then once he finishes the else you call the if portion for "Jane". The else for "John", however, never returns because after you finally finish a [possibly lengthy] stack of view_record calls, with the same issue, you then go back to main_menu which never returns (due to the final else condition in that method that re-calls main_menu)
Hope that helps and makes sense.
Notes:
The modify seems to have the same issue and the change_x methods will loop through and check each employee against the if statement, but since no else no problem (I'd still change them personally, to use the detect on these as well).
The change_x methods don't look like they would run, because employee isn't defined in them
If more than 1 employee can have the same name, you can use select instead of detect and then check for empty? or iterate through only those returned by select and call only the if portion on them.
Why he gives me (Type error) in that statment
" address = cur.fetchone()[2] last = cur.fetchone()[4] no = cur.fetchone()[5] , while it accept "name = cur.fetchone()[1]" in the code : "
import sqlite3
conn = sqlite3.connect('myproject.sqlite')
cur = conn.cursor()
print "Welcome Mr/Hefnawy"
cur.execute('SELECT phone FROM participants')
b = cur.fetchone()[0]
while True:
a = raw_input("Enter Phone number here : ")
if a == b :
cur.execute('SELECT name,address,last_order,no_of_orders FROM participants WHERE phone = ?',(b, ))
name = cur.fetchone()[1]
address = cur.fetchone()[2]
last = cur.fetchone()[4]
no = cur.fetchone()[5]
print "The Costumer is already exist in Paricipants "
print "To edit the costumer data press (1)", "\n" , "to delet the costumer press (2)", "\n" , "add new order to the costumer press (3) "
c = raw_input("Enter your choice here : ")
if c == "1":
print "What do you want to edit ? , to edit name press 1 , to edit address press 2 , to edit phone press 3"
d = raw_input("Enter your choice here : ")
if d == "1" :
e = raw_input("New costumer name please ")
cur.execute('UPDATE participants SET name = ? WHERE phone = ?' , (e , a))
print "Costumer name has been updated to :", e
print ""
conn.commit()
else:
print "The costumer is not exist"
print b
print a , type(a)
When you are fetching something from a cursor say for example
t = cur.fetchone()
you can access the data from t using
print t[0],t[1],t[2] but In your case you are using multiple cur.fetchone() which allows you to use name = cur.fetchone()[1] that ends the data in the cursor. The second line address = cur.fetchone()[2] and the lines that follow it do not have a sql query executed for them to fetch, hence giving you the error. If you want to access the whole row just assign it to a variable and use the variable to get the data.
I need to use a loop in my code so the user is prompted with "Name?" three times, and each answer is stored as a new hash within the data array. Each answer should also have a new random number generated for it, and an email.
I need puts data to output all three hashes and their contents. I've tried using 3.times do, but I'm having trouble:
data = Array.new()
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
data = [
{
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
]
puts data
data = []
3.times do
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
hash = {
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
data << hash
end
puts data