Python raw_input into dictionary declared in a class - python

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

Related

Trying to call an object from a different file but the output is only displaying blanks

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

Trying to write strings in a file using a class function

I'm trying to write a simple game and need to write some informations in a file. This is how the code looks like so far:
class Player:
def __init__(self, name, password, file):
with open(file) as inputFile:
self.playerAndPw = inputFile.read()
self.name = name
self.password = password
def add(self, name, password, file):
file.write(name + " | " + password)
def __str__(self):
print("The player's name is called " + self.name + "\n")
print("Welcome to Guess My Number!")
start = input("Press 1 for New Account, 2 for Log In: ")
if start == "1":
player = Player
playerID = input("Enter a name: ")
playerPassword = input("Enter a password: ")
fileName = "PlayerAndPassword.txt"
player.add(playerID, playerPassword, fileName)
In the last line there is an exception at the last bracket: "Parameter 'file' unfilled. So the code can't get the information out of the function I'm using in the last line.
Would be great, if someone could help me! Thank you!
This is my attempt to correct your code as best I could. As pointed out in the comments, you need to set player to an instance of the Player class by instantiating it as player = Player(...).
Because you're passing the player's name, password and the file to store credentials in to the Player constructor, you don't need to pass these as arguments to Player.add, which is why I remove all parameters for that.
I should point out that this implementation is very simple and incomplete, designed only to address your immediate issues. My implementation will result in file handles remaining open after each call to the Player constructor. If you opt for this sort of approach, you may want to read the Python documentation on input and output operations.
class Player:
def __init__(self, name, password, fileName):
self.name = name
self.password = password
self.file = open(fileName, mode='a')
def add(self):
self.file.write(self.name + " | " + self.password + '\n')
def __str__(self):
print("The player's name is called " + self.name + "\n")
print("Welcome to Guess My Number!")
start = input("Press 1 for New Account, 2 for Log In: ")
if start == "1":
playerId = input("Enter a name: ")
playerPassword = input("Enter a password: ")
fileName = "PlayerAndPassword.txt"
player = Player(playerId, playerPassword, fileName)
player.add()
Console Output
Welcome to Guess My Number!
Press 1 for New Account, 2 for Log In: 1
Enter a name: Tom
Enter a password: Foo
Welcome to Guess My Number!
Press 1 for New Account, 2 for Log In: 1
Enter a name: Dick
Enter a password: Bar
Welcome to Guess My Number!
Press 1 for New Account, 2 for Log In: 1
Enter a name: Harry
Enter a password: Baz
PlayersAndPasswords.txt
Tom | Foo
Dick | Bar
Harry | Baz
class Player:
def __init__(self, name, password, file):
self.name = name
self.password = password
self.file = open(file, mode='a') #first assign file to self.file(referring to this file)
def add(self): #need to add those parameters as they are already initialized by constructor
self.file.write(self.name + " | " + self.password)
def __str__(self):
print("The player's name is called " + self.name + "\n")
print("Welcome to Guess My Number!")
start = input("Press 1 for New Account, 2 for Log In: ")
if start == "1":
playerID = input("Enter a name: ")
playerPassword = input("Enter a password: ")
fileName = "PlayerAndPassword.txt"
player = Player(playerID, playerPassword, fileName) #create instance with said values
player.add() #call the add function to add

UnboundLocalError: local variable 'cars' referenced before assignment

