Trouble with NameError in IDLE - Python - python

got some trouble with my selfmade code.
def even(a, b):
f = []
while a <= b:
if a % 2 == 0:
f.append(a)
a = a + 1
return f;
When i'm tryin to call it from the shell it says:
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
even(0,200)
NameError: name 'even' is not defined.
I think it's not a really tricky problem, but can u help my anyway?
Thank you up front.
Cheers

Two things. Are you indenting your function correctly and how are you calling your function? the following code works:
def even(a, b):
f = []
while a <= b:
if a % 2 == 0:
f.append(a)
a = a + 1
return f;
print(even(2,3))
#output: [2]
Notice the indentation and the fact that even is being called after it is defined.
Edit: I notice you've gotten it working, now would be a good time to refacter some parts of your function i.e. give the variable f a more descriptive name.

If you want to run it from your shell, you would want to:
enter python into shell, to start your python interpreter
enter from <your-code's-filename.py> import even
then you can use the function as you tried: even(0,200)
But you can also just run it from within IDLE like Wright suggests.

Related

Python3: inject a recursive function into exec() in a function

In python3, if a function with recursive invoking is injected into exec() in a function, I got an error.
For example, below code
def B(pys):
exec(pys)
pys="""
def fibonacci(n):
if n == 1 or n == 2:
r = 1
else:
r = fibonacci(n - 1) + fibonacci(n - 2)
return r
print(fibonacci(3))
"""
B(pys)
will raise NameError.
$ py -3.8 testrecursivefun.py
Traceback (most recent call last):
File "testrecursivefun.py", line 14, in <module>
B(pys)
File "testrecursivefun.py", line 2, in B
exec(pys)
File "<string>", line 9, in <module>
File "<string>", line 6, in fibonacci
NameError: name 'fibonacci' is not defined
If I run exec(pys) directly under the module, the exception disappeared.
The reason has been described in another question How does exec work with locals?. But I still don't know how I can figure out the recursive invoking in exec(). Because the function name is dynamic for me. I cannot add it to locals() to exec(). Who can help me figure it out.
For the sake of an answer, you can wrap your code in a function so the recursive function is in its local scope:
import textwrap
def B(pys):
exec(pys, globals(), {})
pys="""
def fibonacci(n):
if n == 1 or n == 2:
r = 1
else:
r = fibonacci(n - 1) + fibonacci(n - 2)
return r
print(fibonacci(11))
"""
def wrap(s):
return "def foo():\n" \
"{}\n" \
"foo()".format(textwrap.indent(s, ' ' * 4))
B(wrap(pys))
Generally, reconsider using exec.
I actually got interested in your question, so I started researching on this topic. Seems like the simple solution to your problem is to:
First compile the string to code using compile function in python
Then execute the compiled code using exec function
Here is the sample solution:
psy="""
def fibonacci(n):
if n == 1 or n == 2:
r = 1
else:
r = fibonacci(n - 1) + fibonacci(n - 2)
return r
print(fibonacci(3))
"""
def B(psy):
code = compile(psy, '<string>', 'exec')
exec(code, globals())
B(psy)
Here compile takes three parameters:
First is the code in string format, Second is the filename hint which we used as we take string as code itself, and third can be one of 'exec', 'eval' and 'single'.
This link contains detail explanation of how you should use exec and eval in python. Do check them out for detail explanation.

I'm trying to learn how to write a loop but it doesn't seem to print to the console

