Explain the code

can someone please explain how the answer to the following code is 21

def any(var):
print(var + 1, end = ’ ’

var = 1
any()
print(var)

First of all. Welcome to phython world. And as you have heard Indentation is very important in pyton. So your code in such state is not readable. It is not clear where function starts where ends. Also when you call a function you must to pass argument - example
`

first = 1 
any(first)`

and your function must to return something or print, so function you use to not repeat yourself.

Hi MariaK

Good advice offered by Gintsm and the trick with this forum when pasting code is to first select ‘Preformatted text’ (CTRL+E), then paste your code between the 2 lines of quotes.

I edited your code slightly so it works…

def any(var):
    print(var + 1, end = '')


var = 1
any(var)
print(var)

… and as you say, it does result in 21.

In fact, if you comment out the last line like so…

def any(var):
    print(var + 1, end = '')


var = 1
any(var)
#print(var)

the result is now just ‘2’.

I didn’t know what the ‘End’ parameter was for (I’m about 30% through the course), but I know now…

Let’s remove the function part as it’s just a distraction.

Look at this…

var = 1
print(var + 1)
print(var)

So now the result is…

2
1

Which is what we would expect. But look what happens when we use that ‘End’ parameter.

var = 1
print(var + 1, end = '')
print(var)

Now the result is…

21

Normally a print statement finishes with a newline command, but as we see, the End parameter set as so, stops the new line meaning the 2nd print statement will appear adjacent on the same line. More info here…
https://www.toppr.com/guides/python-guide/questions/what-does-end-do-in-python/