Im learning python and am currently trying to pass values from input to the args for a module I wrote but I have no idea how to start.
Can someone give me some advice?
This is the module im calling
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
This is the code im using to call and pass the values to the args in the above module
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
Im guessing I need to take the input from the user and place it in the variables of the class. I tried that but im guessing im doing everything wrong??
Employee.Age = int(raw_input("How old are you? "))
There's no use to setting a variable in the module instead of using a local variable, and setting whatever you need to set outside the Collection1() function. Note that you are not setting the employee (object) atributes', but the module's - this is probably not what you want. Also, functions, by convention, should be named with initial lowercase.
Your inheritance model is a bit strange. Why are the employee attributes in a different (sub) class? Generally, the attributes go into the main class constructor. If you really want to use a separate class for the attributes, you shouldn't use a subclass at all in this case.
EDIT
Here's what I think you meant to do:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
if you want the Employee in a different file (module), just put it there and from your main code run from Employee import Employee (the first is the module, the second is the class).
Related
I have a program the functions correctly but I have to add error checking and now I am running into an issue. The problem is that if you type in a number for the worker_name then the following time you type in a name, once you go through all of the input fields it prints out the "Production worker information" twice. How do I fix this?
Entire program:
class Employee(object):
def __init__(self, name, id_number):
self.id_number = id_number
self.name = name
class Worker(Employee):
def __init__(self, name, id_number, shift_number, pay_rate):
#call superclass __init__ method
Employee.__init__(self, name, id_number)
#initialize shift_number and pay_rate attributes
self.shift_number = shift_number
self.pay_rate = pay_rate
def main():
#variables
worker_name= " "
worker_id = " "
worker_shift = 0
worker_pay = 0.00
#get data attributes
while 1:
try:
worker_name = input("Enter the worker name: ")
print()
if not worker_name.isalpha():
print("Only letters are allowed!")
print()
main()
break
worker_id = int(input("Enter the ID number: "))
print()
worker_shift = int(input("Enter the shift number: "))
print()
worker_pay = float(input("Enter the hourly pay rate: "))
print()
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
#create an instance of Worker
Employee.worker = worker_name, worker_id, worker_shift, worker_pay
if not worker_name.isalpha():
pass
#display information
print ("Production worker information ")
print("---------------------------------")
print()
print ("Name: ", worker_name)
print()
print ("ID number: ", worker_id)
print()
print ("Shift: ", worker_shift)
print()
print ("Hourly Pay Rate: $ " + format(worker_pay, ",.2f"))
main()
You are recursively calling main() instead of allowing the while 1: loop to work.
I think you meant:
if not worker_name.isalpha():
print("Only letters are allowed!")
print()
continue
The continue will jump back to the while 1:
You shouldn't call again main() inside itself, use you try/except system
def main():
#variables
worker_name, worker_id, worker_shift,worker_pay = "", "", 0, 0
while True:
try:
worker_name = input("Enter the worker name: ")
if not worker_name.isalpha():
print("\nOnly letters are allowed!")
continue
worker_id = int(input("\nEnter the ID number: "))
worker_shift = int(input("\nEnter the shift number: "))
worker_pay = float(input("\nEnter the hourly pay rate: "))
break
except Exception as e:
print("Invalid choice! try again! " + str(e), "\n")
Use the loop to retry the input if it fails (rather than calling recursively). You can also take advantage of try/catch to make the code quite a bit shorter -- just try the whole thing you want to do in order to create the worker and then you don't need to separately declare and check each variable one at a time.
class Employee:
def __init__(self, name: str, id_number: int):
assert name.isalpha(), "Only letters are allowed in employee names!"
self.id_number = id_number
self.name = name
class Worker(Employee):
def __init__(
self,
name: str,
id_number: int,
shift_number: int,
pay_rate: float
):
# call superclass __init__ method
Employee.__init__(self, name, id_number)
# initialize shift_number and pay_rate attributes
self.shift_number = shift_number
self.pay_rate = pay_rate
def main():
# create an instance of Worker
while True:
try:
name = input("\nEnter the worker name: ")
assert name.isalpha(), "Only letters are allowed!" # fail fast!
worker = Worker(
name,
int(input("\nEnter the ID number: ")),
int(input("\nEnter the shift number: ")),
float(input("\nEnter the hourly pay rate: "))
)
break
except Exception as e:
print(f"Invalid choice! try again! {e}\n")
# display information
print(f"""
Production worker information
---------------------------------
Name: {worker.name}
ID number: {worker.id_number}
Shift: {worker.shift_number}
"Hourly Pay Rate: ${worker.pay_rate:.2f}
""")
main()
class Employee():
def __init__(self, name, salary=0):
self.name = name
self.salary = salary
def hire(self):
hired = input('is employee hired? enter yes or no')
if 'yes' in hired:
hiresalary = int(input('enter employee salary'))
self.salary = hiresalary
def fire(self):
fired = input('is employee fired? enter yes or no')
if 'yes' in fired:
employeelist.remove(self.name)
if 'no':
pass
def raise_salary(self):
input("do you want to raise {}'s salary, enter yes or no".format(self.name))
if 'yes':
raise_sum = int(input("by how much do you want to raise {} salary?".format(self.name)))
self.salary += raise_sum
if 'no':
pass
I want to know if there's a way that every instance of the class will be stored in a list so that if i call the fire method i can delete that instance from the list.
As people above said, you would ideally store a list of employees outside of your Employee class. You could then change your Employee.fire() method to accept the list of employees like so:
employees = []
class Employee():
def __init__(self, name, salary=0):
self.name = name
self.salary = salary
def hire(self):
hired = input('is employee hired? enter yes or no')
if 'yes' in hired:
hiresalary = int(input('enter employee salary'))
self.salary = hiresalary
def fire(self, employeelist):
fired = input('is employee fired? enter yes or no')
if 'yes' in fired:
employeelist.remove(self)
return employeelist
def raise_salary(self):
input("do you want to raise {}'s salary, enter yes or no".format(self.name))
if 'yes':
raise_sum = int(input("by how much do you want to raise {} salary?".format(self.name)))
self.salary += raise_sum
if 'no':
pass
bob = Employee('Bob', 50)
employees.append(bob)
sally = Employee('Sally', 75)
employees.append(sally)
employees = bob.fire(employees)
For a homework, I made an employee class file. Then I made a separate program that has a menu, from which a user can add, edit, display the content of the employee file. however, when i am trying to display, the only output coming is blank.
employee.py:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = ""
self.__employeeid = ""
self.__department = ""
self.__job_title = ""
def set_name(self, name):
self.__name = name
def set_id(self, employeeid):
self.__employeeid = employeeid
def set_department(self, department):
self.__department = department
def set_job_title(self, job_title):
self.__job_title = job_title
def get_name(self):
return self.__name
def get_employeeid(self):
return self.__employeeid
def get_department(self):
return self.__department
def get_job_title(self):
return self.__job_title
The actual program file:
import pickle
from Employee import Employee
try:
filename=open('Employee.dat','rb')
dictionary=pickle.load(filename)
except:
dictionary={}
while True:
print('\n1. Look up an employee in the dictionary')
print('2. Add a new employee in the dictionary')
print("3. Change an existing employee's name,department and job title in the dictionary")
print('4. Delete an employee from the dicionary')
print('5. Quit the program\n')
choice=input('\nEnter a choice: ')
if choice == '1':
while True:
employeeid=input('\nEnter the ID of the employee: ')
if employeeid in dictionary:
ob=dictionary[employeeid]
print('Employee Name: ',ob.get_name())
print('Employee ID: ',ob.get_employeeid())
print('Employee department: ',ob.get_department())
print('Employee job title: ',ob.get_job_title())
break
else:
print('\nEmployee not found \n')
break
elif choice== '2':
while True:
name=input('\nEnter the name of the employee: ')
employeeid=input('\nEnter the employee id: ')
dept=input('\nEnter the employee department: ')
title=input('\nEnter the employee job title: ')
ob=Employee(name,employeeid,dept,title)
dictionary[employeeid]=ob
print("employee has been added")
break
elif choice== '3':
while True:
employeeid=input('\nEnter the employee ID to change the details: ')
if employeeid in dictionary:
ob=dictionary[employeeid]
while True:
name=input('\nEnter the new name of the employee: ')
ob.set_name(name)
dept=input('\nEnter the new department of the employee: ')
ob.set_department(dept)
title=input('\nEnter the new job title of the employee: ')
ob.set_job_title(title)
break
else:
print('\nID not found \n')
elif choice == '4':
while True:
employeeid=input('\nEnter the ID of the employee to delete: ')
if employeeid in dictionary:
del dictionary[employeeid]
print('\nEmployee data removed \n ')
else:
print("Employee data not found")
elif choice == '5':
filename=open('Employee.dat','wb')
pickle.dump(dictionary,filename)
filename.close()
else:
print('\nPlease enter a valid choice ')
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program
Enter a choice: 2
Enter the name of the employee: sam
Enter the employee id: 1
Enter the employee department: 2
Enter the employee job title: 3 employee has been added
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program 4
Enter a choice: 1
Enter the ID of the employee: 1 Employee Name: Employee ID:
Employee department: Employee job title:
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program
Enter a choice:
I expected the values that i put initially to be in the second output
but it is only displaying blanks
First: Your Employee import is incorrect. If your filename is employee.py, you should write:
from employee import Employee
because your program can't find the file named Employee.py.
Second: Try not to use while True. It can easily throw your program in the infinite loop. For example: If you will select the fourth choice - Delete an employee from the dicionary - you will never return to the main menu because you can't break your infinite loop.
Third: Your Employee.__init__ creates empty fields:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = ""
self.__employeeid = ""
self.__department = ""
self.__job_title = ""
and you use no setters in the main module. Of course it will return empty strings for every field. Add setters to the main module or change employee.py to this:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = name
self.__employeeid = emplpoyeeid
self.__department = department
self.__job_title = job_title
I am having trouble passing a variable from one function to another:
def name():
first_name=input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
return surname()
def surname():
last_name=input("\nCan you tell my your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
return surname()
else:
print("Nice to meet you %s %s." % (first_name,last_name))
I want the last command to print the inputed first_name from def name() and last name from def surname()
I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:
print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
What am I doing wrong?
You need to pass the information in the function call:
def name():
first_name = input("What is your name? ")
if len(first_name) == 0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
surname(first_name) # pass first_name on to the surname function
def surname(first_name): #first_name arrives here ready to be used in this function
last_name = input("\nCan you tell my your last name please?")
if len(last_name) == 0:
print("\nYou did not enter a last name!")
surname(first_name)
else:
print("Nice to meet you %s %s." % (first_name,last_name))
name()
def functionname(untypedparametername):
# do smth with untypedparametername which holds "Jim" for this example
name = "Jim"
functionname(name) # this will provide "Jim" to the function
You can see how they are used if you look at the examples in the documentation, f.e. here: https://docs.python.org/3/library/functions.html
Maybe you should read up on some of the tutorials for basics, you can find lots of them on the python main page: https://wiki.python.org/moin/BeginnersGuide
You can also use while loop to ask the names constantly until there is a valid input.
def name_find():
while True:
first_name=raw_input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name_find()
else:
print("\nHello %s." % first_name)
return surname(first_name)
def surname(first_name):
while True:
last_name=raw_input("\nCan you tell me your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
else:
print "Nice to meet you %s %s." % (first_name, last_name)
break
I am incredibly new to Python and I really need to be able to work this out. I want to be asking the user via raw_input what the module and grade is and then putting this into the dictionary already defined in the Student class as grades. I've got no idea what to do! Thanks in advance!
students = [] # List containing all student objects (the database)
def printMenu():
print "------Main Menu------\n" "1. Add a student\n" "2. Print all students\n" "3. Remove a student\n" "---------------------\n"
class Student:
firstName = ""
lastName = ""
age = 0
studentID = ""
degree = ""
grades = {"Module Name":"","Grade":""}
def setFirstName(self, firstName):
self.firstName = firstName
def getFirstName(self):
return self.firstName
def setLastName(self, lastName):
self.lastName = lastName
def getLastName(self):
return self.lastName
def setDegree(self,degree):
self.degree = degree
def getDegree(self):
return self.degree
def setGrades(self, grades):
self.grades = grades
def getGrades(self):
return self.grades
def setStudentID(self, studentid):
self.studentid = studentid
def getStudentID(self):
return self.studentid
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
def addStudent():
count = 0
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the student's degree: ")
while count != -1:
student.grades = raw_input("Please enter the student's module name: ")
#student.grades["Grade"] = raw_input("Please enter the grade for %: " % grades)
studentid = raw_input("Please enter the student's ID: ")
age = raw_input("Please enter the student's age: ")
student = Student() # Create a new student object
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)
student.setGrades(grades)
student.setStudentID(studentid)
student.setAge(age)
students.append(student) # Add this student to the database
A few things:
Move the initialization of your class attributes into an __init__ method:
Get rid of all the getters and setters as Jeffrey says.
Use a dict that has module names as keys and grades as values:
Some code snippets:
def __init__(self, firstName, lastName, age, studentID, degree):
self.firstName = firstName
self.lastName = lastName
...
self.grades = {}
and:
while True:
module_name = raw_input("Please enter the student's module name: ")
if not module_name:
break
grade = raw_input("Please enter the grade for %s: " % module_name)
student.grades[module_name] = grade