Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i'm new to python so sorry if this insanely simple, but i'm kind of stuck and I've viewed the other questions regarding coin toss but this is even more simple than those:
put simply, why wont my prog work?
class Coin:
showing_heads=True
value=1
def show(self):
if (self.showing_heads==True):
return "Heads"
else:
return "Tails"
def turn(self):
if (self.showing_heads==True):
self.showing_heads=False
else:
self.showing_heads=True
def run_cointoss(2):
coin1=Coin()
coin2=Coin()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
print "Turn them over"
coin1.turn()
coin2.turn()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
One problem is you're using 2 in function arguments. Function argument expect valid identifiers and 2 is not a valid identifier:
>>> def func(x):
pass
...
>>> def func(x = 2):
pass
...
Your error:
>>> def func(2):
pass
File "<ipython-input-234-dc2d2489d3d8>", line 1
def func(2):
^
SyntaxError: invalid syntax
Secondly if your original code is indented as it is in question body, then you should move the definition of function run_cointoss outside of the class body.
You should not create coins inside the coin class:
def run_cointoss(2):
coin1=Coin()
coin2=Coin()
Instead, create them after the class definition
class Coin:
showing_heads=True
value=1
def show(self):
if (self.showing_heads==True):
return "Heads"
else:
return "Tails"
def turn(self):
if (self.showing_heads==True):
self.showing_heads=False
else:
self.showing_heads=True
# Class definition is done
def run_cointoss():
coin1=Coin()
coin2=Coin()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
print "Turn them over"
coin1.turn()
coin2.turn()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
run_cointoss()
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I'm having trouble trying to get a game creation exercise to stop printing the else statement (at the bottom of the code block). the idea is, you can navigate from room to room, but if you go in a direction you're not supposed it should tell you. However, it seems to be doing that even when you CAN go somewhere. I'd greatly appreciate any advice.
Code is below:
class Room:
number_of_rooms = 0
def __init__(self, room_name):
self.name = room_name
self.description = None
self.linked_rooms = {}
self.character = None
Room.number_of_rooms = Room.number_of_rooms + 1
def set_description(self, room_description):
self.description = room_description
def get_description(self):
return self.description
def set_name(self, room_name):
self.name = room_name
def get_name(self):
return self.name
def describe(self):
print(self.description)
def set_character(self, new_character):
self.character = new_character
def get_character(self):
return self.character
def describe(self):
print( self.description )
def link_room(self, room_to_link, direction):
self.linked_rooms[direction] = room_to_link
def get_details(self):
print(self.name)
print("--------------------")
print(self.description)
for direction in self.linked_rooms:
room = self.linked_rooms[direction]
print( "The " + room.get_name() + " is " + direction)
def move(self, direction):
if direction in self.linked_rooms:
return self.linked_rooms[direction]
else:
print("You can't go that way")
return self
I would greatly appreciate any advice on this, it's maddening. I just need it to stop printing "You can't go that way" when you can. It actually does work, it just insist on printing it every time you go into a new room as well as when you can't.
This is the code it links to
foyer = Room("foyer")
ballroom = Room("ballroom")
dining_hall = Room("dining hall")
kitchen = Room("kitchen")
foyer.link_room(ballroom, "south")
ballroom.link_room(foyer, "north")
ballroom.link_room(dining_hall, "east")
dining_hall.link_room(ballroom, "west")
dining_hall.link_room(kitchen, "north")
kitchen.link_room(dining_hall, "south")
If you add the following test code to the end of your class (assuming that it is inside a module Room.py):
if __name__ == "__main__":
print("Testing")
# rooms
room1 = Room("Floor")
room2 = Room("Kitchen")
room3 = Room("Living Room")
# link the rooms
room2.link_room(room1, "left")
room3.link_room(room1, "right")
# move
room2.move("up") # not allowed
room3.move("right") # should be possible
Then you can run the test code directly if you execute the module.
Now if you are in room 3 (living room) it is possible to get out on the right.
But if you are in room 2 (kitchen) you can only move to the left.
The test prints "You can't go that way" only if you do a move like room2.move("up") which is correct, because only "left" is allowed. Comment that line and you won't see that message any more.
According to this test, the class is behaving as it should. Note that you could (and should!) also write a unit test from the example I gave, asserting the expected output.
Update:
In your example, allowed moves are:
# allowed
kitchen.move("south")
dining_hall.move("north")
ballroom.move("east")
foyer.move("south")
And examples for not allowed moves are:
# not allowed
kitchen.move("west")
dining_hall.move("east")
ballroom.move("south")
foyer.move("north")
For these you will get "You can't go that way".
Maybe the issue you had was that you were using objects rather than strings as parameter to describe the direction.
For example, this will always fail (printing "You can't go that way"):
foyer.move(ballroom) # param should be a string, not an object
To prevent this kind of error, you could add a check to the move method:
def move(self, direction):
if not isinstance(direction, str):
raise ValueError("Direction needs to be a string!")
if direction in self.linked_rooms:
return self.linked_rooms[direction]
else:
print("You can't go that way")
return self
With that addition, the application will throw an exception, if you pass an object and not a string:
ValueError: Direction needs to be a string!
For interactive testing, you could use this code:
new_dir = "nop"
current_room = foyer
while new_dir != "":
print("current room: " + current_room.name)
print("please enter direction:")
new_dir = input()
if new_dir == "":
print("leaving")
break
new_room = current_room.move(str(new_dir))
if new_room != current_room:
print("moving to: " + new_room.name)
current_room = new_room
For debugging, it might be also helpful if you add the following code to the top of the module:
def Log(func):
def inner(*args, **kwargs):
print(f"Logging {str(func)}: {args[1:]}")
result = func(*args, **kwargs)
print(f"Result: {str(result)}")
return result
return inner
Now you can decorate any of the functions with the #Log attribute like so:
#Log
def __init__(self, room_name):
...
#Log
def move(self, direction):
...
Whenever such a decorated function is called, it will print it to the console, e.g.:
please enter direction:
south
Logging <function Room.move at 0x000001994B97C720>: ('south',)
Result: <main.Room object at 0x000001994B97A150>
moving to: ballroom
current room: ballroom
please enter direction:
If you're done with debugging, you can comment out the attributes (# #Log) to remove the extra print outs.
I'm learning Python through Exercism.IO, I'm currently on the Bob problem where the object of the problem is as follows:
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He says 'Fine. Be that way!' if you address him without actually saying
anything.
He answers 'Whatever.' to anything else.
So far I've passed a few tests and I'm stuck at a point where it's suppose to return whatever but all the characters are integers, so of course it's not working.
Here's where I'm failing:
def test_only_numbers(self):
self.assertEqual(
'Whatever.', bob.hey('1, 2, 3')
)
All the characters are integers and my test to see if they're yelling looks like this:
def is_yelling(self):
return self.sentence == self.sentence.upper()
Obviously the characters are the same when upper or lower case because they're numbers so the program thinks they're yelling. My question is how can I refactor this program to make it so that when the assertion is all numbers, it won't count it as yelling?
def hey(what):
sentence = SentenceThinker(what)
if sentence.is_silence():
return "Fine. Be that way!"
elif sentence.is_yelling():
return "Whoa, chill out!"
elif sentence.is_question():
return "Sure."
else:
return "Whatever."
class SentenceThinker(object):
def __init__(self, sentence):
self.sentence = sentence
def is_yelling(self):
return self.sentence == self.sentence.upper()
def is_question(self):
return self.sentence.endswith("?")
def is_silence(self):
return not self.sentence
consider using the built-in String method str.isupper()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to call/run a method only onetime I tried this but it didn't wotk:
class S ()
_int_(self)
self.xxx = True # i tried with and without
def Packet (event):
if (xxx == True):
self.f(event, xxx)
print xxx
else:
....
def f (event):
print "something"
Do_Somthing
xxx=False
the problem xxx is still true
Best regards
Amer
The whole class's syntax seems wrong to me. You can do something like this
class S:
def __init__(self): # Initializer function for instance members
self.flag = True
def myMethod(self): # Actual method to be called
if self.flag:
....
....
self.flag = False
Change xxx to self.xxx.
The xxx = False creates a new name binding instead of assigning to the field in your object.
Also, there are also some other syntax errors in your code. Is this the actual code you are running? The code you posted shouldn't run.
from itertools import count
class S ()
def __init__(self)
self.xxx = count()
def Packet(self, event):
if next(self.xxx) == 0:
self.f(event)
else:
....
def f(self, event):
print "something"
#Do_Something
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
class Item:
def __init__(self, name, price, kind):
self.name = name
self.price = price
self.kind = kind
def getPrice(self):
return self.price
def getName(self):
return self.name
def getKind(self):
return self.kind
class Cart:
def __init__(self):
self.list = []
pass
def addItem(self, item):
self.list.append(item)
def getTotalsByKind(self, kind):
total = 0
for i in self.list:
if i.getKind() == kind:
total += i.getPrice()
t = '{:.2f}'.format(total)
print "The total for %s items is %s" %(kind, t)
You are printing the return value of the method.
Remove the print statement from before the .getTotalsByKind() method call; the method itself does all the printing.
Your method does not have an explicit return statement, which means the default return value None is used:
>>> def foo():
... # Nothing is returned in this function
... print 'Bar!'
...
>>> print foo()
Bar!
None
>>> foo()
Bar!
The better alternative is to have your method return the string to be printed:
def getTotalsByKind(self, kind):
total = 0
for i in self.list:
if i.getKind() == kind:
total += i.getPrice()
t = '{:.2f}'.format(total)
return "The total for %s items is %s" %(kind, t)
Now you can do different things with the returned string, not just print it.
You should make getTotalsByKind return the string, not print it. To do this, make this line:
print "The total for %s items is %s" %(kind, t)
like this:
return "The total for %s items is %s" %(kind, t)
Now, when you print the results of getTotalsByKind, it will work.
Functions, by default, return None if they come to the end of themselves without returning. And, by using print with getTotalsByKind (which you must be doing), you are telling Python to print the return value of getTotalsByKind, which is None.
You don't show this part of your code, but my guess is that you're doing print cart.getTotalsByKind(...), thereby telling Python to print the return value of that function. But it doesn't return anything, therefore it returns None. Instead that method prints the total.
You have fallen prey to a poorly named method: getTotalsByKind implies that the totals will be returned, but there's only one total, and it is printed instead of being returned. I would name this method printTotalByKind instead. Or name it getTotalByKind and have the caller do the printing (and formatting). Then your method could be written much more simply as follows:
def getTotalByKind(self, kind):
return sum(item.price for item in self.list if item.kind == kind)
This isn't related to your question, but your getter methods are entirely superfluous and should probably be removed. You can already get an item's price via item.price, no need for the overhead of calling a function to do the same thing. PINJ.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm in a python class with a dumb teacher and I havent been able to get anything to work right. Here's a simple program i'm just trying to get to work once i know it doesn't really gget the average.
>>> class two:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Number? 5
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
class two:
File "<pyshell#28>", line 9, in two
main()
File "<pyshell#28>", line 7, in main
y= average(x+1,x)
NameError: global name 'average' is not defined
Your error happens because you do not have any global name average in scope when you use it.
You seem to be confused about when and whether to use the class keyword. In your particular example, you don't need it -- both average and main want to be global functions, not class methods.
Try this program instead:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Alternatively, if you want to learn about classes:
class two:
def __init__(self, x,y):
self.x = x
self.y = y
def average(self):
return (self.x + self.y)/2
def main():
t = two(7,42)
print(t.average())
main ()
Notice how the declaration of average now includes a self parameter -- this links the call to a particular two object. Notice also how the invocation of average changed: it is now t.average(). In this case, t is the specific object which will be passed as the first parameter of two.average().
def average(a,b):
return int((a+b)/2)
def main():
print 'enter a number'
num = raw_input()
y = average(int(num)+1,int(num))
print y
main()