How to use module variable? [duplicate] - python

This question already has answers here:
How to link multiple scripts?
(3 answers)
Closed 2 years ago.
I'm supposed to write a vending machine program, divided into three scripts (machine-user interaction, purchases and stocks).
I'm trying to create a variable stocklist in the stock file, so that I can call it for functions in the machine script.
machine script:
if stockchoice == 1:
import stock
stock.stocklist
stock.stockchoice1(stocklist)
stock script:
stocklist = []
def stockchoice1(lista):
print("Insira o compartimento, quantidade, produto e valor:")
stock1 = input()
lista += stock1
print(lista)
I'm getting the error name 'stocklist' is not defined.
How can I use the variable / functions across the different scripts?

stocklist as a standalone name is in fact undefined. You need to refer to it as an attribute of its module:
stock.stockchoice1(stock.stocklist)
Or, depending on your goal, you might prefer to define it as a standalone name, like this:
stocklist = stock.stocklist
stock.stockchoice1(stocklist)
or
from stock import stocklist
stock.stockchoice1(stocklist)

Related

Is there an alternative to waitForFinished method to check if the process is finished? [duplicate]

This question already has answers here:
Using QProcess.finished() in Python 3 and PyQt
(1 answer)
Qt No such slot for the QProcess::finished() signal
(3 answers)
Closed 2 years ago.
I am currently trying to create an app with PyQt5 and the GUI keeps on hanging.
There were a couple of backend exe files that needed to be executed in the app using command prompt and I found out about the fact that waitForFinished blocks the entire GUI.
I tried going searching it everywhere but no luck. I just found that most of the related questions had just one answer which was to use signals instead of waitForFinished(-1). I wanted to learn how to use signals but nowhere could I find a tutorial of any sorts that could help me.
The code is:
process = QProcess()
cd = "babel.exe"
tem = " "
if not file.endswith("mol"):
tem = re.sub('\..*', '.mol', file)
filech = tem
ar = [file, filech, "-rcpb"]
process.start(cd, ar)
process.waitForFinished(-1)
process.kill
Thanks in advance..

Last imported file overwrites statements from previous files. Better ways of specifying imported variables?

Hey stackoverflow community,
i’m new to this forum and to python developing in general and have a problem with Alexa/ Python overriding the similar named variable from different files.
In my language learning skill I want Alexa to specifically link a “start specific practice” intent from the user to a specific practice file and from this file to import an intro, keyword and answer to give back to the user.
My problem with the importing, is that Python takes the last imported file and overrides the statements of the previous files.
I know I could probably change the variable names according to the practices but then wouldn't I have have to create a lot of individual handler functions which link the user intent to a specific file/function and basically look and act all the same?
Is there a better way more efficient of doing the specifying of those variables when importing or inside the functions?
import files and variables
from übung_1 import intro_1, keywords_1, real_1
from übung_2 import intro_1, keywords_1, real_1
working with the variables
def get_practice_response(practice_number):
print("get_practice_response")
session_attributes = {}
card_title = "Übung"
number = randint(0, len(keywords_1))
print(intro_1 + keywords_1[number])
speech_output = intro_1 + keywords_1[number]
session_attributes["answer"] = real_1[number]
session_attributes["practice_number"] = practice_number
session_attributes["keyword"] = keywords_1[number]
reprompt_text = "test"
should_end_session = False
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
I expected giving out the content of the specifically asked file and not variable content from the most recent files.
Sadly I haven't found a solution for this specific problem and hope someone could help me pointing me in the right direction.
Thank you very much in advance.
Might be easiest to import the modules like so:
import übung_1
import übung_2
The refer to the contents as übung_1.intro_1, übung_2.intro_1, übung_1.keywords_1 and so on.
As you point out, these two lines
from übung_1 import intro_1, keywords_1, real_1
from übung_2 import intro_1, keywords_1, real_1
don't work the way you want because the second import overrides the first. This has to happen because you can't have two different variables in the same namespace called intro_1.
You can get around this by doing
import übung_1
import übung_2
and then in your code you explicitly state the namespace you want:
print(übung_1.intro_1 + übung_1.keywords_1[number])

Random Modules and "randint()" function [duplicate]

