Programming a temperature sensor in python - python

I'm trying to make code for my temperature sensor. Been stuck on a NameError when I try to execute the code. My question is, does anyone have a clue what I am doing wrong?
Code:
import datetime
from sense_hat import SenseHat
def hotwater():
sense = SenseHat()
sense.clear()
celcius = round(sense.get_temperature(), 1)
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]
while __name__ == '__main__':
Hotwater()
Error:
Traceback (most recent call last):
file "/home/pi/Web_test.py", line 9 in <module>
results= 'temp. C' + str(celcius)
NameError: name 'celcius' is not defined

The variable Celsius is only accessible in the hotwater function. It cannot be accessed outside of it. To fix the issue, you could move the printing into the hotwater function:
def hotwater():
sense = SenseHat()
sense.clear()
celcius = round(sense.get_temperature(), 1)
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]
hotwater()
Or, you could have hotwater return celsius:
def hotwater():
sense = SenseHat()
sense.clear()
celcius = round(sense.get_temperature(), 1)
return celcius
celcius= hotwater()
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]
Although you could use the global keyword to make celsius accessible everywhere, that is generally frowned upon.

Your function fails to returned the value to the main program.
Variable celcius[sic] is local to the function.
Also, you've failed to invoke the function where you try to use the value.
Follow the examples in your learning materials: call the function, return the value to the main program, and save or use it as needed:
def hotwater():
sense = SenseHat()
sense.clear()
return round(sense.get_temperature(), 1)
if __name__ == '__main__':
while True:
celsius = hotwater()
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]
I'm not sure what plans you have for result_list, but I think you'll need to update the code above.

Related

Execute method from another python file with argues

I'm a python begginer and I wanted to execute a method (A) with argues that will call another method (B) that will return values to (A).
I only can't reached the (B) method directly, for this I used a main. And so I can't retrieve (B)'s informations from (A)
My architecture looked like this :
Main Folder
|-> test_caller.py (A)
|-> called_file.py (B)
I want to call a method with argues from test_caller.py (main method), that will execute method to called_file.py (function_called()), and I want that function_called() method return flag or value if it's possible.
test_caller.py :
import sys
import subprocess
import os
def main():
#method can't return something
# my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
# script_descriptor = open(my_path)
# a_script = script_descriptor.read()
# sys.argv = [my_path, "variable1","https://google.com"]
# exec(a_script)
my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
#call function tes.py, but need a main method and so doesn't return the function value yet
test = subprocess.run(['python',my_path,"variable1","https://google.com"],check=True)
print(test)
if __name__ == '__main__':
main()
called_file.py :
import sys
import requests
def function_called(variable,variable2):
#Potato = Flag
try :
potato = 0
print(str(variable + " is ready to use "+ variable2 + " as variable number 2"))
request = requests.get(variable2)
if(request.status_code == 200):
response = request.text
return response
else :
potato = 1
#Flag exception potato = 1 => failure
except Exception as exc :
print("An error occured " + str(exc))
potato = 1
return potato
#I want that main issue disappear, for returning potato method value (flag 0 or 1) to my method's calling
# if __name__ == "__main__":
# function_called(sys.argv[1],sys.argv[2])
How could I do that ? Thanks for helping me.
Hello AKX thanks for your help, this solution might be good for our program,
For those who's had a similar problem, the solution now is this:
on test_caller.py :
def main():
test = importlib.import_module("called_file")
object = test.function_called("tata","https://www.google.com")
print(object) #do what you want from the returned object

Python NameError and I can not understand

I'm now practicing defining functions:
def get_seconds(hours, minutes, seconds):
return 3600*hours+60*minutes+seconds
Now, I want to exec the function:
amount_a = get_seconds(7200*minutes+30*seconds)
amount_b = get_seconds(__)
result = amount_a + amount_b
print(result)
Error:
NameError: name 'minutes' is not defined
First you define "get_seconds" function, you just need to do :
amount_a = get_seconds(hours=2, minutes=30, seconds=0)
amount_b = get_seconds(hours=0, minutes=45, seconds=15)

Calling methods from other files in python results in executing the entire python file [duplicate]

