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
Related
im trynig to operate a class after it has being in a dictionary and its not working.
I'm trying to operate "balance_check_in_the_bank_account" metoud at the third "if()"
when the user ask for number "2" action.
all_bank_accounts = {}
class BankAccount():
def __init__(self, first_name, last_name, personal_number,currency, amount = 0):
self.first_name = first_name
self.last_name = last_name
self.personal_number = personal_number
self.currency = currency
self.amount = amount
def balance_check_in_the_bank_account(self):
print('The amount of money in the bank is:\n ', self.amount)
while True:
cmd = int(input(" Press 1 to create a bank account or Press 2 to other options:\n"))
if cmd == 1:
first_namee = input("What is your first name? ")
last_namee = input("What is your last name? ")
personal_numberr = input("What is your ID? ")
currencyy = input("What type of currncey would you like to use? ")
amountt = int(input("What is the amount of money would you like to deposit? "))
the_account = BankAccount(first_namee, last_namee, personal_numberr, currencyy, amountt)
dictank = {f"{personal_numberr}":the_account}
all_bank_accounts.update(dictank)
print(all_bank_accounts)
else:
personal_number = input("What is your ID? ")
if personal_number in all_bank_accounts.keys():
cmd = int(input(" Press 2 to check in the bank account.\n Press 3 to deposit cash.\n Press 4 to withrawal cash.\n Press 5 to check the average of deposits or withrawals.\n Press 6 to print an account details page ."))
if cmd == 2:
one_of_the_accounts = all_bank_accounts[f"{personal_numberr}"]
one_of_the_accounts.balance_check_in_the_bank_account
else:
print("The bank account not exist")
In my class called Commands, I have a "carstuff" command (it's a very basic command system) which is supposed to bring up my help menu, but instead it just brings up the python help menu. Here's my commands.py file:
class Commands:
pass
def askCommand(self):
command = input("Enter command: ")
if command == "carstuff":
#the other part that's having problems
help()
elif command == "sell":
pass
elif command == "addcar":
pass
#part that's having problems
def help(self):
print(
"carstuff: Brings up the help menu\nsell: Sells the current car\naddcar: Adds another car"
)
And here's my main.py file (I'm making a mockup of craigslist)
from car import Car
from commands import Commands
print("Welcome to Craigslist on the command line! Start by entering your car info below.")
brand = input("Enter your car brand: ")
model = input("Enter your car model: ")
year = input("Enter your car's year: ")
condition = input("Enter your car's condition: ")
car = Car(brand, model, year, condition)
print("Your car's price is: " + str(car.price))
print("Now that you've listed your car, you can use commands now!\n")
command = Commands.askCommand(Commands)
And I have another car.py file (but I don't know if it will be of any use)
class Car:
def __init__(self, brand, model, year, condition):
self.brand = brand
self.model = model
self.year = year
self.condition = condition
self.price = len(model) * 0.75 * 3000
if self.condition == "Bad":
self.price - 100
elif self.condition == "Brand New":
self.price + 100
def Sell(self):
sure = input("Are you sure you want to sell? (Y/N): ")
if sure == "Y" or "y":
self.sellprice = self.price % 75
print("You got " + self.sellprice + " from this car.")
elif sure == "N" or "n":
print("Sell cancelled.\n")
Finishing up a database project and I'm having issues w/ it all coming together. I keep getting the below error after the user inputs the final data request.
Traceback (most recent call last):
File "c:/Users/j/Documents/Ashford U/CPT 200/Python Code/CPT 200 - Wk 5 Final Project JC.py", line 72, in <module>
main()
File "c:/Users/j/Documents/Ashford U/CPT 200/Python Code/CPT 200 - Wk 5 Final Project JC.py", line 42, in main
if employee_found is None:
UnboundLocalError: local variable 'employee_found' referenced before assignment
The user is to be able to input the requested data and it loop to the main question of adding, viewing, querying, or editing. So far its not looping back and I'm not sure where I've gotten off the wrong track at. Any help is much appreciated as I still have to add in the ability to write this to a file. Code below.
class Employee:
def __init__(self, name, ssn, phone, email, salary):
self.name = name
self.ssn = ssn
self.phone = phone
self.email = email
self.salary = salary
def add():
name = input("Please enter the employee's name: ")
ssn = input("Please enter the employee's ssn: ")
phone = str(input("Please enter the employee's phone number xxx-xxx-xxxx: "))
email = input("Please enter the employee's email: ")
salary = str(input("Please enter the employee's salary: "))
return Employee(name, ssn, phone, email, salary)
def formatEmployee(employee, name, ssn, phone, email, salary):
print(f'---------------------------- {name} -----------------------------')
print(f'SSN: {ssn}')
print(f'Phone: {phone}')
print(f'Email: {email}')
print(f'Salary: {salary}')
print('------------------------------------------------------------------------')
def main():
employee_list = []
#Loop of questions to add, search, edit, ect.
while True:
user_input = input('Please enter a command (add, view, query, edit): ')
if user_input == 'add':
new_employee = add()
employee_list.append(new_employee)
print(f'There are now ({(len(employee_list))}) employees in the database.')
if user_input == 'view':
for employee in employee_list:
#prints(employee_list)
formatEmployee(employee)
if user_input == 'find':
ssn = input('Enter employee SSN:')
employee_found = find(ssn, employee_list)
if employee_found is None:
print('Employee not found')
else:
formatEmployee(employee_found)
if user_input == 'edit':
ssn = input('Enter SSN of employee to edit their info: ')
employee_found = find(ssn, employee_list)
edit_field = input('Please enter the employee information that you want to edit: ')
new_info = input(f'Please enter the new: {edit_field}')
print('edit complete!')
# Employee edit branches
def edit(info, newinfo, employee):
if info == 'name':
employee.name = newinfo
if info == 'ssn':
employee.ssn = newinfo
if info == 'phone':
employee.phone = newinfo
if info == 'email':
employee.email = newinfo
if info == 'salary':
employee.salary = newinfo
#Query by SSN of employee
def find(ssn, employee_list):
for employee in employee_list:
if ssn == employee.ssn:
return employee
return None
main()
The problem is in your indentation... your main function should look like this:
def main():
employee_list = []
#Loop of questions to add, search, edit, ect.
while True:
user_input = input('Please enter a command (add, view, query, edit): ')
if user_input == 'add':
new_employee = add()
employee_list.append(new_employee)
print(f'There are now ({(len(employee_list))}) employees in the database.')
if user_input == 'view':
for employee in employee_list:
#prints(employee_list)
formatEmployee(employee)
if user_input == 'find':
ssn = input('Enter employee SSN:')
employee_found = find(ssn, employee_list)
if employee_found is None:
print('Employee not found')
else:
formatEmployee(employee_found)
if user_input == 'edit':
ssn = input('Enter SSN of employee to edit their info: ')
employee_found = find(ssn, employee_list)
edit_field = input('Please enter the employee information that you want to edit: ')
new_info = input(f'Please enter the new: {edit_field}')
print('edit complete!')
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).
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