This question already has an answer here:
Python - AttributeError: 'int' object has no attribute 'randint'
(1 answer)
Closed 5 years ago.
I am a beginner Python user. I was wondering why I am unable to use two randint() functions. I've done a little research on the issue, and it seems as though "I can only have one random module active at any time". Is there any way to get around this so I can have two "random values"?
Also, this is my first question ever, so criticism towards the question, sample code and answer are all welcome.
import random
random = random.randint(1, 5)
random_2 = random.randint(7, 11)
print(random)
print(random_2)
What's happening is that Python is confusing random (the number) with random (the module). Also, don't name the file random.py because it's going to search the module in the local directory, first.
And it's not a bug.

NameError in Python Script [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 6 years ago.
I am working through an example Python script from the book "Doing Math with Python" and I keep running up against a NameError which tells me my variable isn't defined, when, it looks to me like it is defined.
I'm using Python 3.4 and the code is
'''
Gravitational Calculations
'''
import matplotlib.pyplot as plt
#Draw the graph
def draw_graph(x,y):
plt.plot(x,y,marker='o')
plt.xlabel('Distance (m)')
plt.ylabel('Force (N)')
plt.title("Gravitational force as a function of distance")
def generate_F_r():
#Generate values for r
r=range(100,1001,50)
#Empty list to store F values
F=[]
#G Constant
G=6.674*(10**-11)
#Two masses
m1=0.5
m2=1.5
#Calculate F and append it into the F-list
for dist in r:
force=G*m1*m2/(dist**2)
F.append(force)
#Call the Draw Plot Function
draw_graph(r,F)
if __name__=='__main__':
generate_F_r()
The error it gives me is:
NameError name 'r' is not defined
Isn't it defined in the line that states r=range(100,1001,50)?
Why isn't it taking this as a definition?
I'm sure there is something glaringly simple and incredibly stupid I'm doing but I am at my wits end as to how such a simple thing could be so hard.
Thanks!
Code in functions is not executed until the function is called. You don't call generate_Fr() until after you have already tried to reference r. Even if you did call the function first, though, r is still just a local variable. You need to make it global with global r at the beginning of the function.

Unbound Local Error python [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 9 years ago.
I need help figuring out why I am getting the following error:
Traceback (most recent call last):
File "prawtest3.py", line 25, in <module>
commentMatcher()
File "prawtest3.py", line 13, in commentMatcher
commentCollection.append(comment)
UnboundLocalError: local variable 'commentCollection' referenced before assignment
This is my code. For background information, I am trying to create a reddit bot that compares a persons comments and then pms a user when the person they are monitoring submits a new comment. If you see a problem with the functionality as well, feel free to share your input. I just need to diagnose my code first to get rid of the syntactical errors before worrying about the semantic ones.
import praw
import time
r = praw.Reddit('PRAW related-question monitor by u/testpurposes v 1.0.')
r.login()
user = r.get_redditor('krumpqueen')
commentCollection = []
commentComparison = []
def commentMatcher():
comments = user.get_comments(limit = 4)
for comment in comments:
commentCollection.append(comment)
time.sleep(60)
comments = user.get_comments(limit = 4)
for comment in comments:
commentComparision.append(comment)
if commentCollection[1] != commentComparision[1]:
r.send_message('krumpqueen', 'just made a new comment', 'go check now')
commentCollection = list(commentComparision)
else:
r.send_message('krumpqueen', 'did not made a new comment', 'sorry')
while(True):
commentMatcher()
Your use of commentCollection makes python (incorrectly1) assume that commentCollection is a local (since you have an assignment to it later and no global statement). When you try to append to the local (which hasn't been created yet) python throws the UnboundLocalError.
1Of course, it's not python making an incorrect assumption, That's how the language is designed to work.
You do commentCollection = list(commentComparision) inside of commentMatcher. Because you've done this, Python concludes you have a local name commentCollection.
Your code fails for the same reason that the code
def foo():
bar.append(3)
bar = []
would fail.
To get commentCollection = list(commentComparision) to a) rebind the global name commentCollection, and b) not make it look like this is a local name at all, add global commentCollection as the first line in the definition of commentMatcher.
In serious code, you wouldn't want to manage your state as globals like this, but rather you'd make an object.

Categories