What's wrong with my python classes? - python

Can anyone tell me what's wrong with my class code? When I executed it, the program just pop up "Indentation Error: unindent does not match any outer indentation level"
The following is my code:
class Student:
totalStudents = 0
def __init__(self, name, year):
self.name = name
self.year = 0
self.grade = []
self.attend = 0
print("Add {0} to the classroom".format(self.name) )
Student.totalStudents += 1
def addGrade(self, grade):
self.grade.append(grade)
def attendDay(self):
self.attend += 1
def classAverage(self, grade):
return sum(self.grade) / len(self.grade)
def __str__(self, name, grade):
return "{0} is a {1} grader studnet".format(self.name, self.year)

This code works when I run it in the current edit of the question -- the question was edited by #KillianDS, and I presume he/she unwittingly fixed the problem by fixing the formatting.
Looking at the original edit, the problem appears to be on your first line after class Student:. The line totalStudents = 0 is indented 2 levels in, whereas the line before it (class Student:) is not indented at all. EDIT: You also mix tabs and spaces, which causes problems.
Your formatting should look like this:
(Note: use 4 spaces, not a tab character! You should adjust your text editor so that it uses spaces, not tabs, when you hit the tab key.)
class Student:
totalStudents = 0
def __init__(self, name, year):
self.name = name
self.year = 0
self.grade = []
self.attend = 0
print("Add {0} to the classroom".format(self.name) )
Student.totalStudents += 1

While programming with Python you should take care of ;
Don't use TAB character
or
Be sure your editor to converts your TAB character to space characters

Related

Is there a cleaner method to pass a list of 10 or more values to a class and its function in python2.7 and execute them? [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 3 years ago.
Code Problem: Take userinput from a file and execute the class and its function line by line. The userinput will be like a list with 10 or more values. I have reduced the number of items for discussion purpose. I can make the code work and get the output but wondering if there is any cleaner method which can be scaled easily.
Note: Python2.7 cannot use 3.7 yet
##Below is an example code and its output
\\
class student():
def __init__(self,name,age,club):
self.name=name
self.age=age
self.club=club
def get_club(self):
if int(self.age)<10 and self.club=="lego":
print("Student :"+self.name+' is in: '+self.club+ ' club')
elif int(self.age)>15 and self.club=="football":
print("Student :"+self.name+' is in: '+self.club+ ' club')
else:
print("Student :"+self.name+' is in: '+self.club+ ' club')
ui=[("Jim,8,lego"),("Dwight,16,football"),("Pam,21,arts")]
for i in ui:
xy=i.split(',')
c=student(xy[0],xy[1],xy[2])
c.get_club()
\\
Code Output
Student :Jim is in: lego club
Student :Dwight is in: football club
Student :Pam is in: arts club
As a simple example in python2, you'll want to use argument unpacking here.
class X:
def __init__(self, a, b):
self.a = a
self.b = b
a = range(2)
x = X(*a)
x.a
0
x.b
1
To show this for your specific example, I'm using StringIO to simulate a file:
from StringIO import StringIO
ui=[("Jim,8,lego"),("Dwight,16,football"),("Pam,21,arts")]
class Student:
def __init__(self, name, age, club):
self.name = name
self.age = int(age)
self.club = club
def get_club(self):
"""
You'll want to use string formatting here, it makes code much
more readable, and allows the support of different formats
"""
if self.age < 10 and self.club == "lego":
print("Student : {} is in {} ".format(self.name, self.club))
elif self.age > 15 and self.club == "football":
print("Student : {} is in {} ".format(self.name, self.club))
else:
print("Student : {} is in {} ".format(self.name, self.club))
# you'll want to use `with open(file) as fh:` instead of
# this, which is just an example
fh = StringIO('\n'.join(ui))
for line in fh:
line = line.strip().split(',')
# note the * here before the iterable
c = Student(*line)
c.get_club()
Student : Jim is in lego
Student : Dwight is in football
Student : Pam is in arts
str.format is portable from python2 to python3, and good on you for using the parentheses on print, that will make your eventual migration journey much easier

(Classname) has no attribute (attribute)

I'm trying to create a DnD style dungeon crawler game. I'm using the 5E SRD and other publicly available information as the base for my characters and gameplay.
Currently I'm working on the character generator, and it seems to be going well, but I've hit a roadblock when trying to assign the racial bonuses. I've got the races set up as their own subclasses, each with it's unique bonuses. When I try to assign the appropriate bonuses based on the character's race I get a (Classname)has no attribute (attribute) error.
python
class Race:
def __init__(self, race):
self.name = race
self.racial_str_bonus = 0
self.racial_char_bonus = 0
class Dragonborn(Race):
def __init__(self):
super()
self.name = "Dragonborn"
self.racial_str_bonus = +2
self.racial_char_bonus = +1
def get_racial_bonus(race):
race = race
racial_str_bonus = 0
racial_char_bonus = 0
if race == "Dragonborn":
racial_str_bonus = Dragonborn.racial_str_bonus
racial_char_bonus = Dragonborn.racial_char_bonus
return racial_str_bonus, racial_char_bonus
class BaseCharacter:
def __init__(self, racial_str_bonus, racial_char_bonus):
self.racial_str_bonus = racial_str_bonus
self.racial_char_bonus = racial_char_bonus
#classmethod
def generate_player_character(cls):
cls.race = input("Race: ")
get_racial_bonus(cls.race)
BaseCharacter.generate_player_character()
What I'm looking for is something along the line of:
'''
Race: Dragonborn
print(my_player_char.racial_str_bonus)
2
'''
Where am I goofing up?
Thanks, everyone for the feedback. In cleaning up the code to get it minimally reproducible, I figured out the issue. Per Jonrsharpe's note, I corrected the inhertance invocation to 'super().init(self)'. Once that was correct, I realized that the way they had been defined, I had to include parentheses in the property call: "Dragonborn().racial_str_bonus".
Thanks again, and I will remember to improve my submissions in the future.

How to make a function that calls aand prints each students name and courses

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

Error on codeacademy labs writing python script

this is my first attempt at coding a game with python. I am at trying to run it through codeacademy labs but it says this:
File "<stdin>", line 7
__init__(self, name, size_v, size_h):
^ SyntaxError: invalid syntax Unknown error.
don't be afraid of hurting my feelings I am a very novice coder and I know I'm probably making quite a few mistakes.
I supposed I'm also looking for an explanation or alternative on how to code and experiment in a different setting (i think it's called an IDE)
from datetime import datetime
log = open("log.txt", "a")
class Ocean(object):
__init__(self, name, size_v, size_h):
self.name = name
self.size_v = size_v
self.size_h = size_h
class Ship(object):
__init__(self, size):
self.health = size
self.size = size
class BattleShip(Ship)
__init__(self):
self.health = 4
self.size = 4
class AirCarrier(Ship)
__init__(self):
self.health = 6
self.size = 6
class MedicShip(Ship)
__init__(self, size):
self.health = 2
self.size = 2
class ArmouredShip(Ship)
__init__(self, size):
self.health = 3
self.size = 2
def create_user_profile(username):
user_profile = open(username + "prof", "r+")
def create_default_ocean(name):
ocean = Ocean(name, 20, 20)
return ocean.populate(2,1,1,1)
def mainload():
gametime = datetime.now()
gamestate = "mainmenu"
username = str(raw_input("What is your name? "))
create_user_profile(username)
gametype = str(raw_input("What do you want to play? (QUICKPLAY) (CUSTOM)"))
log.write("[] " + gametime + " [] " + gamestate + " [] " + username + " [] " +gametype")
quick = "quick quickplay qp q"
custom = "custom cust c"
mainload()
if gametype.lower() in quick:
ocean = create_default_ocean(newocean)
elif gametype.lower() in custom:
#get height/width of ocean
#get amount of ships/size
There's 4 kind of errors in your script:
You forget the def identifier before each function:
class Ocean(object):
def __init__(self, name, size_v, size_h):
# ^^^
self.name = name
self.size_v = size_v
self.size_h = size_h
See documentation examples to get the syntax of classes :)
You forget some semicolons after class definition
class MedicShip(Ship):
# ^ this one
You also have a syntax error in the last function (mainload), there's a quote at the end. The correct line is:
log.write("[] " + gametime + " [] " + gamestate + " [] " + username + " [] " +gametype)
Finally, if you want to execute your code, you'll need to put something (other than comments) in the elif block at the end of your file. Otherwise, the interpreter will raise a syntax error (EOF error). Put a pass statement if you don't want to put any code for the moment:
elif gametype.lower() in custom:
pass # <- do nothing but create a correct block for the elif
#get height/width of ocean
#get amount of ships/size
I recommend you to read some beginner Python tutorial to learn the syntax ;)
You should define your function __init__() by writing def __init__(self, size)
also in some places you have forgotten to put ':' after defining class.
If you are a beginner in python u can get tutorial here(official python documentation)
To practice some basic programming stuff go to www.codingbat.com

