The question is rather academic. I came across the following behaviour in python:
This Code:
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
actually gives me 10 prints instead of one. So does the function recursively call itself after the return statement because there is no break?
If I put in a break before the return statement I still get 2 prints instead of only one.
Can someone explain this behaviour
I only see one new printed.
It also appears that you're a missing a colon : at the end of your loop for n in range(0,10).
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
# prints 'new' once...
Related
I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.
def hi (n):
if n<=5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
1) In the above code i have declared a function hi() which takes an input n
2)I want to iterate inside the if condition until n is less than 5,totally execute the print statement 4 times
3)But it is not working after execution of one time inside the condition
4)I am thinking i have given return statement for if condition but the function is totally being exit
5)(i am thinking i am returning the n value to the if condition and it checks the condition and it will iterate ) if wrong correct me
Not sure exactly what you want to achieve, but based on the info you have provided:
def hi (n):
while (n < 5):
print("we are inside hi")
n -= 1
Briefly speaking, using return inside a function means to return the value that is followed or return None if there is no value. In addition, the execution of the function is terminated just after the return statement is executed.
You can use the return statement, but if you want to iterate it is not correct because your function will terminate its execution. Also remember that once you execute the iteration of the loop, there won't be more statements to execute inside your function which means an implicit return statement will be executed which returns None, and again function ends execution.
You need a loop for this. Try this instead
for _ in range(4):
print("we are inside hi")
Of course, you need a loop to make iteration. If you just want to print the statement 4 times, simply make a range of loop.
def hi ():
for n in range(4):
print(n+1," we are inside hi")
hi()
you can use this:
def hi (n):
while n <= 5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
you need a loop to iterate and return statement will exit from the function call.
def recurr(k):
if (k>0):
result =k*recurr(k-1)
print(result)
else:
result=1
return result
recurr(4)
Output:
1
2
6
24
Because you're printing result after you recurse.
When you call recurr(4), the first thing it does is call recurr(3). This calls recurr(2), then recurr(1), and finally recurr(0). This last one is the base case, so it returns 1.
After that returns, you calculate result = k * 1, which is result = 1 * 1, then it prints that, so it prints 1 and then returns 1.
Then the previous recursion calculates result = k * 1, which is result = 2 * 1, then it prints that, so it prints 2 and returns it.
This repeats through all the recursions.
Its because you were printing result everytime you called it inside function instead of print what first call of function returned.
def recurr(k):
if (k>0):
return k*recurr(k-1)
return 1
print(recurr(4)) # -> 24
Because in every call of the function recurr() the print() function is executed.
If you want to print 24 that's the code:
def recurr(k):
if (k>0):
result =k*recurr(k-1)
else:
result=1
return result
print(recurr(4))
The recursion stack will print your message multiple times. This snippet may clarify why:
def factorial(k):
if (k>0):
print(f'factorial({k}) calls factorial({k-1})')
result = k*factorial(k-1)
else:
print(f'factorial({k}) is the base case')
result=1
return result
print(factorial(4))
you have to remove the print part in your function. Instead, you should write the code like this at the end of the code:
print(recurr(4))
The point is, the function is calling itself, and each time the function is called and processes the "if" block, it throws out a print. as for the order, the function evaluates the brackets inside out. As stated by #timgeb in comments,
recurr(4) --> 4*recurr(3*recurr(2*recurr(1*recurr(0))))
This evaluates recurr(0), which then successfully evaluates recurr(1) and so on.
The recursion in your code occurs on line 3, and the print statement occurs on line 4, after the recursion. When executing recurr(4), the entire code for recurr(3) (including the print statement for recurr(3)) is executed before the print statement for recurr(4).
Get 4 friends. Label them 1!, 2!, 3! and 4!. Tell them that if asked what their value is they must ask (n-1)! for their value, and then multiply by n, write it on a bit of paper and hand to the asker. All asking, must also be done on a bit of paper.
Now ask 4! for their value, when you get it shout it out.
Next tell them to do the same but whenever they pass a bit of paper to someone, they mast also shout out the value. Record what happens.
Which of the shouters is the one to keep?
When you use recursion, you build up a set of operation on the way down to the last call. Then you unroll them from the last, backwards up out to the first.
In this toy, you build up your result from the highest number, by putting your operation (k*next_value) at the bottom, and build it up. Then you get the result of each operation, from the top to the bottom.
I have the following code:
def is_prime(n):
limit = (n**0.5) + 1
q = 2
p = 1
while p != 0 and q < limit:
p = n % q
q = q + 1
if p == 0 and n != 2:
return 'false'
else:
return 'true'
But when I send in an integer, there is nothing returned. The console simply moves on to a new command line. What's wrong here?
EDIT 1:
The following are screenshots of different scenarios. I would like to make it such that I call the function with a particular number and the function will return 'true' or 'false' depending on the primality of the number sent into the function. I guess I don't really understand the return function very well.
Also, note that when I send in to test 9, it returns true, despite 9 being quite definitely a composite number...should the if/else bits be outside the while loop?
Key to below image:
1: this is the code as it is above and how I call it in the Spyder console
2: adding a print statement outside the function
3: this is a simple factorial function offered by the professor
image here
EDIT 2:
I made a quick change to the structure of the code. I don't really understand why this made it work, but putting the if/else statements outside the while loop made things result in expected true/false outputs
def is_prime(n):
limit = (n**0.5)+1
q=2
p=1
while p!=0 and q<limit:
p = n%q
q = q+1
if p==0 and n!=2:
return 'false'
else:
return 'true'
Also, I call the function in the console using is_prime(int_of_choice)
Thanks for the helpful suggestions
If you want to print something to the console you have to use a print statement. The return keyword means that you can use this value in a piece of code that calls this function. So to print something:
print (x)
For more information about the print statement see: https://en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings
Nothing is wrong, but you have to print out the return of your function.
Like this:
def Test():
if True:
return "Hi"
print(Test())
In this case python will show "Hi" in your console.
First, the following is my function.
def countdown(n):
if n <= 0:
return 0.0
else:
print(n)
countdown(n-1)
Second, when I call countdown(0), the result is as below.
>>> countdown(0)
0.0
It means, since 0 <= 0 is true, then do if statement return 0.0.
Next, when I call countdown(3), the result is.
>>> countdown(3)
3
2
1
But I expectation is
>>> countdown(3)
3
2
1
0.0
My question is, why countdown(3) does not return 0.0?
Thank you very much.
Your notion of result mixes up two different things:
something printed by a function, as a side-effect.
something returned by a function, which gets printed by REPL when you call the function in the interactive interpreter, but doesn't get printed otherwise (e.g. if you run the whole program with the python interpreter invoked from the shell).
In your first example, countdown(0) doesn't print anything, but REPL prints the value returned by countdown(0), which is 0.0.
In your second example, countdown(3) ends up calling countdown(2), and so on... but the value from countdown(0) is lost: that's because countdown(1) calls countdown(0) for side-effect only, not returning anything (which is equivalent to returning None).
There are two ways to make countdown match your expectations, when calling it in REPL:
return countdown(n-1) as a final statement;
print 0.0 instead of returning it in the first if branch.
These two variants look the same when run in REPL, but in fact they are different (see the first paragraph above).
You probably didn't want to use return. Instead of return use print().
So your function should be:
def countdown(n):
if n <= 0:
print(0.0)
else:
print(n)
countdown(n-1)
Or simplified (but a bit weird):
def countdown(n):
print(max(0.0, n))
if n > 0:
countdown(n - 1)
As answer to your question I will say: it's because Python shell prints returned object and code doesn't.
Make program which executes your countdown function with value 0 or less.
It won't print anything.
So it's best to not use return for printing things.
EDIT:
You should use return when you (or anyone else) wants to use that value.
Example:
def SUM(a, b, c):
return a + b + c
If you want to use SUM of three numbers you could just write a = SUM(3, 4, 5).
If you used print instead of return a would be None.
Also I think almost all shells prints returned value.
Return printing is like printing values without print, e.g.: if you write 5 + 1 in shell it would print 6, but if it's in function/program it wouldn't do anything.