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)
Related
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def add(self,s1,s2):
summ1 = self.m1 + self.m2
summ2 = s1.m1 + s1.m2
summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(summ1)
print(summ2)
print(summ3)
why summ1 is not getting printed even it is defined in function?
Well summ1,summ2,summ3 are defined in add function when I try to print them this code is giving me error.
Error is
NameError: name 'summ1' is not defined
summ1,summ2,summ3 are local variables defined in the function add and they are not visible outside of this function. If you replace them by self.summ1, self.summ2, self.summ3, then print(std1.summ1) etc. will work.
As AnkurSaxena said, you can not access your variables the way you try it.
The following code should solve your problem:
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
self.summ1 = None
self.summ2 = None
self.summ3 = None
def add(self,s1,s2):
self.summ1 = self.m1 + self.m2
self.summ2 = s1.m1 + s1.m2
self.summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(std1.summ1)
print(std1.summ2)
print(std1.summ3)
def state_from_record(state_name):
state_split = state_name.split(",")
return state_split
def cases_from_record(covid_cases):
covid_split = covid_cases.split(",")
return covid_split
def deaths_from_record(covid_deaths):
death_split = covid_deaths.split(",")
return death_split
result1 = state_from_record(result[0])
print(result1)
This is the second part of the code which continues on:
import random
def state_report(state, data_list):
if state_split is random:
states = choice(state_split)
for s in states:
if states == state_split:
return states + "\n" + "Total Confirmed Cases: " + covid_split + "Total Deaths: " + death_split
else:
return "No record found for " + states
result2 = state_report(states, state_split)
print(result2)
I am trying to use a previous code and it keeps on coming as a name error saying that "states" doesn't exist.
here is my output:
NameError Traceback (most recent call last)
<ipython-input-20-8fee8f642c90> in <module>()
10 return "No record found for " + states
11
---> 12 result2 = state_report(states, state_split)
13 print(result2)
NameError: name 'states' is not defined
What you are bumping into is a programming concept called the scope
Imagine these two functions:
def first_func():
foo = "abc"
print(foo)
def second_func():
print(foo)
second_func()
Running this code will raise NameError, because variable foo is out of the scope of the second_func, since it is defined within the boundaries of the first_func.
If you move the variable foo out of the first function, like so:
foo = "abc"
def first_func():
print(foo)
def second_func():
print(foo)
second_func()
Both functions will run fine. Because variable foo is now defined in a broader scope and accessible from within both functions.
My goal is to create a function that I can use to measure the execution and resource use of another function. Using a tutorial, I've create the below using Python's ThreadPoolExecutor:
from resource import *
from time import sleep
from concurrent.futures import ThreadPoolExecutor
class MemoryMonitor:
def __init__(self):
self.keep_measuring = True
def measure_usage(self):
max_usage = 0
u_run_time = 0
s_run_time = 0
while self.keep_measuring:
max_usage = max(max_usage, getrusage(RUSAGE_SELF).ru_maxrss)
u_run_time = max(u_run_time, getrusage(RUSAGE_SELF).ru_utime)
s_run_time = max(s_run_time, getrusage(RUSAGE_SELF).ru_stime)
sleep(0.1) # run this loop every 0.1 seconds
return [max_usage, u_run_time, s_run_time]
def execute(function):
with ThreadPoolExecutor() as executor:
monitor = MemoryMonitor()
stats_thread = executor.submit(monitor.measure_usage)
try:
fn_thread = executor.submit(function)
result = fn_thread.result()
print("print result")
print(result)
print("print result type")
print(type(result))
finally:
monitor.keep_measuring = False
stats = stats_thread.result()
print(stats)
return result
def foo():
i = 0
while i < 3:
print("foo")
i+=1
return 1
def bar(x):
while x < 3:
print("foobar")
x+=1
return 1
var = execute(foo)
print("Var = " + str(var))
var = execute(bar(0))
print("Var = " + str(var))
If I pass the function foo as an argument to the function execute, it prints the correct results and returns the value returned by foo.
If I pass the function bar in the same way, but with bar itself requiring an argument, the function runs (prints 3 times) and then I get the following error:
result = self.fn(*self.args, **self.kwargs)
TypeError: 'int' object is not callable
After some testing, the part where I'm stuck appears to be passing a function as an argument, if that function itself requires an argument. As I understand the ThreadPoolExecutor, the fn_thread object encapsulates the execution of the function submitted. The result object should simply hold the result of that execution - what am I missing that this cannot handle being passed a function with an argument?
You are submitting
bar(0)
instead of
bar, 0
To clarify, look at the submit's signature:
submit(fn, *args, **kwargs)
the result of
bar(0)
is an integer, and the executor cannot call an integer, since it is not 'callable', as the error message suggests.
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.
I have the following function, I want to concat the 2 strings, What wrong am I doing here?
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd
for key in commands:
conf_cmd += key + '\n'
print(conf_cmd)
Getting the following error:
conf_cmd += key + '\n'
After running it, I get this error:
NameError: name 'conf_cmd' is not defined
I added your code with your critical issue resolved.
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd = '' // <-- ''
for key in commands:
conf_cmd+=key+'\n'
print(conf_cmd)
All you need to do is to add:
conf_cmd = ''
just after commands = ["abcd","123"]
Why?
global conf_cmd Does not create new string, it just means you can access the global variable.