first of all my apoligies if i asked something irrelevant, i am new to programming ad also new in python, my question is:
i have to write a simple program in which i have to ask for the number of employee in the company and then i have to create database of the entries, entry contains name of employee, hi/her salary and remarks.
i already write this program by putting number of employee fixed but when number of employee are not fixed then how to save each input in different variales, i think there is need to use loops but how to make this through loops?
TrustyTony 888 pyMod Team Colleague Featured Poster
Are you using list or dictionary?
nytman 0 Light Poster
i used list when i know how many employee in the company, but in this case when number of employee will be decided by user i am confused how to make list variale, for example :-
n = int(raw_input("number of employee"))
for i in range(n):
name = raw_input("enter the name")
i += 1
here how i can make this name variable , and store the multiple inputs given by user and later i can used them.
TrustyTony 888 pyMod Team Colleague Featured Poster
I don't see your list. post your solution for fixed number of workers. I suggest defining a function asking the info and returning list or dictionary of person's data.
nytman 0 Light Poster
name1 = raw_input("enter the first employee name: ")
name2 = raw_input("enter the second employee name: ")
name3 = raw_input("enter the third employee name: ")
cmpny_employ = [name1, name2, name3]
print name1
print name2
print name3
print cmpny_employ
this is something which i had done in case of fixed number of workers, without using loops.
TrustyTony 888 pyMod Team Colleague Featured Poster
But you needed to input all entries of one function
entry contains name of employee, hi/her salary and remarks.
And append the info list in your employers list. What you mean database, does a employers list suffice or you need to use real database like sqllite?
Use loop and append method (or list comprehension if you have covered those).
Here some start:
def input_info(prompts):
info = []
for prompt in prompts:
#input and append
return info
employees = []
for number in range(int(raw_input('Enter number of employees: '))):
#append info
Edited by TrustyTony
nytman 0 Light Poster
thank you sir, this is what i had done by using loop and append,
n = int(raw_input("enter the number of employee in the compay: "))
name = []
salary = []
remark = []
for i in xrange(n):
name.append(raw_input('Enter the name: '))
salary.append(int(raw_input('enter the salary: ')))
remark.append(int(raw_input('enter the remark in between 1-10: ')))
print name
print salary
print remark
this is working fine but i have to test it for some cases, will get back to you after testing my codes and then i will try this same thing by the use of functions and modules.
Edited by TrustyTony because: You could also use Code button for next code paste, formatting fixed
Lucaci Andrew 140 Za s|n
You could use a class to store all your employees information. Than, just add to your list those objects. Here's a small example:
class Employee:
def __init__(self, name, salary, desc):
self.name = name
self.salary = salary
self.desc = desc
def __str__(self): return 'Name: '+self.name+', Salary: '+str(self.salary)+', Description: '+self.desc
def run():
l = []
n = input("Number of employees: ")
for i in range(n):
Name = raw_input("Name: ")
Salary = input("Salary: ")
Description = raw_input("Description: ")
l.append(Employee(Name, Salary, Description))
print "What you have entered: "
for i in range(n): print l[i]
run()
And here's a sample output:
'''
>>>
Number of employees: 2
Name: John
Salary: 10
Description: Hard-working
Name: Annabell
Salary: 5
Description: John's secretary
What you have entered:
Name: John, Salary: 10, Description: Hard-working
Name: Annabell, Salary: 5, Description: John's secretary
'''
Edited by Lucaci Andrew
TrustyTony commented: No capitalized simple variables, please! -3
nytman 0 Light Poster
Thank you Lucaci Andrew,
it really works and the program which i write in my last post was also working fine, but the problem which i am facing right now is:-
I have to ristrict user to enter any randum values like for salary he/she must enter numaric values if he entered any alphanumeric value to salary, program will again sk him to enter the salary again, by the help of try and except method i write some code and it works fine independentely but once i merged that code with my this program it gives error, my code is:-
a = 0
while a == False:
try:
a = float(raw_input("enter the first number: "))
except ValueError:
print "Could you at least give me an actual number?"
but when i merged this code with my actual program it give error:-
n = int(raw_input("enter the number of employee: "))
salary = []
for i in xrange(n):
salary = 0
while salary == False:
try:
salary = salary.append(int(raw_input("enter the salary: ")))
except ValueError:
print "could you please enter the correct salary? "
AttributeError: 'int' object has no attribute 'append'
i dont understand where i was wrong.
snippsat 661 Master Poster
Hmm PEP-8 is gone fall in our head.
def __str__(self): return 'Name: '+self.name+', Salary: '+str(self.salary)+', Description: '+self.desc
And not to happy with all that +
def __str__(self):
return 'Name: {} Salary: {} Description: {}'.format(self.name, self.salary, self.desc)
Edited by snippsat
woooee 814 Nearly a Posting Maven
The easiest to understand is to Use a function
def get_one_salary(ctr):
while True: ##infinite loop
salary=raw_input("enter the salary #%d: " % (ctr+1))
try:
salary = float(salary)
return salary
except ValueError:
print "could you please enter the correct salary? "
n = int(raw_input("enter the number of employee: "))
salary = []
for ctr in xrange(n):
input_value = get_one_salary(ctr)
salary.append(input_value)
print salary
Lennox 0 Newbie Poster
I'm learning Python and in the program below, the parameter "base" must be able to accept either an integer or a float. All my test results match those on the automated test but when I post my program I get this response:
Your output: 0.63 to the power 6 is 0.0625
TypeError: float argument required, not NoneType.
Correct output: 0.0625
As you can see the results are identical so what is the "TypeError" in my program??!! Secondly, is there a way to declare a variable so that it accepts both int and float types? And what exactly is "NoneType"?
def iterPower(base, exp):
ans = 1
counter = 0 # Stores the no. of times base is raised to the power "exp"
while exp > 0:
if base == 1:
print base, 'to the power', exp, 'is', base
break # Terminates loop if base value is 1
else:
ans *=base
counter = (counter + 1)# Gives value of exponent in printing
exp -=1
if type(ans)== float:
print base,'to the power', counter, 'is', round(ans, 4)
else:
print base,'to the power', counter, 'is', ans
#return ans
TrustyTony 888 pyMod Team Colleague Featured Poster
You are not returning any answer so result of function is None
This has no connection to this thread, next time start your own thread for your question!
Lucaci Andrew 140 Za s|n
As pyTony said, start your own thread if asking a different question.
Here's a quick and dirty iterpow function for positive exponents:
def iterpow(b, e):
r = 1
for i in range(e): r*=b
return r
Edited by Lucaci Andrew
Lennox 0 Newbie Poster
Sorry... thought I was... (~)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
@nytman, as a beginner you could also use a list of tuples ...
# index constants for (name, salary, mark) tuple
NAME = 0
SALARY = 1
MARK = 2
# create a list of (name, salary, mark) tuples
mylist = []
while True:
name = raw_input("Enter your name (q to quit): ")
if name.lower() == 'q':
break
while True:
try:
salary = float(raw_input("Enter your salary: "))
break
except ValueError:
print "salary in numbers only!"
mark = raw_input("Enter a mark from 1 to 10: ")
mylist.append((name, salary, mark))
print mylist
print '-'*50
for item in mylist:
print "%s has a salary of %s" % (item[NAME], item[SALARY])
''' possible result ...
Enter your name (q to quit): Joe Blow
Enter your salary: 1234
Enter a mark from 1 to 10: 1
Enter your name (q to quit): Jean Lamar
Enter your salary: 2345
Enter a mark from 1 to 10: 3
Enter your name (q to quit): q
[('Joe Blow', 1234.0, '1'), ('Jean Lamar', 2345.0, '3')]
--------------------------------------------------
Joe Blow has a salary of 1234.0
Jean Lamar has a salary of 2345.0
'''
nytman 0 Light Poster
Thanks to all, for your kind suppport,and sorry for this delay in replying, i tried to use function and it works, here is my code:-
def get_salary(ctr):
while True:
salary = raw_input("enter salary #%d: " % (ctr+1))
try:
salary = float(salary)
return salary
except ValueError:
print "please enter correct salary?"
def get_name(nme):
name = raw_input("enter the name #%s: " % (nme+1))
return name
def get_remark(rmk):
while True:
remark1 = raw_input("enter the remark in between 1-10: ")
try:
remark1 = int(remark1)
if remark1 > 10:
#while remark1 > 10:
print "please enter the remark between 1-10: "
else:
return remark1
except ValueError:
print "Could you at least give me an actual number?"
n = int(raw_input("enter the number of employee: "))
salary = []
name = []
remark1 = []
for ctr in xrange(n):
input_value = get_salary(ctr)
salary.append(input_value)
for nme in xrange(n):
input_name = get_name(nme)
name.append(input_name)
for rmk in xrange(n):
input_remark = get_remark(rmk)
remark1.append(input_remark)
print salary
print name
print remark1
one more thing is there is any way to check that user only enter character while entering name?
upto this extent my program is working fine, i think there is need to optimize this code, i will try and also i have to add few more things into it, thanks again.
:)
nytman 0 Light Poster
here is more optimized code of my previous reply:-
def get_salary(ctr):
while True:
salary = raw_input("enter salary #%d: " % (ctr+1))
try:
salary = float(salary)
return salary
except ValueError:
print "please enter correct salary?"
def get_name(ctr):
name = raw_input("enter the name #%d: " % (ctr+1))
return name
def get_remark(ctr):
while True:
remark1 = raw_input("enter the remark of #%d in between 1-10: " % (ctr+1))
try:
remark1 = int(remark1)
if remark1 > 10:
#while remark1 > 10:
print "please enter the remark between 1-10: "
else:
return remark1
except ValueError:
print "Could you at least give me an actual number?"
n = int(raw_input("enter the number of employee: "))
salary = []
name = []
remark1 = []
for ctr in xrange(n):
input_value = get_salary(ctr)
salary.append(input_value)
input_name = get_name(ctr)
name.append(input_name)
input_remark = get_remark(ctr)
remark1.append(input_remark)
print salary
print name
print remark1
and here is its output:-
enter the number of employee: 2
enter salary #1: 123
enter the name #1: qwe
enter the remark of #1 in between 1-10: 12
please enter the remark between 1-10:
enter the remark of #1 in between 1-10: 1
enter salary #2: qwe
please enter correct salary?
enter salary #2: 1234
enter the name #2: we3
enter the remark of #2 in between 1-10: wer
Could you at least give me an actual number?
enter the remark of #2 in between 1-10: 23
please enter the remark between 1-10:
enter the remark of #2 in between 1-10: 2
[123.0, 1234.0]
['qwe', 'we3']
[1, 2]
please give me your suggestion if you found something more helpful for me.
TrustyTony 888 pyMod Team Colleague Featured Poster
def get_name(nme):
while True:
name = raw_input("enter the name #%s: " % (nme+1))
if name.isalpha():
return name
print 'Use only letters!'
print get_name(0)
Edited by TrustyTony
nytman 0 Light Poster
Thanks Pyton it is working fine.
Now the next oroblem which i am facing right now after asking user to input how many employee are there in the company, user can enter any number of entries, now u have to shortlist the name who will get maximum remark and applouse him, while looser must be motivated and rank goes down by .5.
for that what i think i have to create a list like this :-
employee_data_list = [(name1, salary1, remark1), (name2, salary2, remark2)....(nameN, salaryN, remarkN)]
and then sort this list on the basis of remark.
but here i am unable to collect user inputs like that.
please suggest some needful and also suggest if there is some other way to do this. Waiting for the reply.
bumsfeld 413 Nearly a Posting Virtuoso
Your individual lists have to line up properly to match name and data:
name = ['Frank', 'Bill']
salary = [1234.0, 1535.0]
remark = [3, 2]
employee_list = zip(name, salary, remark)
print(employee_list)
'''
[('Frank', 1234.0, 3), ('Bill', 1535.0, 2)]
'''
# sort by remark which is at tuple index 2
employee_list_sorted = sorted(employee_list, key=lambda x: x[2])
print(employee_list_sorted)
'''
[('Bill', 1535.0, 2), ('Frank', 1234.0, 3)]
'''
The approach vegaseat used avoids potential match problems.
Edited by bumsfeld
nytman 0 Light Poster
Thank you all for all your help, upto this point things are fine,
now i have to make database of what entries user have input to emp_db.txt.
and then i have to ask user wether he want to view the data base or not.
if yes then i have to read the the database from the emp_db.txt and show it to user and then i have to ask user wether he want to do some update or not.
if he want to update then which employee he want to update and them give user freedom to update the employee database.
here is my code for asking user wether he want to update the data base or not:-
import sys
cmpny_account = 0
while cmpny_account == False:
try:
cmpny_account = float(raw_input("enter the company account balance: "))
except ValueError:
print "please enter you account balance not any other thing"
def get_salary(ctr):
while True:
salary = raw_input("enter salary #%d: " % (ctr+1))
try:
salary = float(salary)
return salary
except ValueError:
print "please enter correct salary?"
def get_name(ctr):
while True:
name = raw_input("enter the name : " )
if name.isalpha():
return name
print"use only letters!"
def get_remark(ctr):
while True:
remark1 = raw_input("enter the remark of #%d in between 1-10: " % (ctr+1))
try:
remark1 = int(remark1)
if remark1 > 10:
#while remark1 > 10:
print "please enter the remark between 1-10: "
else:
return remark1
except ValueError:
print "Could you at least give me an actual number?"
n = int(raw_input("enter the number of employee: "))
salary = []
name = []
remark1 = []
for ctr in xrange(n):
input_value = get_salary(ctr)
salary.append(input_value)
input_name = get_name(0)
name.append(input_name)
input_remark = get_remark(ctr)
remark1.append(input_remark)
print salary
print name
print remark1
total_salary = sum(salary)
cmpny_account_savings = cmpny_account - total_salary
pension_fund = total_salary/10
cmpny_account_with_pension = cmpny_account_savings + pension_fund
if total_salary < cmpny_account:
print "go ahead"
else:
print"you already finished your company balance now what you are looking at start it again !!"
sys.exit()
print "total salary is : %d" % total_salary
print "company account after giving salary and adding pension fund is: %d" % cmpny_account_with_pension
cmpny_employ_list = zip(name,salary,remark1)
a = sorted(cmpny_employ_list, key = lambda cmpny: cmpny[2], reverse = True)
print a
b0 = a[0]
b1 = a[1]
#b2 = a[2]
if b0[2] == b1[2]:
print "two of you have same remark so now who have more salary will win"
if b0[1] == b1[1]:
print "you both have same remark as well as same salary so no one is winner!!!"
else:
new_list = [b0, b1]
c = sorted(new_list, key = lambda new: new[1], reverse = True)
d0 = c[0]
d1 = c[1]
print "the winner is ", d0[1]
print "salary of winner is: ", d0[0]
print "Remark of winner is: ", d0[2]
looser = a[n-1]
looser_new_remark = looser[2] - 0.5
print "And our looser is: ", looser[0]
print "No issues better luck next time and your new remark is: ", looser_new_remark
else:
print "the winner is : ", b0[0]
print "Salary of winner is : ",b0[1]
print "Remark of winner is: ", b0[2]
looser = a[n-1]
looser_new_remark = looser[2] - 0.5
print "And our looser is: ", looser[0]
print "No issues better luck next time and your new remark is: ", looser_new_remark
file1 = open('emp_db.txt', 'w')
print >> file1, a
file1.close()
ask_user = raw_input("do you want to see the record from data base yes or no? ")
if ask_user == 'yes':
emp_db_result = open("emp_db.txt", "r")
db = emp_db_result.read()
print "result of employee data base is: ", db
emp_db_result.close()
elif ask_user == 'no':
sys.exit()
ask_user_again = raw_input("do you want to update anything yes or no?")
if ask_user_again == 'yes':
ask_user1 == raw_input("which employee you would like to update?")
now i dont understand how to update particular employee database and i have to keep asking to user untill he says now he want to finish.
waiting for your reply.
TrustyTony 888 pyMod Team Colleague Featured Poster
Update = read data in memory + change data in memory + write out changed data over old file
nytman 0 Light Poster
dear Pytony,
sorry sir still i am unable to perform, if i asked user which employee he want to update then how to fech the data of that employee from emp_db.txt and update it and again save it in emp_db.txt.
waiting for your reply.
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.