I am trying to keep the value of a variable between files on a python script. The end goal is to separate functions from an algorithm.
The function is very simple - I have saved it in a file called test:
def tests(x):
global y
x=10
y=x
return y
Then the algorithm part is again simple - saved in a different file, called test1:
import test as t
y=0
t.tests(y)
print("new value is "+str(y))
However, the value does not seem to be updated to 10 - it keeps its initial value of 0.
I am sure I am missing sth very obvious, but could you pls help?
The above code works if I contain the function and the algorithm parts in the same fie, but I would like to separate them.
Thank you
The error is pretty minute, the only reason the value is not updated is because you forgot to assign the value to the variable y
The code in the second file(test1) should be:
import test as t
y = 0
y = t.tests(y)
print("New value is " + str(y))
Related
I'm trying to get my code to get a string of data from a sensor, and then do something when it reads a specific value.
The following code is how I'm receiving the data now (this is just a test) the function is called earlier in the code at the time where I want it to be called.
def gettemperature(self)
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
This code works, and returns the temperature value rounded to the terminal, but how could I, instead of printing the value to the terminal, make it so when that string of rounded value is say, 200 degrees, then it prints the temperature value? instead of printing it every 2 seconds (the frequency of the data being received, as per another part of the code)
Using something like
if temp = 200
then print(blahblah)
in short, the above code is what I'm trying to do. If the temp equals a certain value, then something else will happen.
That last code doesn't work. I'm pretty new to coding, so I'm assuming I'm either not going about this the right way, or the syntax of how I'm going about trying to get that value to do something isn't correct (obviously)
Thanks for any help! I'm surprised I got this far, haha.
It would be better if your function gettemperature would return something and then print the result in the condition:
def gettemperature()
temp = board.temp_sensor
return temp
temp = gettemperature()
if temp == 200:
print("Temperature is " + str(round(temp)) + " degrees.")
Before using stackoverflow, I'd recommend learning all this stuff from some basic course, as you'll get to learn the stuff yourself rather then get the answer from someone else.
Try learning conditional statements.
what you want is, to put a conditional statement which triggers if temperature is greater than 200.
If the temp is always a number in string data type, you can use the below code.
def gettemperature(self):
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
temp=int(temp) #typecasting string datatype to integer
if temp == 200:
print("Temperature is high")
Below is my code. Here, I am trying to read the variable gobs(x) from an input file and then I want to use it for other calculations, eg., computing error(x). But, I found, I can read it from input file properly within the loop, but when trying to use it outside the loop, only the first data is getting transferred. For all 100 data, which I read as gobs(x) inside the loop, it is showing the value of last data only, when I am using it outside the loop.
code started below
constant = 99
x0=50
z0=5
def gsyn (x):
return (constant*z0)/(z0**2+(x-x0)**2)
with open ('Grav_H_Cyln_v3_output.txt') as finp:
lines=finp.readlines()
for line in lines:
g=float(line)
x=line
def gobs (x):
return g
print (gobs(x)) # here, gobs(x) is printing properly
def error(x):
return (gsyn(x)-gobs(x))
for i in range (1, 100, 1):
x=i
print (error(x)) # here, only the first value of gobs(x) is coming
print ('stop')
This seems like a very odd solution to what is fundamentally a very simple problem. Make gobs a dictionary so you can set or retrieve gobs[x] at will.
gobs = dict()
with open ('Grav_H_Cyln_v3_output.txt') as finp:
lines=finp.readlines()
for line in lines:
g=float(line)
gobs[line] = g
print (gobs[line])
You could try creating a vector gobs[] outside the loop, and filling it up within the loop over lines.
That should do.
Instead of reassigning the value of x on each iteration of your loop, append i to a list that is declared outside of the if-block scope.
x = []
for i in range (1, 100, 1):
x.append(i)
print(x)
My code is really simple:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
else:
print (x_min)
It gives me the correct result (x-->0) but not only once but alot of times. Why is that and how can I keep it from doing so?
Because you told it to. :-)
Your if statement reads:
if I have a new minimum, record the value and position;
otherwise, print the existing minimum.
Any time you don't find a new minimum, you print. Since this function has its minimum early in your range, you get a lot of output.
If you want the global minimum printed only once, then do it only once: move it outside of the loop.
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
To fix this, move the print statement out of the for loop:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
Why do this? Well, before, when you had the print statement in the for loop, each time the for loop went through, whenever the if statement was not true, it printed, so you got a bunch of printed things. Now, when you move it out of the for loop, it can only be printed once, and the program works as you expect.
I'm new to programming, so this question might be dumb.
I need to introduce the value of Tr1 into the Bzero1 function. When I run the module I get the result below:
.
The program is not running the Bzero1 function and I'm not sure why. Is it because I am not introducing the Tr1 value correctly or something else? I want Bzero1 to perform the operation 0.083-(0.422/Tr1**1.6), with Tr1 obtained from the result of T/Tc1.
I would appreciate your help a lot.
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
Tc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", Tc1)
def Tr1(T, Tc1):
print("Relative temperature 1: ", T/Tc1)
Tr1 = Tr1(T, Tc1)
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
Do not replace Tr1 function value, to avoid such replacement change:
Tr1_value = Tr1(T, Tc1)
Call Bzero1 function with code:
Bzero1(Tr1_value)
Modify Tr1 to return value:
def Tr1(T, Tc1):
result = T/Tc1
print("Relative temperature 1: ", result)
return result
Also, let me suggest you to take a look on python official tutorial - there you can learn a lot about python ...
Good Luck !
def is only defining a function, not calling it. E.g.
def foo(a):
print a * 2
means there is now a function foo that takes argument a. The a in foo(a) is the name of the variable inside the function.
So in your case
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
defines the function Bzero1 as taking argument Tr1, but doesn't call it. You need to call the function, just like you called Tr1:
Bzero1(Tr1)
You can see that this way it becomes confusing quite quickly on which is a variable outside of your function, and which are variables inside functions. Therefore it is better to use different names for variables in your outer program v.s. those inside functions.
Here are a few more best practices that you might find useful:
It is generally better to first define all functions and then execute the program's main code, as opposed to intermixing function definitions and the main program.
Another best practice is to make functions only calculate output from inputs, and handle output somewhere else. This way you get to reuse your functions in other parts of your program while always keeping control of when and what to output to the user.
Finally, you shouldn't generally reassign names, e.g. Tr1 = Tr1(...) means that Tr1 is now no longer the name of the function but the name of the result returned by Tr1. In short, use different names for different things.
Applying these tips, your code might look as follows:
# function definitions first
def Tr1(vt, vtc1):
return vt/vtc1
def Bzero1(vtr1):
return 0.083-(0.422 / vtr1 ** 1.6)
# get user input
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
vTc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", vTc1)
# run calculations
vTr1 = Tr1(T, vTc1)
vBz1 = Bzero1(vTr1)
# print output
print("Relative temperature 1: ", vTr1)
print("Bzero 1: ", vBz1)
Note
Since I don't know the semantic meaning of your variables I have just used small letter v as a prefix - in general it is better to use meaningful names like temperature or temp1 and temp2 etc. Programs are not math papers.
#Use main and a void function named randnums.
#randnums takes no arguments and return none.
#The randnums function generates 6 random integers between 1 and 9.
#The total should be printed on a new line.
#Main should call the randnums function.
import random
total=0
def main():
randnums()
def randnums():
for nums in range(6):
nums=random.randrange(1,10)
total=total+nums
print(nums,end=' ')
print("\nThe total is:",total)
main()
I keep getting:
local variable 'total' referenced before assignment
Or when total=nums it only shows the last int generated.
Can someone please explain to a beginner what I'm doing wrong?
When you assign to a variable inside a function, Python interprets it as local variable to that function. So when you do -
total=total+nums
You are actually trying to access the local variable total before defining it.
Based on your program, does not look like you need total to be a global variable, you can simply define it as 0 at the start of randnums() . Example -
def randnums():
total = 0
for nums in range(6):
You are facing problem because of variable scope.
total=total+nums
Notice that line, in your local scope, total doesn't exist but you are trying to get it's value and then add some num with it, which is the cause of your error.
If you really want to use it, use it like below:
global total
total=total+nums
So, that it recognises the global total variable.