Please can someone help me to fix the code, I want to create a school class and create an object. After that, I want to use the join function to add students ( if a student exists it will not add it and it will show a message, and if not exists it will add the student), same as the leave function (it will delete from the list only if exists). and finally, the show_all function will display all the values in the list. I think the structure of the code is wrong, so please can someone help me
class School:
def __init__(self):
print("A class has opened!")
def join(self, student):
self.student = student
if self.student not in my_school:
print(self.student +" is a new member of the school!")
else:
print("We already have "+ self.student +".")
def leave(self):
if self.student in my_school:
del self.student
else:
print("No such student")
def show_all(self):
print(my_school)
# create new object in class
my_school = School()
# add the student if not exists only
my_school.join('Sarah')
# delete if exists
my_school.leave("Noor")
# show all the list
my_school.show_all()
Your code has several errors:
When you call join (a bad method name, because it already exists) you reassign the student to single variable.
In leave you reference the instance witch is not possible because it doesn't jet exist.
Here is some code:
class School:
def __init__(self):
print("An instance of School was created!")
self.students = []
def join(self, student):
if student not in self.students:
self.students.append(student)
print(student + " is a new member of the school!")
else:
print("We already have "+ student +".")
def leave(self, student):
if student in self.students:
self.students.remove(student)
else:
print("No such student")
def show_all(self):
print(self.students)
# create new object in class
my_school = School()
# add the student if not in students
my_school.join("Sarah")
# delete the student if in the students list
my_school.leave("Noor")
# print the students
my_school.show_all()
This is by no means good code, but comes close to what you wanted to achieve.
Related
i'm making a little game for fun and i ran into an issue, how can i see if the email of a member is assigned to a instance?
file1:
if "test1#gmail.com" in file2:
print("ok"
else:
print("not ok")
file2:
player1 = Player("testName1", "test1#gmail.com", "testpwd1"
player2 = Player("testName2", "test2#gmail.com", "testpwd2"
player3 = Player("testName3", "test3#gmail.com", "testpwd3"
player4 = Player("testName4", "test4#gmail.com", "testpwd4"
overriding the __contains__ method will do the trick.
So:
def __contains__(self, key):
return key in self.email
Edit:
If for some reason you don't care which attribute contains the value, this will work:
def __contains__(self, key):
return key in list(self.__dict__.values())
If you put Players in a list then you could use a dictionary to index that list. This example lets you look up by name and email at the same time.
file2.py
class Player:
def __init__(self, name, email, pwd):
self.name = name.lower()
self.email = email.lower()
self.pwd = pwd
players = [
Player("testName1", "test1#gmail.com", "testpwd1"),
Player("testName2", "test2#gmail.com", "testpwd2"),
Player("testName3", "test3#gmail.com", "testpwd3"),
Player("testName4", "test4#gmail.com", "testpwd4")
]
# index to lookup up player by name or email
player_index = {player.name:player for player in players}
player_index.update({player.email:player for player in players})
file1.py
import file2
if file2.player_index.get("test1#mail.com".lower(), None) is not None:
print("ok")
else:
print("not ok")
It would be common to place that players list in some other data structure like a CSV file or even a pickled file. Assuming you want to update players dynamically, it becomes awkward to represent them as class instances in a .py file. But that's an enhancement for another time.
I have a book library program that it's class reads a file containing ID and name and assign them to self objects as id and card holder. then there is self object for borrowed books, so then I can identify which user borrowed which book.
The problem is in main function when a user return a book, I don't know how to update the self borrowed book object to delete that book from the object, so the self id will not have books borrowed to it.
Here is how the class looks:
#loan time length is 3 weeks by default
LOAN_TIME = 3
class Librarycard:
def __init__(self, card_id, card_holder):
self.__id = card_id
self.__holder = card_holder
#a dictionary that will contain the full book : loan time, updated in later function
self.__loan = {}
def return_book(self, book):
del self.__loan[book]
print('returned')
return
and this is my main function part which concern the book loaning:
def main():
command = input("Command: ")
#borrowed books main list to check if book borrowed or not
borrowed_books = []
if command == "R":
book = input("Book code: ")
if book not in borrowed_books:
print('This book has not been borrowed by anyone')
else:
del borrowed_books[book]
print('book returned')
# this is where I try to enter the function from the class to update the object
# dictionary
book.return_book(book)
if __name__ == "__main__":
main()
A couple of issues here.
First, the book that comes from the input is a string and not the actual book class. So, when calling book.return_book(book), the compiler is looking for a method return_book in the string class (which is obviously not there).
Second, borrowed_books is never being updated in the main class, so the user will never return any books.
Third, instead of using del in the Class, use self.__loan.pop(book). It is the inbuilt python function, and is a better way to remove the book.
Finally, there are a lot of camel case issues
Here is what the final code may look like.
class LibraryCard:
def __int__ (self, card_id, card_holder):
self.card_id=card_id
self.__card_holder=card_holder
self.checked_out={}
def return_book (self, book_id):
popped = self.checked_out.pop(book_id, "Book was already returned, or was never checked out")
if (popped != "Book was already returned, or was never checked out"):
print("Book returned: "+popped)
else:
print(popped)
def isCard(self, id, name):
return self.card_id==id and self.__card_holder==name
def main():
cards = {}
while (true):
command = input("To check out a book press \"C\", to return a book press \"R\" (without the quotes):\t")
print("Whether or not you have an account, please follow the instructions below")
card_id=input("Enter your card id:\t")
user_name=input("For security purposes, enter your name:\t")
if (user_id not in cards):
print("Welcome to Library Services")
cards[user_id] = LibraryCard(card_id, user_name)
if (not cards[user_id].isCard(user_id, user_name)):
print("Wrong user name or user id, please retry")
continue
if (command=="C"):
book=input("Enter the name of the book you would like to check out: ")
cards[user_id].checked_out[book]=3
print("Checked out successfully!")
else:
book=input("Enter the name of the book you would like to return: ")
cards[user_id].return_book(book)
class Librarycard:
def __init__(self, card_id, card_holder):
self.__id = card_id
self.__holder = card_holder
# a dictionary that will contain the full book : loan time, updated in later function
self.__loan = {'tttt': {},"uuuu":{}}
def return_book(self, book):
del self.__loan[book]
print('returned')
return
def main():
# command = input("Command: ")
command = "R"
# borrowed books main list to check if book borrowed or not
borrowed_books = ["tttt","aaaa"]
if command == "R":
# book = input("Book code: ")
book = "tttt"
if book not in borrowed_books:
print('This book has not been borrowed by anyone')
else:
borrowed_books.remove(book)
print('book returned')
library_book = Librarycard('card_id', 'you know holder')
print("before ",library_book._Librarycard__loan)
library_book.return_book(book)
print("after ",library_book._Librarycard__loan)
if __name__ == "__main__":
main()
C:\Users\sharp\AppData\Local\Programs\Python\Python39\python.exe C:/Users/sharp/Desktop/project/testid.py
book returned
before {'tttt': {}, 'uuuu': {}}
returned
after {'uuuu': {}}
Process finished with exit code 0
I have fixed it in a way that I added a new variable that connects the class in the main function, then did a loop that runs into all the cards inside the class keys of the class, and finally with that key I activated the return book function.
The main issue was that I didn't create an access for which ID I wanted to delete the book from. but once activated with the for loop I was able to reach all ID'S object and delete the book from the one that has it.
Here is how the code looks like in the specific parts concerning this problem:
def main():
#function that reads the text file and assign the card ids and card holders as a
#dictionary.
library = read_card_data("library.txt")
while True:
command = input("Command: ")
if command == "R":
book = input("Book code: ")
if book not in borrowed_books:
print('This book has not been borrowed by anyone')
else:
del borrowed_books[book]
for card in library.keys():
library[card].return_book(book)
Here is what i have so far
from CSE_324_course import Course
from CSE_324_skeleton_student import Student
math = Course("Algebra I")
language = Course("Spanish I")
science = Course("Earth Science")
history = Course("U.S. History I")
phys_ed = Course("Physical Education I")
speaking = Course("Speech I")
art = Course("Art I")
test_student = Student("Jill", "Sample")
test_student.add_course(math)
test_student.add_course(language)
test_student.add_course(science)
test_student.add_course(history)
test_student2 = Student("Bill", "Sample")
test_student2.add_course(math)
test_student2.add_course(phys_ed)
test_student2.add_course(science)
test_student2.add_course(history)
test_student3 = Student("Kim", "Sample")
test_student3.add_course(language)
test_student3.add_course(speaking)
test_student3.add_course(science)
test_student3.add_course(art)
student_list=[test_student,test_student2,test_student3]
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
#Each iteration should:
#get,concatenate, and print the first and last name of the student
#print all courses for that student
#print a blank line between students
'''for this part you may need to review the other skeleton code to:
- see how to get items from a list
- see if there is code (like a function) in that file you can call in this file
- verify that running this file gets you the correct output with information from that file
Also, review syntax of pulling items from a list f
2 page of code
Course import Course
class Student:
student_id = 0
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.courses = []
self.student_id = Student.student_id
Student.student_id += 1
def __str__(self):
# TODO You will need to use a variable in the loop, so you must intialize it here,
# that variable will need to be initalized to get items listed in the first def _init_ section
# TODO add a loop that will go through the course list
# TODO Add code here to create a string representation of a student,
# including first and last name and all courses that student is taking
return "complete this return statement based on your in loop variable"
def get_first_name(self):
return self.first_name
def get_last_name(self):
return self.last_name
def get_student_id(self):
return self.student_id
def add_course(self, new_course):
# TODO add code to append new_course to self.courses
print "Course not yet added, implementation needed."
3rd page
class Course:
def __init__(self, course_name):
self.course_name = course_name
def __str__(self):
return self.course_name
I think you are looking to change
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
(which you have improperly indented) to:
for student in student_list:
print("{} {}".format(student.first_name, student.last_name))
for course in student.courses:
print(course) # This won't work because "2 page of code Course import Course" needs to be finished
print("\n") # blank line between students
I am having trouble getting my Python program to work for my class assignment. I have written what I think is the correct code but I still get errors like:
*NameError: name 'self' is not defined* Here is the Assignment:
Create a final program that meets the requirements outlined below.
Create an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:
private string make
private string model
private string color
private int year
private int mileage
Your program should have appropriate methods such as:
constructor
add a new vehicle
remove a vehicle
update vehicle attributes
At the end of your program, it should allow the user to output all vehicle inventory to a text file.
Below is my code and any help is appreciated:
class Automobile:
def __init__(self, make, model, color, year, mileage):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
def add_vehicle(self):
auto = Automobile()
vehicle_file = open('vehicle.txt', 'a')
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = input("Enter year: ")
mileage = input("Enter mileage: ")
vehicles = Automobile(make, model, color, year, mileage)
vehicle_list = [vehicles.make, vehicles.model, vehicles.color, vehicles.year, vehicles.mileage]
for i in vehicle_list:
vehicle_file.write("%s\t" % item)
vehicle_file.write("\n")
vehicle_file.close()
print("Your record has been succesfully added to the inventory")
def delete_vehicle(self):
del_rec = input("Enter record to delete: ")
with open("vehicle.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if del_rec not in line:
f.write(line)
f.truncate()
print("Succesfully deleted record from inventory")
def set_make(self, make):
self.make = make
def get_make(self):
return self.make
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_year(self, year):
self.year = year
def get_year(self):
return self.year
def set_mileage(self, mileage):
self.mileage = mileage
def get_mileage(self):
return self.mileage
def main():
menu = {}
menu['1']="Add Vehicle."
menu['2']="Delete Vehicle."
menu['3']="Find Vehicle"
menu['4']="Exit"
user=True
while user:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Exit/Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
Automobile.add_vehicle
elif ans=="2":
Automobile.delete_vehicle(self)
elif ans=="3":
print(Automobile.vehicles)
elif ans=="4":
print("\n Goodbye")
break
elif ans !="":
print("\n Invaild Entry")
if __name__ == "__main__":
main()
Assuming you are importing this module you have created and using it in main, it works fine for me. The only thing you need to change is to change i to item in your for loop, and remove the self in delete vehicle all the way at the bottom. This removed all of the errors for me from your class. Also Please do note that if you are supposed to be using private and protected variables you need to add for ex: __self.Make. Your variables are currently not private or protected. by adding the _ or __ modifier you make the variables private or protected. I'm guessing you have a vague idea of what private and protected do, but that's why you need the getter and setters. give that a shot and see if it helps! also if you are still unclear please make sure to look back over private and protected variables. also not sure if your add vehicle method will work at the bottom because you didn't close the parentheses. it should be addvehicle()
I have a huge problem right now, I cannot refer to my Player-attributes, my code is looking like this currently:
from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.ones=0
self.twos=0
self.threes=0
self.fours=0
self.fives=0
self.sixs=0
self.abovesum=0
self.bonus=0
self.onepair=0
self.twopair=0
self.threepair=0
self.fourpair=0
self.smalladder=0
self.bigladder=0
self.house=0
self.chance=0
self.yatzy=0
self.totalsum=0
#self.lista={"ones":0,"twos":0,"threes":0, "fours":0,"fives":0,"sixs":0,"abovesum":0,"bonus":0,"onepair":0,"twopair":0,"threepair":0,"fourpair":0,"smalladder":0,"bigladder":0,"house":0,"chance":0,"yatzy":0,"totalsum":0}
def __repr__(self):
return self.name
def __str__(self):
return self.name
def countbonus(self):
self.abovesum=self.ones+self.twos+self.threes+self.fours+self.fives+self.sixs
if self.abovesum>=63:
self.bonus+=50
return self.abovesum, self.bonus
else:
return self.abovesum, self.bonus
def counttotalsum(self):
self.totalsum=self.abovesum+self.bonus+self.onepair+self.twopair+self.threepair+self.fourpair+self.smalladder+self.bigladder+self.house+self.chance+self.yatzy
def add(self):
moment=input("Where do you want to put your points?: ") #ej klar
points=input("How many points did you get?: ")
self.lista
def visa(self):
for i in self.name:
print(i)
def welcome():
print("Welcome to the yahtzee game!")
players = int(input("How many players: "))
rounds=0
spelarlista=[]
spelarlista.append("name")
while not players==rounds:
player=input("What is your name?: ")
rounds=rounds+1
spelarlista.append(Player(player))
table_data = [spelarlista,
['Ettor',spelarlista[0].ones],
['TvÄor'],
['Treor'],
['Fyror'],
['femmor'],
['sexor']]
table = AsciiTable(table_data)
table.inner_row_border = True
table.table_data[0][0] += '\n'
print(table.table)
welcome()
I'm currently getting the errormessage "Str"-object has no attribute "ones". I understand that the line spelarlista[0].ones is not working, but let's say I ru the programme with the players "James" and "Anders", and I want my yatzy to print out the table with the players current score, how do I refer to that, let's say I did type "James" first, what do I write to get his points?
Thanks in advance!
spelarlista.append("name") means that the first item in your list is a string. Then later you try to access spelarlista[0].ones.
As the error message says, string objects do not have an attribute ones.