def name(n):
if n>0:
name(n-1)
name(n-1)
print(n)
name(5)
How this is generating 1,1,2,1,1,2,3.....so on output? like which function is working first or both working simultaneously and how n is printing like this.
Try with smaller numbers. For example if you run name(1) it will just print 1. becase two functions in the middle will just return. If you write name(2) it will run the first inner funtion, which will print 1(like I said previously). Second function will do the same and last statement will print 2. So the output is 1 1 2. If you go for name(3) it will just the same as name(2) but twice and will print 3 at the end (1 1 2) (1 1 2) 3. name(4) will do name(3) twice and print 4 at end and so on
Another way to lok at this is in reverse. eg. you look at the smallest number:
name(0): Prints nothing, thus ""
name(1): calls name(0) twice, and then prints 1, thus "1"
name(2): calls name(1) twice, and then prints 2, thus "112"
name(3): calls name(2) twice before it prints 3, thus "1121123"
name(4): calls name(3) twice before it prints 4, thus "112112311211234"
name(5): calls name(4) twice before it prints 5, thus "1121123112112341121123112112345"
Finally the clue is that there is no spcial treatment of functions that recurse. Every call to a function, even print, will wait for that to return and then continue on the next line as long as the statement didn't include a return in which it would return. that name(5) ends up calling itself with different versions of n at different levels is no problem because each of them has their own version of n that is unique to that call.
Hello I attached this image that shows explanation in details
Related
I was trying to solve the following problem: Draw a star pattern that increases in every step (1st step: 1 star, 2nd step: 2 stars). E.g.
*
**
I am not sure why my code is not showing any output when I am writing return? When I am writing print, it is giving me the star output but also giving me None. May I know why return or print are not working properly? I am using Python 3.7. My code is:
def string(inp):
for i in range (inp):
return i*"*"
print (string(5))
range starts at 0, and return terminates a function, so that means string will always return an empty string.
Here's one possible option for getting your expected result:
def stars(n):
for i in range(1, n+1): # Add one to start and stop
print(i * "*") # Print inside the function
stars(2) # Don't print outside the function
Output:
*
**
If you need to print outside the function, you could use a generator:
def stars(n):
for i in range(1, n+1):
yield i * "*" # "yield" is like "return" but can be used more than once
for s in stars(2):
print(s) # Print each string that gets yielded
# Or print all at once, using the "splat" unpacking operator
print(*stars(5), sep='\n')
Using return won't print an output, use something like this:
def string(inp):
for i in range (inp):
print(i*"*")
string(5)
also this will only print 4, if you make it
for i in range(inp + 1):
It will work as intended,
hope this helps!
I will translate the code to plain English, as explicitly as I can:
Here are the rules that take a value `inp` and compute the `string` of that `inp`:
Letting `i` take on each integer value from 0 up to but not including `inp`:
We are done. The `string` of `inp` is equal to the string '*' repeated `i` times.
Compute the `string` of `5` and display it.
Hopefully the problem is evident: we can only be done with a task once, and i is equal to 0 at that point, so our computed value is an empty string.
When I am writing print, it is giving me the star output but also giving me None
From the described behaviour, I assume that you mean that you tried to replace the word return in your code with print, giving:
def string(inp):
for i in range (inp):
print(i*"*")
print (string(5))
That produces the triangle, of course, except that
Since i will be equal to 0 the first time through the loop, a blank line is printed; and since i will be equal to 4 the last time through the loop, there is no ***** line.
At the end, None is printed, as you describe. This happens because the value computed by string is the special value None, which is then printed because you asked for it to be printed (print(string(5))).
In Python, each call to a function will return a value when it returns, whether or not you use return and whether or not you specify a value to return. The default is this special None value, which is a unique object of its own type. It displays with the text None when printed, but is different from a string with that text (in the same way that the integer 5 is different from the string "5").
May I know why return or print are not working properly?
They are working exactly as designed. return specifies the result of calling the function, and can only happen once per function, and does not cause anything to be displayed. print displays what it is given.
If you wish to return multiple values from a call, then you need to work around that restriction - either by using a generator instead (as in #MadPhysicist's or #wjandrea's answers), or by using some single, structured datum that contains all those values (for example, a list, or a tuple).
A a re-entrant function that preserves state between calls is a generator. To make a generator function, change the keyword return to yield:
def string(n):
for i in range(n):
yield (i + 1) * '*'
Calling this version of string will return a generator that yields a new line of your desired output at each iteration.
To print:
for line in string(5):
print(line)
To print all at once:
print('\n'.join(string(5)))
This is a loop in PYTHON 3.X.
for i in range(2, 2):
print(i)
The result that I got after running this program was a blank console.
What type of output we get from this loop.
The range of numbers returned are integers from start to stop. ( the first param being start, and second being stop when 2 are given)
It includes the start int, but not the stop int.
hence, range(2,2) contains no numbers in between.
range(2,4) returns 2,3 but not 4.
Documentation here.
The reason you're getting blank output is because what the range() function does.
The first argument in the range() function tells the function which number to iterate to.
So, if this was your code:
for i in range(2):
print(i)
Then your output would be:
0
1
It starts from 0 and prints two numbers, because of the two.
However, the second parameter in your code tells it what to count by. For example, you added a 2 for the second parameter. This tells the program to skip count by 2, and since you have only 2 output in the first place, the program doesn't print anything
Read up on range in python 3.
Hopefully this helps!
I am new to python and working on basic functions and conditionals.
Here's an example of 1 function in my code:
def oddEven(oe):
if oe % 2 == 0:
print("number is even")
else:
print("number is odd")
There are 3 total functions in my code (omitted because unnecessary). The first two pass the value of the integer named first, and the last function takes two integer parameters and pass both first and second and checks the result.
Here is how I'm recalling these and checking my code
first = 30
second = 60
oddEven(first)
minutes(first)
relation(first, second)
Instructions say:
Run the program five times using the provided first values and your chosen second values, and check your results. You can alternatively run the program once and use a for loop to execute your code five times.
If the values were for example 23, 33, 14, 31 I could just do:
oddEven(23)
oddEven(33)
oddEven(14)
oddEven(31)
Right? And then do the same for the second function and the third. How could I make a for loop for this?
This is simple way to do this :
list_values = [22,33,14,31]
for value in list_Values:
oddEven(value)
You’re right, you use a for loop in order to do that. The previous answers may have been able to iterate through the list for both the evenOdd and minutes functions, but they didn’t handle the case where you compare two consecutive values for your relation function.
Create a list of 5 numbers and iterate through it. Handling the case where you’re comparing two consecutive numbers against each other can be done with a simple if statement that stops executing once you’ve reached the second to the last element in the list.
If you’re not familiar with lists yet, think of them as ‘containers’ for your data; where you can systematically store and access each piece one at a time.
What’s happening in the code is the for loop iterates through the list one element at a time. The function range(n) takes in a number n, for an argument, and then creates a ‘range’ of numbers from 0 to n - 1.(Ex. range(2) will iterate through the for loop 2 times giving i a value of 0 on the first loop and 1 on the second.
An element from a list can be accessed with this notation: list[i], where i is a number that starts from 0 (therefore accessing the first element of the list) and ranges all the way up to the (length of the list - 1). So to access the third element in a list would be done like so: list[2].
The code below is pretty modular so you can add any amount of numbers to the numbers[] list and it should work, given that there is more then 1 number in the list. It’s a good practice to get in the habit of making your code as modular as possible, instead of hard coding in constants. This is done by passing the (length of the list) to the range(), which allows the for loop to iterate over any size list.
If you add only one number to the list ( ex. numbers = [42]), the only thing that would happen is that the code inside the if statement will not execute, as it requires there to be more than 1 number in the list. The oddEven and minute function should still work though. Go ahead and give that a try! Try adding more than 5 numbers to the list too.
numbers = [23, 33, 14, 21, 42]
for i in range(len(numbers)):
first = numbers[i]
oddEven(first)
minutes(first)
if i < (len(numbers) - 1):
second = numbers[i + 1]
relation(first, second)
Hey guys can anyone explain that output to me?
Don't get why its counting down again.
def kaboom(i):
print("first Print: ", i)
if i < 3:
kaboom(i+1)
print("second Print: ", i)
OUTPUT:
first Print: 1
first Print: 2
first Print: 3
second Print: 3
second Print: 2
second Print: 1
Second Print counts down because for every call you make to kaboom(i+1), that call is being put on the top of a stack of calls. Once i >= 3, the stack stops growing and the calls are being popped off where they left off. So 3 is printed and that execution of kaboom(2+1) finishes. Then the call to kaboom(1+1) resumes where it left off and prints 2 and finishes. Finally kaboom(1) resumes and prints 1.
your function is diving to the farthest call then is coming back and is printing second Print
call 1 --> i = 1 back to call 1 --> second Print, i it is still 1
↓ ↑
call 2 --> i = 2 back to call 2 --> second Print, i it is still 2
↓ ↑
cal 3 --> i = 3 (end of call chain, it goes back)
To understand this you need to understand how recursion works. It works on the concept of stacks. You can have a look at the following link, to get a clear understanding : https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
You are calling the same function again if i<3, so it's printing first print and so on.. but after it's returned, the execution won't end there right. It has to execute rest of the method, which is second print.
recursion strategy uses stacks which works as Last In First Out. In your case, If I am right, your base condition is satisfied only at 3 and until then it is stored in the stack and then getting printed.
Think of it this way: you create a new occurrence of kaboom every time it is called.
the first time kaboom is called i is one. First is printed and kaboom(2) is called. First is printed and kaboom(3) is called. First is printed and kaboom is not called again because i=3. BUT kaboom(3), kaboom(2), and kaboom(1) are not done yet because they still have to print the second time. Because kaboom(3) was opened most recently it has to close first, hence why second 3 is printed first. Then kaboom(2) prints second 2 and finally kaboom(1) finally finishes by finally printing second 1.
I was testing with something and I wrote this code for example purposes.I felt the output I got was weird.I expected that function calls are executed one after the other but according to this code both the print statements are getting executed after each other and then the return values are printed together.What does this mean and what is the flow of the code in this case?
global num
num=5
def demo(num):
num+=1
print("hi")
return(num)
print(demo(num),demo(num))
output-
hi
hi
6 6
I expected that function calls are executed one after the other
That's exactly what happens.
But there's no way the print can happen before the demo calls, because it's trying to print out the values returned by those calls. (You can loosely think of this as a special case of anywhere you see parentheses: 2 * (3+4) can't multiply by 2 until it's added 3+4, and print(demo(num), demo(num)) can't print the results of demo(num) and demo(num) until it's called them. But don't take that too literally.)
So, those demo calls happen left to right, then the print call happens.
In more detail, let's step through how it evaluates this line:
print(demo(num),demo(num))
… Python has to do this:
Evaluate print by looking it up as a builtin name, which finds the builtin print function.
Evaluate the first argument.
Evaluate demo by looking it up as a global name, which finds the global demo function that you defined.
Evaluate num by looking it up as a global name, which finds the global 5 value.
Call the function on the argument.
The parameter num gets the value passed in, 5.
num += 1 updates the local variable (parameters are local variables) num to 6.
print("hi") prints out hi.
return(num) returns the value of the local variable, 6.
Evaluate the second argument.
… same as above, it prints out hi and returns 6.
Call the function returned by evaluating print on the two arguments returned by the two calls, so it prints out 6 6.
If you want the rigorous definition, he details are covered in Calls in the reference documentation. In particular (stripping out irrelevant bits)
call ::= primary "(" [argument_list] ")"
…
The primary must evaluate to a callable object…. All argument expressions are evaluated before the call is attempted.
according to this code both the print statements are getting executed after each other and then the return values are printed together
Yes. The two function calls have to be executed in order, so that it can get the values to pass to the print function. Executing them prints out Hi twice. Then it has all the values, so it can print them, which prints out 6 6, since both values are 6.
Program evaluation has an order of operations just like arithmetic does. And similarly, it's not always intuitive, especially when we "consume" things left to right, up to down while reading.
So, what gives? Lets become the python interpreter and see why order of operations is important.
# A wild statement appears. Time to compute!
print(demo(num),demo(num))
# I cant't print yet! i'm missing info!
I need to evaluate this first demo(num), and by default im going to do it a closed room away from globals
# evaluating demo(num=5) - num here is a new local variable, it has no relation to the global one defined above
num+=1 # num = 6
print("hi") # [[[PRINT hi]]] ~> to console
return 6 # returns the value 6 filling in another piece of the puzzle
Where are we at now? Almost ready to call this print, just need to do this demo thing again
print(6, demo(num))
# What is num though?
# Well, the only num I know of out here in global space is 5
print(6, demo(5))
# evaluate: demo(5)
This seems familiar!
# evaluating: demo(num=5) - again, a NEW local variable is created just for this function call
num+=1 # num = 6
print("hi") # [[[PRINT hi]]] ~> to console
return 6
Finally, print has all its arguments it needs
print(6, 6) # [[[PRINT 6 6]]] ~> to console
print is not magic, it's just another function! Same as the demo you wrote.
And functions will not evaluate until all their parameters are supplied.
print(a, b) needs the values of a & b before it can do its thing.