This question already has answers here:
Python print statement “Syntax Error: invalid syntax” [duplicate]
(2 answers)
Closed 9 years ago.
I am learning to make a role playing game in Python by watching some tutorials on Youtube. The guy didn't show me how to setup anything to get it working. I did get pygame and stuff working by watching other videos. Anyway here is my error and code:
#!C:\python32
class Character:
def __init__(self, name, hp):
self.name = name
self.hp = hp
c = Character("Test", 5)
print c.name
print c.hp
Error:
File "C:\Users\Johnathan\Desktop\My Game\character\character.py", line 8
print c.name
^
SyntaxError: invalid syntax
[Finished in 0.2s with exit code 1]
In python3 print is a function, not a statement.
Try:
print(c.name)
Also you are missing an indentation after class Character:. (Rule of thumb: After most colons follows either a single statement on the same line, or an indented suite of statements.) Your code should read:
class Character:
def __init__(self, name, hp):
self.name = name
self.hp = hp
c = Character("Test", 5)
print(c.name)
print(c.hp)
Related
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
This question already has answers here:
TypeError: module.__init__() takes at most 2 arguments (3 given)
(5 answers)
Closed 3 years ago.
I am viewing the Pluralsight course on Python. At the end of the module we are to write a Python script. The author does not show how to create two of the scripts. I have them coded as the follows:
main.py
from hs_student import *
james = HighSchoolStudent("james")
print(james.get_name_capitalize)
student.py
students = []
class Student:
school_name = "Springfield Elementary"
def __init__(self, name, s_id=332):
self.name = name
self.s_id = s_id
students.append(self)
def get_name_capitalize(self):
return self.name.capitalize()
...
hs_student.py
import student as student
students = []
class HighSchoolStudent(student):
school_name = "Springfield High School"
def get_school_name(self):
return "This is a High School student"
def get_name_capitalize(self):
original_value = super().get_name_capitalize()
return original_value + "-HS"
...
When running the code, I get an error. From my understanding, I am passing too many arguments to the get_name_capitalize function. How can I fix this?
The error message is:
TypeError: module() takes at most 2 arguments (3 given)
This code:
class HighSchoolStudent(student):
is trying to inherit from the student module, not the student.Student class. Change it to:
class HighSchoolStudent(student.Student):
to inherit from the intended class.
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 4 years ago.
class Myclass(object):
def __init__(self , msg , integer):
self.msg = msg
self.integer = integer
print (self.msg)
print (self.integer)
return
Error
File "<input>", line 3
self.msg = msg
^
IndentationError: expected an indented block
This question is a duplicate, and fyi Python2 allows mixed usage of tabs and spaces but Python3 does not. It recommends using spaces for uniformity.
Please check PEP8 for more info:
https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces
EDIT:
And please indent after defining a function. It must be all indented up to the code block.
class Myclass(object):
def __init__(self , msg , integer):
self.msg = msg
self.integer = integer
print (self.msg)
print (self.integer)
return
Whitespace matters in python.
Edit: Ran without issues
>>> class MyClass(object):
... def __init__(self, msg, integer):
... self.msg=msg
... self.integer = integer
... print(self.msg)
...
>>> x = MyClass('foo', 5)
foo
This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 3 years ago.
I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting
'not defined error' for describe_restaurant().
Here is my code:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant():
print(self.r_name.title())
print(self.c_type.title())
def open_restaurant():
print(self.r_name + " is now open!")
Restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(Restaurant.r_name)
print(Restaurant.c_type)
describe_restaurant()
open_restaurant()
I thought that describe_restaurant shouldn't need to be defined though because I'm calling it out as a function to use?
Try:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant(self):
print(self.r_name)
print(self.c_type)
def open_restaurant(self):
return "{} is now open!".format(self.r_name)
restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(restaurant.r_name)
print(restaurant.c_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
You need to create a class instance and call it's functions. In addition, as mentioned in the comments, you need to pass self to the instance methods. A short explanation of this can be found here.
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