When I run my python program from terminal with python sumSquares.py, I get the following result: <function diffSum at 0x1006dfe60>
My program looks like this:
def diffSum():
sumSquares = 0
for i in range(0, 100):
sumSquares += i**2
squareSum = 0
for i in range(0, 100):
squareSum += i
squareSum **= 2
print (squareSum)
return sumSquares - squareSum
print(diffSum)
Even though I have a print statement at the end, it doesn't actually print the result that is returned; it just prints the function address. Any ideas why this is?
You need to call the function by adding parentheses after its name, as in:
print(diffsum())
Related
I am new to Python and want to understand why there is no use of return in the following code, and still it is working perfectly fine.
def printCount(num):
for i in range(2, num +1):
print(i)
printCount(10)
If you don't use the return statement in your function definition, the implicit statement
return None
is appended to the function body.
It means that your code
def printCount(num):
for i in range(2, num +1):
print(i)
printCount(10)
is fully equivalent to the code
def printCount(num):
for i in range(2, num +1):
print(i)
return None
printCount(10)
In python return stops the function, and sends the returned value back. For example:
def printCount(num):
for i in range(2, num +1):
return(i) #THIS IS USING RETURN
printCount(10)
count = printCount(5)
In this code, on the first iteration in the for loop, it would return i, which would be 2. This would stop the function and set the variable count to the returned value, which is 2. The function wouldn't do anything else.
In your code, I pressume that return is not used because the desired output is:
2
3
4
5...
If you used return, the code would send back 2 at the beginning and that would be it.
I need to write a function that prints a timer as output (everything at the same time). However, I need to write "Ready?" at the beginning, so I only want it to be printed once.
Here's what I have so far:
def factorial(i):
while i > 0:
print(i)
return (factorial(i-1))
print('Go!')
factorial(5)
I want the function to print the output like so:
Ready?
5
4
3
2
1
Go!
You can use an inner function:
def factorial(i):
def recursive_output(i):
if i > 0:
print(i)
recursive_output(i-1)
print("Ready!")
recursive_output(i)
print("Go!")
You can add an argument to the function
FIRST_TIME = True
NOT_FIRST_TIME = False
def factorial(i, is_first_time):
if is_first_time:
print('Ready?')
if i:
print(i)
return (factorial(i-1, NOT_FIRST_TIME))
print('Go!')
factorial(5, FIRST_TIME)
What is the problem?
i even tried this at the starting soas to get a output
print("enter list elements")
arr = input()
def AlternateRearr(arr, n):
arr.sort()
v1 = list()
v2 = list()
for i in range(n):
if (arr[i] % 2 == 0):
v1.append(arr[i])
else:
v2.append(arr[i])
index = 0
i = 0
j = 0
Flag = False
#set value to true is first element is even
if (arr[0] % 2 == 0):
Flag = True
#rearranging
while(index < n):
#if 1st elemnt is eevn
if (Flag == True):
arr[index] = v1[i]
index += 1
i+=1
Flag = ~Flag
else:
arr[index] = v2[j]
index +=1
j += 1
Flag = ~Flag
for i in range(n):
print(arr[i], end = "" )
arr = [9, 8, 13, 2, 19, 14]
n = len(arr)
AlternateRearr(arr, n)
print(AlternateRearr(arr))
There's no error.
Just the driver code dosen't work i guess, there's no output.
no outputs
The only place where it could output anything is print(AlternateRearr(arr)). But let's take a look at AlternateRearr itself - what does it return?
There's no return statement anywhere in AlternateRearr, so the print would show None. Well, it's something, not completely nothing...
But the code doesn't reach this part anyway - if it did, it would throw an error because print(AlternateRearr(arr)) passes only one argument to the function AlternateRearr that takes 2 arguments. You don't have default value set for n, so it wouldn't work.
Okay, so we came to conclusion that we don't reach the print anyway. But why? Because you never call it. You only define it and it's a different thing from calling it.
You might encounter a problem if you just try calling it near your normal code - Python is an interpreted language, so your main-level code (not enclosed in functions) should be at the bottom of the file because it doesn't know anything that is below it.
Is that your complete code?
Because you do have a function called AlternateRearr but you never call it
Call the function and also pass the integer for iteration.
Add after the function:
AlternateRearr(arr, 5)
I want to use return instead of print statements but when I replace the print statements with return I don't get anything back. I know I'm missing something obvious:
def consecCheck(A):
x = sorted(A)
for i in enumerate(x):
if i[1] == x[0]:
continue
print x[i[0]], x[i[0]-1]
p = x[i[0]] - x[i[0]-1]
print p
if p > 1:
print "non-consecutive"
break
elif x[i[0]] == len(x):
print "consecutive"
if __name__ == "__main__":
consecCheck([1,2,3,5])
-----UPDATE------ HERE IS CORRECTED CODE AFTER TAKING HEATH3N's answer:
def consecCheck(A):
x = sorted(A)
for i in enumerate(x):
if i[1] == x[0]:
continue
print x[i[0]], x[i[0]-1]
p = x[i[0]] - x[i[0]-1]
print p
if p > 1:
a = "non-consecutive"
break
elif x[i[0]] == len(x):
a = "consecutive"
return a
if __name__ == "__main__":
print consecCheck([4,3,7,1,5])
I don't think you understand what a return statement does:
A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address.
You need to wrap consecCheck([1,2,3,5]) in a print statement. Otherwise, all it does it call the function (which no longer prints anything) and goes back to what it was doing.
print takes python object and outputs a printed representation to console/output window
when return statement used in function execution of program to calling location, also if function execution reaches to return statement then no other line will be executed. read detail difference between print and return
So In your case if you want to show result in output console you may do it as following example:
def my_function():
# your code
return <calculated-value>
val = my_function()
print(val) # so you can store return value of function in `val` and then print it or you can just directly write print(my_function())
In your code you are printing values and continuing execution in that case you might consider using yield keyword suggested by #COLDSPEED or just use print to all statement except last one
When I run these commands in the interpreter I get the result I want. However when I try to run it using a .py file I do not. Im new to coding and in my brain I don't understand why this code does not work.
in the interpreter:
>>> a = 'This dinner is not that bad!'
>>> n = a.find('not')
>>> b = a.find('bad')
>>> if n < b:
a.replace(a[n:], 'good')
'This dinner is good'
This is the result I want.
When I run this code I do not get the result I want. What am I doing wrong, and why does this code not work?
def test(s):
n = s.find('not')
b = s.find('bad')
if n < b:
s.replace(s[n:], 'good')
print test('This dinner is not that bad!')
This is a exercise from the google intro to python course. I have the correct answer from the example, and understand how that works. Im just not sure why my code is not working.
Thanks for the help.
def test(s):
n = s.find('not')
b = s.find('bad')
if n < b:
return s.replace(s[n:], 'good')
print test('This dinner is not that bad!')
You should return the result from function test.
Because in the function version, you will get None as default value, you didn't return the value :
def test(s):
n = s.find('not')
b = s.find('bad')
return_res = ''
if n < b:
return_res = s.replace(s[n:], 'good')
return return_res
print test('This dinner is not that bad!')
Output:
This dinner is good
Or not use return_res:
def test(s):
n = s.find('not')
b = s.find('bad')
if n < b:
return s.replace(s[n:], 'good')
return "something else"
print test('This dinner is not that bad!')
The interpreter in most (or all?) IDEs, if I'm not mistaken (I execute my code with Sublime, which saves and runs the file instead when executing), you get the result of your last expression printed automatically, giving you the false impression that python code behaves in this way. It doesn't.
So in other words: Your code works just the same in both the interpreter and the file. The problem you have is one of misconception, that the code is doing something different in the interpreter. What's really happening is that in neither code snippet do you actually catch the result and print it; in the case of the interpreter, it prints it automatically as kind of a visual aid, but you can't rely on that.
In your second snippet, you would have to write:
return s.replace(s[n:], 'good')
Notice the use of return in this case. In your first example, you also should be catching it or at least printing the result explicitly. But because it isn't enclosed in a function, the equivalent would be:
if n < b:
print a.replace(a[n:], 'good')
or:
if n < b:
newString = a.replace(a[n:], 'good')
print newString