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.
Related
in the below code i am trying to understand the differences between global and local variables. At the runtime the following error is generated:#
File "m:\python lessons\globalAndLocal_1.py", line 21, in globalVsLocal_1
self.g2()
NameError: name 'self' is not defined
Note
i want to call g2 from within g1
please tell me how to call method g2()
code:
class globalVsLocal_1:
def f1(self):
global a #this is to reference a variable declared in the global context.
print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
a = a + 10
print ("f1 a = %s"%(a))
def f2(self):
print("f2 a = %s"%(a))
def f3(self):
print("f3 b = %s"%(b))
#b = b + 1 #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without
#manipulate it
print("f3 b = %s"%(b))
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()
The scope of g2() is local to the function g1() so you cannot call it outside. It's also unusual that you try to call g2() in the middle of the class definition.
class ...
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
class globalVsLocal_1:
def f1(self):
global a #this is to reference a variable declared in the global context.
print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
a = a + 10
print ("f1 a = %s"%(a))
def f2(self):
print("f2 a = %s"%(a))
def f3(self):
print("f3 b = %s"%(b))
#b = b + 1 #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without
#manipulate it
print("f3 b = %s"%(b))
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()
You were missing indentation while called g2.
This gives the following output
f1 a = 1
f1 a = 11
f2 a = 11
f3 b = 20
f3 b = 20
g2 b = 20
If I had a function name stored in a variable, how can I know inside the function the name of the variable used to call it?
e.g.:
var_name = function1
var_name("3")
def function1(self, params=""):
print("the parameter is " + params + "called by" + VARIABLENAME)
I would have an output like:
the paramter is 3 called by var_name
Thanks for the support
Unfortunately you can't do that on python, but you could do something like this to get the current function:
import inspect
def function1(n):
print("the parameter is " + n + " called by " + inspect.getframeinfo(inspect.currentframe()).function)
function1("3")
You could identify the calling function and additionally lookup all defined functions using globals():
import inspect
import types
def function1(n):
alias = getCallingAliases(inspect.getframeinfo(inspect.currentframe()).function)
print("the parameter is " + n + " called by " + alias)
def getCallingAliases(realFn):
for k, v in globals().items():
if isinstance(v, types.FunctionType):
# k == function or alias
# v == original function
aliasName = v.__name__
if realFn != k and realFn == aliasName:
return k
return '<unknown>'
var_name = function1
var_name("3")
Out:
the parameter is 3 called by var_name
Note: That's not error prone and might need to be adjusted to your needs (regarding classes, imported function from other modules, ...)
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)
I'm trying to get my results function to call my retrieve_pub_vote_summary function, which creates a tuple. I then want my results function to print the tuple.
#application.route('/results/')
def results:
publication = "nytimes"
retrieve_pub_vote_summary(publication)
print(pub_tuple)
##############################################
def retrieve_pub_vote_summary(publication):
onevotes = 1
twovotes = 2
pub_tuple = (onevotes, twovotes)
print(pub_tuple)
return pub_tuple
pub_tuple prints fine in retrieve_pub_vote_summary. But it doesn't seem to go to results. I get "NameError: name 'pub_tuple' is not defined."
You have 2 errors in the code:
def results(): # added ()
publication = "nytimes"
pub_tuple = retrieve_pub_vote_summary(publication) # assign the result
print(pub_tuple) # now pub_tuple is defined the line above
##############################################
def retrieve_pub_vote_summary(publication):
onevotes = 1
twovotes = 2
pub_tuple = (onevotes, twovotes)
print(pub_tuple)
return pub_tuple
results() # call results
Now it returns
(1, 2)
(1, 2)
pub_tuple in retrieve_pub_vote_summary is a local variable inside retrieve_pub_vote_summary. That's why it couldn't be printed and you got the error.
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.