I'm practicing Python and i'm trying to write a loop but it won't print when i run it. I'm using Python 2.7 through jupyter notebook. When I run the code all it does is bring up another kernel but doesn't print anything.
def main():
x = 0
while (x < 5):
print (x)
x = x + 1
You've defined the function, but now you have to tell Python to run it!
All you need to do is to call it, like so:
def main():
x = 0
while (x < 5):
print (x)
x = x + 1
main() #This is calling a function
Additionaly, you might want to change your x = x + 1 line to x += 1. They're equivalent, but it's much neater like this, and it saves you having to type the variable twice.
Within the jupyter notebook (or in the interactive mode of cmd), you can also do this after pressing shift + enter and calling the main() again.
I'm guessing you've worked with C or one of its relatives, where the entry point of a program is a call to main. That's not how it is in Python. Python works like many scripting languages, running the file from top to bottom, and your file contains one task for it to do: define a function named main. The tradition in scripts with such a function is to put a test at the bottom to call it, allowing a choice between importing the code and running it as a program:
if __name__ == '__main__':
main()
With this little epilogue, your program should actually run the main function.
There are a couple of other C-isms in your program as well. Python doesn't need parenthesis in while or if tests, and we have a more convenient for that operates using iterators instead of integers. For when integers are needed, range is convenient:
for x in range(5):
print(x)
If you're running Python 2, print is a statement that doesn't need parenthesis, but it is a function in Python 3 so I kept them.
Remove your main function, by deleting def main(): and just specify x=0 before the while loop
In your code, you define a function main() but you never call it. To fix this, either remove def main() from the cell, that is, simply execute the code that you want to run
x = 0
while (x < 5):
print (x)
x = x + 1
or call your function main():
def main():
x = 0
while (x < 5):
print (x)
x = x + 1
main()

Def function python: raw_input not store

I'm newbie in python. I'm study hard to know well how python work since I starting study in 2013 at college. Sorry, if little messy.
Let me showing my problem below.
I have some def function looks like:
def thread_1():
a = input('Value UTS (100) = ')
if a > 100:
print line2
d=raw_input('Dont higher than 100. Input y to repeat : ')
d='y'
if d=='y' :
thread_1()
return a
def thread_2():
b = input('Value UAS (100) = ')
if b > 100:
print line2
d=raw_input('Dont higher than 100. Input y to repeat : ')
d='y'
if d=='y' :
thread_2()
return b
def thread_3():
c = input('Value Course (100) = ')
if c > 100:
print line2
d=raw_input('Dont higher than 100. Input y to repeat : ')
d='y'
if d=='y' :
thread_3()
def thread_4():
value_total = a*50/100+b*30/100+c*20/100
and this my expression def into program list
if p==1:
thread_1()
thread_2()
thread_3()
thread_4()
Finally, I running this program :
As long as I input number is well, but in the end program showing the error code like that :
Traceback (most recent call last): File "ganjil-genap.py", line 71, in <module>
thread_4() File "ganjil-genap.py", line 36, in thread_4
value_total = a*50/100+b*30/100+c*20/100 NameError: global name 'a' is not defined
Can anyone let me know what I have done wrong?
Thanks in advance.
The variables a,b and c you are using on thread_1, thread_2 an thread_3 are only defined inside those functions. 'a' is only defined inside thread_1, b inside thread_2 and c inside thread_3, but theay are not global variables of the main program. The statement
return a
returns only the value of variable a.
you should make the vaiables global. I think it should look like this:
a=0
def thread_1():
global a
a= raW_input....
this will make your a,b,c variables global.
Then in thread_4() a,b and c should be passed as a parametres of the function.
def thread_4(a,b,c):
I think this should work.
You probably forgot the parameters to the thread_* functions.
For example, the thread_4 function declaration need to look like this:
def thread_4(a, b, c):
value_total = a*50/100+b*30/100+c*20/100
Also you have to give the arguments to your functions in the function call, for example:
if p==1:
a=1, b=2, c=3
thread_1(a, b, c)
thread_2(a, b, c)
thread_3(a, b, c)
thread_4(a, b, c)

Python - how to define a variable using a function?