How to give an object (has-a) an object of another class

So I was having some trouble with some code I'm doing for a basic game that I'm writing in my learning of Python (original question here if it helps).
After a lot of playing around with it, I realized my problem. I don't actually know how to do a "has-a" when trying to let one object (a character) "have" an object of another class (such as a weapon).
If I want, say a Char (character) called dean to do an action specific to the weapon he has. How would I give that object (the Char dean) an object of class "Weapon"?
Thank you.
Edit:
I've found that I can do this by passing the "Weapon" in question as an argument. i.e.:
dean = Char("Dean", hanzo_blade)
Then having Char init with (self, name, weapon).
However, I want the user to choose, from a selection, which weapon the character gets. So I'm not sure if the content of the Char(_____) can be determined on a dynamic basis from user input. If it's possible, how can I do that? If not, what do I do?
Thanks again.
Edit 2: Here is the pertinent code:
class Char(object):
def __init__(self, name):
self.name = name
self.hp = 300
self.mp = 10
self.strn = 1
self.dex = 1
self.armor = 0
self.xp = 0
self.items = []
self.spells = []
self.weapon = sword() # Assume sword is the default. Alternatively, how might I let this default to nothing?
class Weapon(Equip):
impact = 1
sharp = 1
def __init__(self, name):
self.name = name
hanzo_blade = Weapon("Hanzo Blade")
hanzo_blade.wgt = 3
hanzo_blade.impact = 1
hanzo_blade.sharp = 9
dean = Char("Dean")
dean.strn = 3
dean.dex = 8
If hanzo_blade is one option, how could I let the player, for instance, select that Weapon for the Char dean?
Are you aware of the raw_input builtin? (input in Python 3)
# We assume we already have sword, fists, and stern_glare objects
# representing weapons.
weapons = {'sword': sword, 'fists': fists, 'stern glare': stern_glare}
# Prompt for a choice, and keep prompting until you get a valid choice.
# You'll probably want a more user-friendly prompt.
valid_choice = False
while not valid_choice:
weapon_choice = raw_input('Select your weapon')
valid_choice = weapon_choice in weapons
# Create the character.
dean = Char('Dean', weapons[weapon_choice])

Categories

Resources