It requires isgood to be a string only. I want it to be boolean.
Also self.__isgood = goodornot should throw an error, why not?
class Animal:
Name = ""
isgood = None
def setisgood(self,goodornot):
self.__isgood = goodornot
def nameset(self,name):
self.Name = name
dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)
So then convert it to a string.
print("Your pet is: {}".format(dog.isgood))
print("Your pet is:"+dog.isgood)
is attempting to concatenate a boolean and a string, which cannot be done. In order to do so, you either need to convert dog.isgood into a string
print("Your pet is:" + str(dog.isgood))
like TheoretiCAL suggested in the comments, or use format
print("Your pet is:{}".format(dog.isgood))
like Ignacio Vazquez-Abrams answer, or
print("Your pet is:%s" % dog.isgood)
or,
print("Your pet is:", dog.isgood)
All of these examples will result in the following output:
Your pet is:False
Edit:
Thank you juanpa for pointing this out. The spacing on the class is incorrect and should be causing an issue (I guess I assumed initially that it was just a copy paste thing).
class Animal:
def __init__(self):
self.Name = ""
self.isgood = None
def setisgood(self,goodornot):
self.isgood = goodornot
def nameset(self,name):
self.Name = name
dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:", dog.isgood)
Related
I develop bottom up, starting with small simple methods to go to the big full fledged implementation
class Pop(object):
def welcome(self, name, new_member = False):
response = ""
if new_member:
response = " NOT"
return str("hello there "+name+", you seem"+response+" to be a member\n")
def ageVerification(self, name, age, new_member = False):
the_welcome_string = self.welcome(name, new_member)
minimum = ""
excuse = ""
if age < 16:
minimum = " NOT"
excuse = ", sorry"
return str(the_welcome_string+str(age)+" is"+minimum+" the minimum required age to buy beer in Belgium"+excuse+"\n")
def theWholething(self, name, age, address, new_member = False):
if age < 16:
appology = str("you cannot order any beer\n")
else:
appology = str("your beer will be shipped to "+address+"\n")
return str(self.ageVerification(name, age, new_member)+appology)
# EOF
My question is if it is normal that when i reach theWholeThingMethod, I carry along all the parameters of the previously defined methods? Is this pythonic?
My population class has almost 20 "helper" methods called in theWholeThing, and it seems I am just fiddling with parameters to get them in the right order ...
theWholeThing(self,\
name,\
age,\
address,\
registered = True,\
first_date_entered,\
last_date_entered,\
purchased_amount,\
favorite_beer,\
promotional_code,\
and_so_on0,\
and_so_on1,\
and_so_on2,\
and_so_on3,\
and_so_on4,\
and_so_on5,\
and_so_on6,\
and_so_on7,\
and_so_on8,\
and_so_on9,\
and_so_on10):
My question is if it is normal that when i reach theWholeThingMethod, I carry along all the parameters of the previously defined methods? Is this pythonic?
Neither.
There is really no point in having a class if all the methods take all the arguments anyway. These might as well just be functions.
There are many ways this could be done, depending on whether the various parameters are mandatory, or what happens when one is not provided, but here is one possibility:
from dataclasses import dataclass
#dataclass
class Pop(object):
name: str
age: int
address: str
new_member : bool = False
def welcome(self):
response = ""
if self.new_member:
response = " NOT"
return str("hello there "+self.name+", you seem"+response+" to be a member\n")
def ageVerification(self):
the_welcome_string = self.welcome()
minimum = ""
excuse = ""
if self.age < 16:
minimum = " NOT"
excuse = ", sorry"
return str(the_welcome_string+str(self.age)+" is"+minimum+" the minimum required age to buy beer in Belgium"+excuse+"\n")
def theWholething(self):
if self.age < 16:
appology = str("you cannot order any beer\n")
else:
appology = str("your beer will be shipped to "+self.address+"\n")
return str(self.ageVerification()+appology)
# EOF
Note: #nneonneo had a great suggestion of using a dataclasses, so answer tweaked to incorporate that
I’m new and still learning but I’m making a random character Generator and I don’t know how to make it stop or end the code and start a new one.
import random
Rac = ["Human", "Half-Human", "Not Human"]
Race = random.choice(Rac)
Age = random.randint(1,100)
skil = [“Beserker”,”Mage”,”Assassin”]
Skill = random.choice(skil)
Gende = [“Male”,”Female”]
Gender = random.choice(Gende)
class human:
def __dir__(self):
return[Race,Age,Skill,Gender]
person = human()
print(dir(person))
print(“Race: {}, Age: {}, Class: {}, Gender: {}”.format(Race,Age,Class,Gender))
I have two of these but the ages keep printing out the same and I don’t know how to separate them so it’s a different age and not the same number for both.
I need to end the Age for that generator because it interferes and makes it all the same age, Instead of random ages.
Sorry for being confusing.
Based on what I understood,
First of all, I have corrected the code and removed syntax errors.
(Below given code is not an answer. It is just the updated code. I have given my answer below that.)
import random
Rac = ["Human", "Half-Human", "Not Human"]
Race = random.choice(Rac)
Age = random.randint(1,100)
skil = ["Beserker", "Mage", "Assassin"]
Skill = random.choice(skil)
Gende = ["Male", "Female"]
Gender = random.choice(Gende)
class human:
def __dir__(self):
return [Race, Age, Skill, Gender]
person = human()
print(dir(person))
print("Race: {}, Age: {}, Skill: {}, Gender: {}".format(Race, Age, Skill, Gender))
My answer :
Now,
When you create the random object,
Here : Age = random.randint(1,100)
It gets called only once, so only one random number is generated and you are using it 2 times.
I have two of these but the ages keep printing out the same and I don’t know how to separate them how do I separate them so it’s a different age and not the same number for both
What you need, is to generate this number inside the class definition. So it will get called every time you create the object of that class.
Code:
import random
class human:
def __dir__(self) -> list:
self.Rac = ["Human", "Half-Human", "Not Human"]
self.Race = random.choice(self.Rac)
self.Age = random.randint(1,100)
self.skil = ["Beserker", "Mage", "Assassin"]
self.Skill = random.choice(self.skil)
self.Gende = ["Male", "Female"]
self.Gender = random.choice(self.Gende)
return [self.Race, str(self.Age), self.Skill, self.Gender]
person = human()
print(dir(person))
(Note the str() conversion of self.Age)
Now some other knowledge:
dir() method calls __dir__ method in the class and __dir__ is supposed to return list containing items of similar data types (int or str).
This means list should contain all integers or all strings.
For example, code:
class Hello():
def __dir__(self):
return ["1", "2", "3"]
print(dir(Hello()))
Output: ['1', '2', '3']
if:
class Hello():
def __dir__(self):
return [1, "2", 3]
print(dir(Hello()))
Output: TypeError: '<' not supported between instances of 'str' and 'int'
For more information: What's the difference between dir() and __dir__?
I'm working on a MOOC on Python Programming and am having a hard time finding a solution to a problem set. I hope you can provide some assistance.
The problem statement is:
This problem uses the same Pet, Owner, and Name classes from the previous problem.
In this one, instead of printing a string that lists a single pet's owner, you will print a string that lists all of a single owner's pets.
Write a function called get_pets_string. get_pets_string should have one parameter, an instance of Owner. get_pets_string should return a list of that owner's pets according to the following format:
David Joyner's pets are: Boggle Joyner, Artemis Joyner
class Name:
def __init__(self, first, last):
self.first = first
self.last = last
class Pet:
def __init__(self, name, owner):
self.name = name
self.owner = owner
class Owner:
def __init__(self, name):
self.name = name
self.pets = []
Add your get_pets_string function here!
Here's my code:
def get_pets_string(Owner):
result = Owner.name.first + " " + Owner.name.last + "'s" + " " + "pets are:" + Pet.name
return result
My code is getting the following error:
AttributeError: type object 'Pet' has no attribute 'name'
Command exited with non-zero status 1
Below are some lines of code that will test your function. You can change the value of the variable(s) to test your function with different inputs.
If your function works correctly, this will originally
print:
David Joyner's pets are: Boggle Joyner, Artemis Joyner
Audrey Hepburn's pets are: Pippin Hepburn
owner_1 = Owner(Name("David", "Joyner"))
owner_2 = Owner(Name("Audrey", "Hepburn"))
pet_1 = Pet(Name("Boggle", "Joyner"), owner_1)
pet_2 = Pet(Name("Artemis", "Joyner"), owner_1)
pet_3 = Pet(Name("Pippin", "Hepburn"), owner_2)
owner_1.pets.append(pet_1)
owner_1.pets.append(pet_2)
owner_2.pets.append(pet_3)
print(get_pets_string(owner_1))
print(get_pets_string(owner_2))
Could you please offer some guidance on what I'm not doing right with my code?
In your code, the name is an instance variable of Pet class. So, to access name of Pet you need an instance of Pet class. But in your code in the Pet.name, the Pet refers to the class and as there is no class variable name in Pet class, the above error is displayed.
To fix this, you can use the member pets of Owner class representing list of Pet object. So in the get_pets_string() you can iterate over pets member of Owner and print names of all the pets.
So after change to get_pets_string(), it will look like -
def get_pets_string(owner):
result = owner.name.first + " " + owner.name.last + "'s pets are: " + ", ".join(p.name.first + " " + p.name.last for p in owner.pets)
return result
Here I have used join() to show the name of all the pets separated by comma
I'm a beginner to python. I've written this code but I can't execute the for loop inside the print function to iterate through the list of marks:
class student:
def __init__(self, name, age, iden, lMark):
self.name=name
self.age=age
self.iden=iden
self.lMark=lMark
def printAve(self, obj):
for i in obj.lMark:
res+=i
av=res/len(lMark)
return av
def disInfo(self, obj):
print("the name is: ",obj.name)
print("the age is: ",obj.age)
print("the identity is: ",obj.iden)
print("the marks are: ", for i in lMark:
print(i))
def addStudent(self, n, a, i, l):
ob=student(n,a,i,l)
ls.append(ob)
return true
def searchStudent(self, _val):
for i in len(ls):
if ls[i]==_val:
return i
ls=[]
s=student("Paul", 23,14, list(15,16,17,20,12))
bool added = s.add("Van", 20, 12, list(12,18,14,16))
if added==True:
print("Student added successfully")
for i in range(ls.__len__())
s.disInfo(ls[i])
Can someone help me to solve this problem and explain me how to do?
You can't put a bare for loop in the argument list to print, and of course the embedded print doesn't return what it prints. What you can do is
print("the marks are:", ", ".join(lMark))
or perhaps
print("the marks are:", *lMark)
(Also, I believe you mean obj.lMark.)
To reiterate, if you call some code in the argument to print, that code should evaluate to the text you want print to produce; not do printing on its own. For example,
def pi()
return 3.141592653589793 # not print(3.141592653589793)
def adjective(arg):
if arg > 100:
return "big" # not print("big")
else:
return "small" # not print("small")
print(str(pi()), "is", adjective(pi()))
Notice how each function call returns something, and the caller does something with the returned value.
from statistics import mean
# classes are named LikeThis
# constants named LIKE_THIS
# other variables should be named like_this
# hungarian notation is not used in Python
class Student:
# instead of a global variable named ls,
# I'm using a class variable with a clear name instead
all_students = []
def __init__(self, name, age, iden, marks):
self.name = name
self.age = age
self.iden = iden
self.marks = marks
def printAve(self):
# you don't need to pass two arguments when you're only operating on a single object
# you don't need to reinvent the wheel, see the import statement above
return mean(self.marks)
def disInfo(self):
print("the name is:", self.name)
print("the age is:", self.age)
print("the identity is:", self.iden)
# you can't put a statement inside of an expression
# I'm guessing you want the marks all on the same line?
# the *args notation can pass any iterable as multiple arguments
print("the marks are:", *self.marks)
# this makes more sense as a classmethod
# clear variable names are important!
#classmethod
def addStudent(cls, name, age, iden, marks):
# I'm using cls instead of Student here, so you can subclass Student if you so desire
# (for example HonorStudent), and then HonorStudent.addStudent would create an HonerStudent
# instead of a plain Student object
cls.all_students.append(cls(name, age, iden, marks))
# note the capital letter!
return True
# again, this should be a classmethod
#classmethod
def searchStudent(cls, student):
# use standard methods!
try:
return cls.all_students.index(student)
except ValueError:
return None
# the literal syntax for lists in Python is `[1, 2, 3]`, _not_ `list(1, 2, 3)`.
# it also makes more sense to use Student.addStudent here, because just calling Student() doesn't add it
# to the list (although you could do that in __init__ if you always want to add them to the list)
Student.addStudent("Paul", 23, 14, [15, 16, 17, 20, 12])
# in Python, type annotations are optional, and don't look like they do in C or Java
# you also used `add` instead of `addStudent` here!
added: bool = Student.addStudent("Van", 20, 12, [12,18,14,16])
# don't need == True, that's redundant for a boolean value
if added:
print("Student added successfully")
# never call `x.__len__()` instead of `len(x)`
# (almost) never use `for i in range(len(x))` instead of `for item in x`
for student in Student.all_students:
student.disInfo()
First I answer your initial question, you can print a list in different ways, here are some of them.
You can iterate through it with a for loop and print every element on a different line:
for elem in self.lMark:
print(elem)
You can also append all values to a string and separate them by a character or something.
(Note: There will be a trailing space at the end.)
myString = ""
for elem in self.lMark:
myString = myString + str(elem) + " "
print(myString)
Better is this by doing it with strings-join method and a short version of the container iteration:
", ".join([str(i) for i in self.lMark])
There were some more issues in the code example.
Here is a running version of the script:
class Student:
def __init__(self, name, age, iden, lMark):
self.name=name
self.age=age
self.iden=iden
self.lMark=lMark
def printAve(self, obj):
for i in obj.lMark:
res+=i
av=res/len(self.lMark)
return av
def disInfo(self):
print("the name is: ",self.name)
print("the age is: ",self.age)
print("the identity is: ",self.iden)
print("the marks are: ", ", ".join([str(i) for i in self.lMark]))
class StudentList:
def __init__(self):
self.__list_of_students = []
def add(self, s):
self.__list_of_students.append(s)
return True
def get(self):
return self.__list_of_students
def search(self, name):
for s in self.__list_of_students:
if s.name == name:
return s
return None
ls = StudentList()
s=Student("Paul", 23,14, [15,16,17,20,12])
ls.add(s)
added = ls.add(Student("Van", 20, 12, [12,18,14,16]))
if added:
print("Student added successfully")
search_name1 = "Paula"
search_name2 = "Van"
if ls.search(search_name1):
print(search_name1, "is part of the list!")
else:
print("There is no", search_name1)
if ls.search(search_name2):
print(search_name2, "is part of the list!")
else:
print("There is no", search_name2)
for student in ls.get():
student.disInfo()
print("-"*10)
I would suggest to separate the list of students and the students to two different classes as shown in the code above.
You can unpack your list with the * operator:
print("the marks are: ", *lMark)
Try setting this as a function. i.e
def quantity():
for i in lMark:
print(i)
Then,
def disInfo(self, obj):
print("the name is: ",obj.name)
print("the age is: ",obj.age)
print("the identity is: ",obj.iden)
print("the marks are: ", + quantity)
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.