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()
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
class RetailItem:
# The _init_ method initalizes the attributes.
def __init__(self, description, units, price):
self.__description = description
self.__units = units
self.__price = price
# The set_description method acccetps an argument for the retailitem's description.
def set_description(self, description):
self.__description = description
# The set_units method accepts an argument for the retailitem's units.
def set_units(self, units):
self.__units = units
# the set_price method accepts an argument for the retailitem's price.
def set_price(self, price):
self.__price = price
# The set_description methods returns the retailitem's description.
def get_description(self):
return self.__description
# The get_units method returns the retailitem's units.
def get_units(self):
return self.__units
# The get_price method returns the retailitem's price.
def get_price(self):
return self.__price
def make_list ():
#Create an empty list
item_list = []
# Add Item Object to the list
print ('Enter date for the items')
keep_going = 'Y'
i = 1
while keep_going.upper() == 'Y':
print('Item n*',i)
#Get the Item data
descript = input('Enter the description: ')
units_Inv = input('Enter the units: ')
prix = float(input('Enter the price:$'))
print()
# Create an instance of the retailitem class
item = retailitem.RetailItem(descript, units_Inv, prix)
i += 1
#Add the Object to the list
item_list.append(item)
keep_going = input('Press Y to continue to add Data for item or N to stop: ')
# return the list
return item_list
def display_list(item_list):
for var in item_list:
print(var.get_description())
print(var.get_units())
print(var.get_price())
print()
#call the main function.
main ()
main needs to be defined (def main doesn't appear in your example, at least). My guess is that you are expecting the following:
def main():
lst = make_list()
display_list(lst)
The problem is exactly what the error message is telling you:
#call the main function.
main ()
Where is main() defined?
This may be caused by confusion about how Python works vs. other languages. In Python, anything at the global level is executed automatically -- it doesn't need to go in a main function.
So, if you want to run some code, just do it:
class RetailItem:
def __init__(self, description, units, price):
self.__description = description
self.__units = units
self.__price = price
# etc.
l = make_list()
display_list(l)
Typically you would wrap that code at the end in a if __name__ == "__main__" block, but it's not required.
you need somewhere
def main():
#function body - whatever you want it to do
in this case, what it looks like you want to do is to create an instance of the RetailItem class and then call its methods.
The error says the issue. "main is not defined".
You are calling the main() function at the end but didn't define it anywhere in the code.
def main():
# this is your main function
list = make_list()
display_list(list)
w.r.t. "I just want it to run": add the following to the top of your code:
def main():
pass
Your code will now run. Technically.
If you want to reference putting all of the functions together you actually need to declare a function called main() EX:
def main():
makelist()
displaylist(item_list)
####################################
main()
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 8 years ago.
Improve this question
I have a class inside a file called Weapons.py called Pistol that looks like this:
class Pistol(object):
MAXAMMO = 6
def __init__(self, ammo):
if(ammo <= self.MAXAMMO):
self.ammo = ammo
def shoot(self):
if(ammo > 0):
accuracy = random.randint(0, 3)
return 3 * accuracy
ammo -= 1
else:
print("No ammo")
And a class called ColtM1911 that inherits from Pistol. It looks like this:
class ColtM1911(Pistol):
MAXAMMO = 7
def __init__(self, ammo):
self.ammo = 7
When I run:
import Player
import SetUp
from Utils import *
import pickle
import TitleAnimation
import os
import SaveLoad
from Weapons import *
gun = ColtM1911(5)
In another file it gives me "TypeError: object() takes no parameters" When trying this in the shell it worked, so I suspect it is to do with having it in a separate file.
The full traceback is,
Traceback (most recent call last):
File "C:\Users\James\Documents\game.py", line 3, in <module>
gun = Weapons.ColtM1911(5)
TypeError: object() takes no parameters
The only way I can recreate your error is if Pistol is actually defined as:
class Pistol(object()):
# ^ note extraneous parentheses
In Python 3.x, you don't need object at all; all classes are new-style by default. Also, there are logic errors and M1911.__init__ is redundant. Try something like:
import random
class Pistol:
MAXAMMO = 6
def __init__(self, ammo):
if ammo <= self.MAXAMMO:
self.ammo = ammo
else:
# what do you want do do here? Raise an error? Set ammo = MAXAMMO?
def shoot(self):
if self.ammo > 0:
self.ammo -= 1
return 3 * random.randint(0, 3)
else:
print("No ammo")
class ColtM1911(Pistol):
MAXAMMO = 7
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi below is the relevant code for my problem:
class Player:
def __init__(self, name, x, y, isEvil):
self.health = 50
self.attack = randint(1, 5)
self.name = name
self.x = x
self.y = y
self.isEvil = isEvil
def checkIsAlive(self):
if self.health <= 0:
return False
else:
return True
# implicit in heritance. if the child doesn't have a function that the parent has
# the functions of the parent can be called as if it were being called on the
# parent itself
class Enemy(Player):
#def __init__(self, name, x, y, isEvil):
# self.health = 50
# self.name = name
# self.x = x
# self.y = y
pass
and a little more code:
e = Enemy('Goblin', 10, 11, True)
p = Player('Timmeh', 0, 1, False)
isLight()
while True:
if p.checkIsAlive() == True and e.checkIsALive() == True:
fight()
else:
if p.checkIsAlive() == True:
print('%s is victorious!!! %s survived with %s health points.' % (p.name, p.name, p.health))
else:
print('%s shrieks in its bloodlust!!! %s has %s health points' % (e.name, e.name, e.health))
however when i try and run this I get the following error:
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Python33\practice programs\textstrat\classees.py", line 94, in <module>
if p.checkIsAlive() == True and e.checkIsALive() == True:
AttributeError: 'Player' object has no attribute 'checkIsAlive'
However when using the interactive console I can do this:
if p.checkIsAlive() == True and e.checkIsAlive() == True:
... print('they are')
...
they are
all I want to do is call the boolean values for checkIsAlive to determine whether the two objects fight. It works in every other respect and I could just use:
if p.health <= 0 or e.health <= 0:
however that would make my checkIsAlive() method pretty useless when i would also want to be able to recycle as much code ass possible.
I really can't figure out why it is behaving this way and would sure love to understand it. Thanks in advance for your input.
As was pointed out swiftly in the comments above. I had missed a typo in the attribute name checkIsAlive.
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 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()