I am making a program where I store and display an inventory of cars through a menu. However, I keep on receiving the error:
".py", line 24, in car_invent
cars = cars.Car(make, model, mileage, price, doors)
UnboundLocalError: local variable 'cars' referenced before assignment"
I've already imported the module in the beginning and I don't understand why it gives me this error
My code is
import cars
def print_desc(item):
print "Make:", item.get_make()
print "Model:", item.get_model()
print "Mileage:", item.get_mileage()
print "Price:", item.get_price()
def car_invent():
car_invent = []
print "Enter data for the cars."
num_cars = input("Enter number of cars: ")
for count in range(num_cars):
make = raw_input("Enter the make: ")
model = input("Enter the year model: ")
mileage = input("Enter the mileage: ")
price = input("Enter the price: ")
doors = input("Enter the number of doors: ")
cars = cars.Car(make, model, mileage, price, doors)
car_invent.append(cars)
return car_invent
def truck_invent():
truck_invent = []
print "Enter data for the trucks."
num_trucks = input("Enter number of trucks: ")
for count in range(num_trucks):
make = raw_input("Enter the make: ")
model = input("Enter the year model: ")
mileage = input("Enter the mileage: ")
price = input("Enter the price: ")
drive_type = input("Enter the drive type: ")
trucks = cars.Truck(make, model, mileage, price, drive_type)
truck_invent.append(truck)
return truck_invent
def suv_invent():
suv_invent = []
print "Enter data for the cars."
num_suv = input("Enter number of SUVs: ")
for count in range(1, num_suv):
make = raw_input("Enter the make: ")
model = input("Enter the year model: ")
mileage = input("Enter the mileage: ")
price = input("Enter the price: ")
pass_cap = input("Enter passenger capacity: ")
suv = cars.SUV(make, model, mileage, price, pass_cap)
suv_invent.append(suv)
return suv_invent
def read_invent(car_invent, truck_invent, suv_invent):
print "USED CAR INVENTORY"
print "=================="
print "The following car is in inventory."
for item in car_invent:
print_desc(item)
print "Number of doors:", item.get_doors()
print "The following pickup truck is in inventory."
for item in truck_invent:
print_desc(item)
print "Drive type:", item.get_drive_type()
print "The following SUV is in inventory."
for item in suv_invent:
print_desc(item)
print "Passenger Capacity:", item.get_pass_cap()
def menu():
print "MENU"
print "====="
print "1. Enter data for inventory"
print "2. Display inventory"
print "3. Quit"
def main():
menu()
choice = input("Enter choice: ")
while choice != 3:
if choice == 1:
cars = car_invent()
trucks = truck_invent()
suv = suv_invent()
choice = input("Enter choice: ")
elif choice == 2:
read_invent(cars, trucks, suv)
choice = input("Enter choice: ")
else:
print "Invalid choice"
choice = input("Enter choice: ")
main()
Here is also the module for reference:
class Automobile:
def __init__(self, make, model, mileage, price):
self.__make = make
self.__model = model
self.__mileage = mileage
self.__price = price
def set_make(self, make):
self.__make = make
def set_model(self, model):
self.__model = model
def set_mileage(self, mileage):
self.__mileage = mileage
def set_price(self, price):
self.__price = price
def get_make(self):
return self.__make
def get_model(self):
return self.__model
def get_mileage(self):
return self.__mileage
def get_price(self):
return self.__price
class Car(Automobile):
def __init__(self, make, model, mileage, price, doors):
Automobile.__init__(self, make, model, mileage, price)
self.__doors = doors
def set_doors(self, doors):
self.__doors = doors
def get_doors(self):
return self.__doors
class Truck(Automobile):
def __init__(self, make, model, mileage, price, drive_type):
Automobile.__init__(self, make, model, mileage, price)
self.__drive_type = drive_type
def set_drive_type(self, drive_type):
self.__drive_type = drive_type
def get_drive_type(self):
return self.__drive_type
class SUV(Automobile):
def __init__(self, make, model, mileage, price, pass_cap):
Automobile.__init__(self, make, model, mileage, price)
self.__pass_cap = pass_cap
def set_pass_cap(self, pass_cap):
self.__pass_cap = pass_cap
def get_pass_cap(self):
return self.__pass_cap
cars = cars.Car(make, model, mileage, price, doors)
You declare a local variable named cars
You assign cars.Car(...) to cars
But cars is a local variable which doesn't have a value yet (unbound local)
Your program crashs

Python Modules, passing values to args

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).

Using a Loop to add objects to a list(python)

I'm trying to use a while loop to add objects to a list.
Here's basically what I want to do:
class x:
pass
choice = raw_input(pick what you want to do)
while(choice!=0):
if(choice==1):
Enter in info for the class:
append object to list (A)
if(choice==2):
print out length of list(A)
if(choice==0):
break
((((other options))))
I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.
Here is the code I have so far:
print "Welcome to the Student Management Program"
class Student:
def __init__ (self, name, age, gender, favclass):
self.name = name
self.age = age
self.gender = gender
self.fac = favclass
choice = int(raw_input("Make a Choice: " ))
while (choice !=0):
if (choice==1):
print("STUDENT")
namer = raw_input("Enter Name: ")
ager = raw_input("Enter Age: ")
sexer = raw_input("Enter Sex: ")
faver = raw_input("Enter Fav: ")
elif(choice==2):
print "TESTING LINE"
elif(choice==3):
print(len(a))
guess=int(raw_input("Make a Choice: "))
s = Student(namer, ager, sexer, faver)
a =[];
a.append(s)
raw_input("Press enter to exit")
Any help would be greatly appreciated!
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}

Categories