I have a function that returns a number. I want to assign a variable to have this value, but python gives a runtime error when I say temp = foo(i, j) : NameError: name 'foo' is not defined. Note that I've changed the function bodies of bar and foo around, obviously having a function that just returns 1 is useless, but it doesn't change my error.
sum = 0
for i in range(2, 100):
for j in range(2, i):
temp = foo(i, j)
if (temp > 100):
sum = sum + 1
print sum
def bar (n, a):
r = 1
return r
def foo (n, a):
s = bar(n, a)/factorial(5);
return s
def factorial (n):
r = 1
for i in range (2, n + 1):
r *= i;
return r
Names in Python do not exist until they are bound. Move the def foo(...): block above the code that uses foo().
Your definition of foo is AFTER you use it in the file. Put your function definition above the for loop.
As per other answers, your issue is the order in which you run your code: foo hasn't been defined yet when you first call it. Just wanted to add a comment about best practices here.
I always try to put everything in a function and then call any scripts at the bottom. You've probably encountered this pattern before, and it's a good habit to get into:
CONSTANT = 5
def run():
for i in xrange(CONSTANT):
print foo(i) # whatever code you want
def foo(n):
# some method here...
pass
if __name__ == "__main__":
run()
if you run this with python script.py or by hitting f5 in idle, run() will be executed after everything is defined.
By following this pattern you don't have to worry about the order you define your functions in, and you get the added benefit of being able to import foo with other functions without having your script execute during the import, which is probably not a desired behavior.

Python go to def

Hi there
First of all just let me say that I'm new in Python and this is for a school work so this should be done without advanced programing and global functions. Using Python 2.6.6 and WingIDE 101
I need a program to present the user with a menu. The user must pick an option and accordingly to is pick the program does what the user wants.
For example, in the code bellow (its not the actual code), if the user picks 1 it goes to the sum() function.
def menu():
print "What do you want? "
print " 1 for sum"
print " 2 for subtraction"
pick = raw_input("please insert 1 or 2 ")
if pick == "1":
return sum()
if pick == "2":
return subtraction()
else:
menu()
menu()
def sum():
return 8 + 4
def subtraction():
return 8 - 4
I what to know how do I send, after my pick, the program to execute an determined definition.
Thanks
P.S. - running this gives me this error:
Traceback (most recent call last):
File "/usr/lib/wingide-101-3.2/src/debug/tserver/_sandbox.py", line 12, in
File "/usr/lib/wingide-101-3.2/src/debug/tserver/_sandbox.py", line 7, in menu
TypeError: sum expected at least 1 arguments, got 0
There are lots of things wrong with this, so we will take up one by one.
sum is a built-in function in Python. So you cannot name your function sum. You have to call yourself something else, like sum_foo. Or _sum.
Also, your code is executed from top to bottom. So if you are calling a function say X in a function like Y.
def f():
y()
f()
def y():
print 'Y called'
Results in this error:
NameError: global name 'y' is not defined
Because at your program runs, it is not aware of y because the y has not been declared at that point, since the program jumps to f().
To fix this, you would do:
def f():
y()
def y():
print 'Y called'
f()
Also, call the function as func_name() and not return func. And since in your sum and subtraction, you are returning the values, save them in some variable and print them, or print them directly.
def sum():
return 8 + 4
No output
def sum():
print 8 + 4
sum is a builtin at the point you're calling menu(). If you move this call after defining sum and substraction, it won't give you this error.
Please place the sum and subtraction functions above the menu() function definition. You are calling into the built-in sum(iterable[, start]) function provided by python.
the error is because you're using the sum function before you declare it. it should raise a NameError, but the sum function is a builtin so you're calling that func ( that requires at least one argument) and not the func you've written...
to pass through you can call menu() after declaring the sum and subtraction func
ps it's not a good idea to overwrite python's builtin function..change name to your func, and call menu later, or you will get a NameError
You should wrap the call to menu() in a if __name__ == '__main__:' block. At the bottom of your code, just add
if __name__ == '__main__':
menu()
This will help prevent using variables before they're defined.

Categories

Resources