This is the problem:
Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned?
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
return counter
Yet I keep getting a outside function error when I run the system
what am I doing wrong?
Thanks!
You can only return from inside a function and not from a loop.
It seems like your return should be outside the while loop, and your complete code should be inside a function.
def func():
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N -= 1
return counter # de-indent this 4 spaces to the left.
print func()
And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.
You have a return statement that isn't in a function. Functions are started by the def keyword:
def function(argument):
return "something"
print function("foo") #prints "something"
return has no meaning outside of a function, and so python raises an error.
You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.
As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
print(counter)
break
It basically occours when you return from a loop you can only return from function
Related
Here is the code that i wrote to get sum of digits from a number repeated number of times till the sum gets below 10:
T = int(input())
for i in range(T):
N = int(input())
def P():
M = [int(d) for d in str(N)]
N = sum(M)
if N<10:
print(N)
else :
return P()
P()
On running this code it gives me an error like:
Traceback (most recent call last):
File"C:/Users/AdityaShrivastava/AppData/Roaming/Python/Python36/Scripts/tes
ting.py", line 11, in <module>
P()
File "C:/Users/Aditya
Shrivastava/AppData/Roaming/Python/Python36/Scripts/testing.py", line 5, in
P
M = [int(d) for d in str(N)]
UnboundLocalError: local variable 'N' referenced before assignment
You are using recursion to solve this. It is more efficient to simply use a loop:
def gimmeNumber(text):
""""Helper: Asks for input until valid integer number is inputted. Retuns the number"""
while True:
T = input(text).strip()
if T and T.isdigit():
T = int(T)
break
print("Thats not a number ...")
return T
def sumDigits(number):
return sum(int(x) for x in str(number))
T = gimmeNumber("How many numbers? ")
for _ in range(T):
s = 0
N = gimmeNumber("Give me a number: ")
# calculate the cross-sum
s = sumDigits(N)
while s > 9: # repeat while greater then 9
s = sumDigits(s)
print(s)
Input: 4, then 999,888,333,111
Output:
9
6
9
3
As #Arne suggested changing gimmeNumber(text) to use try/except instead fits better into pythons Ask forgiveness not permission mindset, and I agree.
Still, the variant above also works and is easier to understand for beginners. Here is the try/except one:
def gimmeNumber(text):
""""Helper: Asks for input until valid integer number is inputted. Retuns the number"""
while True:
try:
T = int(input(text).strip())
break
except ValueError as e:
print("Thats not a number ...")
return T
For more about input validation I would suggest reading up on it in the answers of Asking the user for input until they give a valid response .
The UnboundLocalError: local variable 'N' referenced before assignment you are getting is as a result of using N inside function P() without having declared and initialized it.
N = int(input()) is inside the loop but outside the scope of P(). The last line P() in the loop will call function P() and not go back to N = int(input()) where N would have been assigned.
I have modified the code to
T = int(input())
for i in range(T):
N = int(input())
def P(N):
M = [int(d) for d in str(N)]
N = sum(M)
if N<10:
print(N)
else :
return P(N)
P(N)
You can fix this by passing N as a parameter in the P function.
T = int(input())
for i in range(T):
N = int(input())
def P(n):
M = [int(d) for d in str(n)]
n = sum(M)
if n<10:
print(n)
else :
P(n)
P(N)
If you set value of N inside the function P, python understands it as creating a local variable with that name. This local variable masks the global variable N used outside of the function. So, you better pass N as a parameter to function P.
Thanks.
Functions in python declare a new scope, which is why N is not visible in your function. You can circumvent this by passing N along into the inner scope, like this:
T = int(input())
for i in range(T):
N = int(input())
def P(N):
M = [int(d) for d in str(N)]
N = sum(M) # this line was the actual culprit
if N<10:
print(N)
else :
return P(N)
P(N)
>>> 1 # test one time
>>> 12345 # cross total of 121212
6
Python is conservative on write-operations. Only reading from an outer-scope variable is fine, but re-assigning the name N (which is what happens if you write N = sum(M)) makes it check strictly for a local variable of that name.
As a consequence, it further assumes that that not-yet-declared variable is where you want to read from in the line above it - which is honestly a bit misleading.
For further information on scopes and namespaces in python, check here.
Below is my code. I don't know what I am doing wrong, but when I run this, I get NameError: name 'counter' is not defined. I'm learning Python from a textbook and according to the textbook my code is right. I can't find the difference between the textbook code and this code... I've seen other questions on stackoverflow about global variables, but I still can't figure out what I did wrong. Why do I get this error? And how to solve it?
UPDATE:
I know what I did wrong. I should write counter = 0 above the function.
def rpower(a, n):
'returns a to the nth power'
global counter # counts number of multiplications
if n == 0:
return 1
# if n > 0:
tmp = rpower(a, n//2)
if n%2 == 0:
counter += 1
return tmp*tmp # 1 multiplication
else:
counter += 2
return a*tmp*tmp # 2 multiplications
print(rpower(2, 10000))
May be your counter variable is declared outside of you function. Like:
counter=0
def rpower(a, n):
'returns a to the nth power'
global counter # counts number of multiplications
if n == 0:
return 1
# if n > 0:
tmp = rpower(a, n//2)
if n%2 == 0:
counter += 1
return tmp*tmp # 1 multiplication
else:
counter += 2
return a*tmp*tmp # 2 multiplications
print(rpower(2, 10000))
I rewrite your code a little bit in PyCharm. Just changed the name of the function, because your code didn't worked by just ctrl+v:
def rpow(a, n):
global counter
if n == 0:
return 1
tmp = rpow(a, n/2)
if n%2 == 0:
counter += 1
return tmp*tmp
else:
counter += 2
return a*tmp*tmp
print(rpow(2, 10000))
I don't got your error, but i reached RecursionError: maximum recursion depth exceeded in comparison
Try to do the same.
The following code should be taking two numbers from the user and then state which number is higher, 9 times, thus "counter <10 " except it only takes the two numbers once, and then the loop is finished. I thought I could increment the loop by using "counter=counter +1" in my loop, but it doesnt seem to work. Any help would be appreciated, thanks!
counter = 0
for counter in range(counter < 10):
num1 = float(input("Enter number 1: "))
num2 = float(input("Enter number 2: "))
if num1 > num2:
print(num1)
else:
print(num2)
counter = counter + 1
counter < 10 returns True which is equal to 1:
>>> counter = 0
>>> counter < 10
True
>>> True == 1
True
In turn, range(1) yields 0 (single item):
>>> list(range(counter < 10))
[0]
That's why it loop once.
Instead of range(counter < 10), you should use range(9). You don't need to declare counter = 0 and to increment yourself counter = counter + 1. for statement take care of it:
>>> for i in range(3):
... print(i)
...
0
1
2
counter<10 is equivalent to 1. That is why, the loop runs just once ( range(1) = {0} ).
You can use either :
for counter in range(10):
...
or
counter = 0
while( counter<10 ):
...
counter+=1
for your purpose.
To make it more clear to you, the expression within the brackets are evaluated at first place. If you want to use for, then you need to pass a sequence, over which the for will loop through. The range() is used to generate the sequence . But here you are passing (count < 10) to range(), which is a condition. So while evaluated, it returns True since counter is 0 (initialized in the first line) and is less than 10. And this returned True is equivalent to 1, so the rest goes as described by falsetru
If you want to pass a condition, then you should use while loop, instead of for. In for, you don't even need to initialize the variable counter separately. If you write :-
for counter in range(9):
this will initialize counter variable and it would be incremented in each iteration.
For your question you can use either of the following:-
for counter in range(9):
# No need to initialize counter
do_stuff
or
# Initialize counter
counter = 0
while(counter <10):
do_stuff
why this function doesn't work as a factorial function?
def Factor(n):
while n>=1:
print n*(n-1)
return 1
This will work
def Factor(n):
val=1
while n>=1:
val = val * n
n = n-1
return val
You have recursion and iteration mixed. Take a look at these two:
def factor_recursion(n):
while n>=1:
return n * factor_recursion(n-1)
return 1
def factor_iteration_for(n):
factor = 1
for i in range(n):
factor *= i+1
return factor
def factor_iteration_while(n):
factor = 1
while n >= 1:
factor *= n
n -= 1
return factor
print factor_iteration_for(4)
print factor_iteration_while(4)
print factor_recursion(4)
You never change the value of n to anything other than what is passed into the function.
I don't think this is going to do what you think it will. Looks like you've mixed recursion and iteration.
First of all, none of your code changes the value of n, so the loop will run indefinitely unless n == 1 when the function is called.
Secondly, you aren't accumulating a partial product inside the loop (hint: before the loop set result =, then inside it multiply the current value of result by the value of n.
Finally, you should then return the accumulated result rather than one.
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print factorial(5)
I am newbee in Python . JUst wandering if it is possible to define a Global variable in Python.
I have this python code to compute total number of times Fib(2) has been accessed. But count is printing 0 when called.
import sys
def fib(n):
"""Takes input a natural number n > 0.
Returns n! """
global count
count = 0
if n == 1 or n == 0:
return 1
else:
if n == 2:
print 'encountered here::: '
count += 1
return fib(n-1) + fib(n-2)
def main():
x = int(raw_input('Enter a natural number > 0 :'))
print 'Fibonacci(%d) = %d' % (x, fib(x))
print 'Count =', count
if 1:
main()
A variable defined in the module outside of any function is considered a global variable. To modify a global variable inside of a function, you must write global variableName inside of the function.
You did this, however, that variable is only defined in your function, it must also be declared outside of the function to be considered a global variable. If not, it will be local to your function, despite the global in front of it.
TL;DR Also declare the variable outside of your function.
EDIT (I was wrong):
By writing global variableName in a function and executing said function, it does make the variable a global variable; if not you would be getting a NameError when you tried to print it.
The reason that you're getting a 0, however, is because everytime you call your function, you initialize count to 0. Nonetheless, the solution about still holds.
Move count = 0 outside your fib(n) function. You only need to declare it as global count once inside the function, while the initialization should be outside. What you're doing is that you are re-initializing it with 0 every time the function is called.
import sys
count = 0
def fib(n):
"""Takes input a natural number n > 0.
Returns n! """
global count
if n == 1 or n == 0:
return 1
else:
if n == 2:
print 'encountered here::: '
count += 1
return fib(n-1) + fib(n-2)
def main():
x = int(raw_input('Enter a natural number > 0 :'))
print 'Fibonacci(%d) = %d' % (x, fib(x))
print 'Count =', count
if 1:
main()
Although, you should avoid global variables.
global foo
foo = [1,2,3]
Now foo can be used anywhere in the program
Put the count = 0 outside the function.