Module is not working correctly with pygame [closed] - python

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 3 years ago.
Improve this question
I can't use functions that are in another module in my main module
#MAIN FILE - mainfile.py
#Imports / display / pygame.init
from file2 import *
font=pygame.font.SysFont("Arial",35)
example(1) #THERE I DEFINE DE CLASS
Text=font.render(list1[0],0,(255,255,255))
win.blit(Text,(5,5))
#while loop
#file 2 - file2.py
class example:
def __init__(self, whichlist):
global list1
if whichlist==1:
list1=["bird", "bird2", "bird3"]
elif whichlist==2:
list1=["bird", "bird2", "bird3"]
#more code
I know that I can just define the example class in the file2, but I want to define it in the main file.

In your example function could be better then class. And instead of global better use return.
In file2.py
def get_list(whichlist)
if whichlist == 1:
return ["bird", "bird2", "bird3"]
elif whichlist == 2:
return ["bird", "bird2", "bird3"]
#else:
# return []
In file1.py
from file2 import get_list
list1 = get_list(1)
If you really need to use class then you should create method in class which uses return
There is also good rule to use CamelCaseNames for classes - it means Example instead of `example
In file2.py
class Example:
def get_list(self, whichlist):
if whichlist == 1:
return ["bird", "bird2", "bird3"]
elif whichlist == 2:
return ["bird", "bird2", "bird3"]
#else:
# return []
In file1.py
from file2 import Example
ex = Example()
list1 = ex.get_list(1)
Eventually
list1 = Example().get_list(1)

Related

Better way to use variables in this function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've got a function get_prefix_lists with returns two values, each is a list of strings.
I then want to use those lists separately in another function. My code below is how i've done it but it feels dirty to use the same variable name (prefixes) in the __main__ section.
Is there a less dirty way?
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
v4_prefixes = []
v6_prefixes = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
v4_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
v4_prefixes.append(result.prefix)
else:
v6_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
v6_prefixes.append(result.prefix)
return v4_prefixes, v6_prefixes
def get_radb_prefixes(prefixes):
for prefix in prefixes:
r = requests.get(url=radb_url + 'route/' + prefix + 'AS11111?password=' + radb_mnt_password, headers=headers)
if r.status_code == 200:
pass
elif r.status_code == 404:
print(f"{prefix} Is in NetBox but not RADB")
else:
print(r.status_code, r.text)
if __name__ == "__main__":
print("V4 check")
prefixes = get_radb_prefixes(get_prefix_lists()[0])
print("V6 check")
prefixes = get_radb_prefixes(get_prefix_lists()[1])
Why not returning a dictionary?
{"v4": [], "v6": []}
Here's just some quickly jotted code to better explain:
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
prefixes = {}
prefixes['v4'] = []
prefixes['v6'] = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
prefixes['v4'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
prefixes['v4'].append(result.prefix)
else:
prefixes['v6'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
prefixes['v6'].append(result.prefix)
return prefixes

Problem with sending variable to another function [closed]

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 3 years ago.
Improve this question
Call function what checking file content, size, etc
Call function if file was changed by file size, if file size changed check file content, add changes to list or delete from list
Question how to use variable in other function correctly?
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size()
sleep(5.0)
Thank you in advance!
You need to assign the returned value of work_with_hosts_file() to a variable, and then pass that as an argument to compare_hosts_file_size().
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(file_size): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
size = work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size(size)
sleep(5.0)

I keep getting error that says main is not defined. I just want it to run. It's supposed to let me enter the description, price, and unit [closed]

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()

How to call/run a method only one time in python [closed]

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

very new to python would appreciate [closed]

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()

Categories

Resources