This question already has answers here:
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 3 years ago.
I am new to python programming. I have written sample code as flows.
temp.py
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Hello.py
from temp import Basics
class Check:
def __init__(self):
print('Check obj')
def createName(self, firstName, lastName):
str = firstName + ' ' + lastName
return str
emp = Check()
completeName = emp.createName('Tushar', 'Banne')
print(completeName)
b = Basics('Tushar', 98765432)
val = b.getString
print("Val is {}".format(val))
I am running Hello.py file and getting the below output.
Tushar
class 'str'
tushar 9620207652
Boolean true
class 'str'
tushar 9620207652
Check obj
Tushar Banne
Val is (bound method Basics.getString of 0x0000024ECCCB5B70
The questions that I have are as follows
Why is the entire temp.py getting executed?
How to execute only getString method.
Why is it that when I use parenthesis after getString, it fails.
Why is the val printing object reference?
Am I following the correct standards of python coding?
Why is the entire temp.py getting executed?
That's how it works. Importing a module means essentially executing it.
How to execute only getString method.
In order to do so, the code in temp.py has to be changed in a way that it is only executed when the module is run at highest level ("as the __main__ module") instead of imported.
You do that this way:
if __name__ == '__main__':
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
if __name__ == '__main__':
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
if __name__ == '__main__':
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Why is it that when I use parenthesis after getString, it fails.
I don't see it fail in your question.
Why is the val printing object reference?
Because you asked it to. Referring to a method or function means seeing it as an object and printing its string representation. If you call it (with the () behind), you perform a function call.
First, check this out What does if __name__ == "__main__": do?
When you are importing a python file, all of the code is executed.
What do you mean fails, what is the error?
val = b.getString means that now val references the method getString, that's why it is printed.
No, read the link above, also, python uses snake_case, not camelCase, so call the method get_string, not getString. (this obviously doesn't changes thte

variable defined in a function throws NameError: global name not defined when used in main

I'm trying to run my function: show_total() , but I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\file.py", in <module>
main()
File ".\file.py", in main
total_money = show_total(bags, coins, coin_to_bag)
NameError: global name 'coin_to_bag' is not defined
my code looks like:
def assign_coin_to_bag(bags, coins):
coin_to_bag = {}
print(bags)
print('\n')
print (coins)
print('\n')
for bag in bags:
print('For bag: ' + bag )
coin_type = input('\nWhich coin do you want to put in this bag? ') #e.g. 0.25 * 2
coin_amount = input('\nNumber of this type? ') #e.g. 0.25 * 2
mattress_status = 'stuffed'
for coin in coins:
coin_to_bag[bag] = [coin_type, coin_amount, mattress_status]
print(coin_to_bag)
return (coin_to_bag)
def main():
bags = gather_bag()
coins = gather_coin()
coins_in_the_bag = assign_coin_to_bag(bags, coins)
total_money = show_total(bags, coins, coin_to_bag)
main()
Thank you for your help!
coin_to_bag is a defined in the scope of assign_coin_to_bag, and is not accessible in main. You caught the return value of assign_coin_to_bag in coins_in_the_bag, and need to use that variable in your call to show_total.
There's a common error new programmers make, which is thinking the name of a variable needs to be the same wherever it's used, even across methods. In fact, the name of the variable means absolutely nothing to the computer. Good names are only there for humans.
As an exercise, we used to have students trace code like this:
def foo(one, three, two):
print "%s %s %s" % (one, two, three)
def bar():
return 1, 2, 4
three, two, one = bar()
foo(two, one, three)
Figure out what gets printed, and that will be good practice to break the variable naming habit.

How can i use my function a_c_t_b()

My code looks like:
def g_b():
items_in_bag = []
done=False
bugout_bag = 'Bug Out Bag'
while done == False:
item = input('What bags do you have? [Enter x to stop]')
items_in_bag.append(item)
if item == 'x':
done = True
items_in_bag.remove('x')
break
else:
continue
items_in_bag.append(bugout_bag)
print("Your bags\n")
print(items_in_bag)
return items_in_bag
def g_c():
coins_in_bag = []
done=False
while done == False:
coin_item = input('What coins do you have? [Enter x to stop]')
if coin_item == 'x':
done = True
break
else:
coins_in_bag.append(coin_item)
continue
print("Your coins\n")
print(coins_in_bag)
return coins_in_bag
def a_c_t_b(items_in_bag, coins_in_bag):
#print('Here are your coins:\n')
#g_c()
#print('Here are your bags:\n')
#print(items_in_bag)
print (items_in_bag,coins_in_bag)
return (items_in_bag,coins_in_bag)
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
main()
However, when i run this code like: import myfile
It gives me an error of:
File ".\myfile.py", line 51, i
a_c_t_b(items_in_bag,coins_in_bag)
NameError: global name 'items_in_bag' is not defined
I'm simply trying to return the values of items_in_bag,coins_in_bag from their respective functions.
Thank you
Please call your functions more sensible names.
To answer your question, your g_b and g_c functions return values, they don't return names. At the point where you call a_c_t_b, Python has no idea what items_in_bag is, because yo'uve never defined it. Python can't know you mean "the value returned from g_b": you have to tell it.
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
You are calling g_b and g_c but never catching their returned values.
You can either do:
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
or:
def main():
a_c_t_b(g_b(), g_c())
When you import the module main function is executed (call in last line). And main function use undefined identifiers items_in_bag and coins_in_bag:
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
Probably you want something like
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag,coins_in_bag)

Categories

Resources