I'm curious of what's the point of using return statement.
def give_me_five():
five = 5
return five
number = give_me_five()
print("Here's what I got from give_me_five():", number)
Above code shows the following result.
Here's what I got from give_me_five(): 5
As you can see, when you can just type 5 in print("Here's what I got from give_me_five():", 5) like this, what's exactly the point of using return statement and why does it need to even make a function to set a value 5?
Why you need return
Try removing return. It then prints
Here's what I got from give_me_five(): None
If you do not return 5, you have no way to recover it outside your function.
That is why you need return. But then...
Why you need functions
In your example, your function always returns the same value, so it is not needed, but suppose you have a more complex function that returns based on an input.
def give_me_more(n)
return n + 1
This function does not always return the same value, so it is a bit more useful. But then you should ask: wait, can't I just replace that function by n + 1 in my code?
Can't we do without function?
Well yes, but keep in mind that functions can be way more complex than the above examples.
def get_factors(n):
factors = []
for i in range(int(math.sqrt(n))):
if n % i == 0:
factors.append(i)
factors.append(n / i)
return sorted(factors)
Do you want to insert this code in your script everytime you want to get the factors of a number? Of course not, and to be able to reuse code you need to write functions. Which in turn requires return.
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 6 months ago.
I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).
x = 0
def solution(digits):
global x
if len(digits) < 5:
return x
else:
if int(digits[0:5]) > x:
x = int(digits[0:5])
solution(digits[1:])
My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.
So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.
My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.
So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?
Your help would be appreciated!
EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.
Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this :/
Instead of using a global variable, pass x 'along' when you call the function. By setting it to have a default value of 0 it doesn't need to be passed in at the start:
def solution(digits, x=0):
if len(digits) < 5:
return x
else:
if int(digits[0:5]) > x:
x = int(digits[0:5])
return solution(digits[1:], x)
print(solution('9328498503734'))
98503
Typically to make a recursive function work, you need to return some kind of combination of a base result with the result of another recursive call on a reduced version of the original argument. Using globals is usually going to be self-defeating because all the recursive calls will overwrite each other (there's a reason using globals is "shunned", it's because it usually makes your code not work, lol).
>>> def solution(digits: str) -> str:
... """Returns the 5-digit substring of digits with the highest int value."""
... if len(digits) <= 5:
... return digits
... else:
... return max(digits[:5], solution(digits[1:]), key=int)
...
>>> solution("9328498503734")
'98503'
def max_5_digits(digits, _max=0):
return _max if len(digits) < 5 else max_5_digits(digits[1:], max(_max, int(digits[:5])))
max_5_digits("9328498503734")
## 98503
I am trying to chose 10 numbers between 1 and 100 using random function,but unfortunately I am having a problem to use whether return or print function.
Using return function does return me only a single number however if I use print function it gives me 5 numbers but a none is also printed after 5 numbers. I am really confused what to do?
Try this, it may help.
import random
a = [] #take a list to store randomly generated values from the loop.
n = 10
for i in range(n):
a.append(random.randint(1,100))
print("random number list is :",a)
For the first approach(by returning value), you can store the randomly generated values in a list or tuple or set (whatever you like) and then return that sequence.( Refer to #Devi Silparasetti's answer. )
For the second approach (using the print() function) . Use print only in the function which prints those numbers. Don't try to print the function calling. Simply invoke function only.
For example-
def abc():
print('abc')
abc()
Don't use print(abc()) .
I guess what you need is a generator:
def generate_random(n):
for i in range(n):
yield random.randint(1,100)
print([x for x in generate_random(10)])
Generator returns multiple values one at a time. So you can consume these values per request.
The purpose is Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits.
For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.
(Assume that the number you are given will always be positive.)
https://www.codecademy.com/zh/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#
Your function fails on digit_sum(1000). It returns 12 when it should return 1.
If I put the dig=[] upper on the def digit_sum, the course occurred alarm that "digit_sum(1000) result is 12 instead of 1" , but I ran this program on my local notepad+powershell, it ok , the result is right.
after that I put the dig=[] into the first line of function , then it worked normally .
I didn't get 2 points....
What's the difference between "dig=[]" inside/outside the function
if the "dig=[]" outside the function is wrong , why I can ran it successfully on my local....?
Thanks for guys to help me......
dig=[]
def digit_sum(n):
u=str(n)
for i in u:
dig.append(i)
s=0
for number in dig:
int(number)
s=s+int(number)
return s
So the difference between inside/outside is locality. When you put dig outside, you create a global list. From there, you're constantly appending to that- the list is never cleared! So if I run digit_sum(1234), I properly get 10. If I immediately thereafter run digit_sum(1000), dig==['1','2','3','4','1','0','0','0'] which will then add all those and mess up.
If you do dig = [] inside the function, it creates a new, local list - it isn't being changed each time, it's a new empty list for each rotation.
The reason you're getting it correctly sometimes is because the function has side effects, so order of calling and history of calling matters. Try to avoid side effects of functions- either don't alter a list, or copy the list>alter that copy>return the copy if you want to assign the new list (or just work with the new list.)
def digit_sum(n):
n = str(n)
total = 0
for i in n:
total += int(i)
return total
Something like :
def digit_sum(n):
dig=0 # this is the result os the sum
number=str(n) #transform the number into string so we can iterate
for i in range(len(number)):
dig=dig+int(number[i]) #transform the char to int
return dig #return the sum
I take the number (eg 123) and I transform it to a string so I can get the length of the string (the number of digit). Then I simply add them (after transforming them to integers) and return the result
dig=[] means you declare an array variable which is not what you want here. If it is declared in the function it means that when the function ends, the variable "disappeared", you won't be able to call it back. It'll only exist IN the function. If it is before the function, the variable exists to the end of your program.
Your aptenpt isn't correct. You want to populate your array with the number THEN sum them. In fact when you assign a number to your array dig you are summing then. For exemple 123 will sum : 1 then 1+2 then 1+2+3
The previous answer is all right.
Just to focuse your attention so that you could avoid mistakes in the future:
When you write:
u=str(n)
for i in u:
dig.append(i)
you don't append the digits of the number to the dig. Instead you add digits 0, 1 ,2 ,3 .. so on. Exactly them however the number may be. Because the For Loop iterates from the beginning to the end of a string, a list etc. and the variable after the word For is just a counter - starting from 0 and ending at the end of the object.
Tha is why the answer of Hearner is right:
the number[i] 's are summed not the i's.
for i in range(len(number)):
dig=dig+int(number[i])
I need to do some introspection in Numpy/Scipy. While it is relatively easy to find info on how to get the help docstring and the arguments, I was not able to get anything concerning how to get info on the returned values. More specifically, I just would like to find which functions return multiple values, or equivalently (more or less) tuples. Any way to do it?
There is no way you can find this out from Python in general. The answer is not a constant.
def complicated(i):
if i == 1:
return 0
elif i == 2:
return (0,1)
elif i == 3:
return [0,1,2]
elif program_halts(i):
return {}
else
return "Nope"
What is worse, even if you know the inputs, you can't tell the result without solving the halting problem.
Your only chance is to read the documentation.
The documentation ought to tell you, but you can test at runtime if you really need to:
r = something()
if type(r)==tuple or type(r)==list:
for rn in r:
# do something with each returned value
# (which might include further checking if it's a list or a tuple)
elif type(r)==int or type(r)==float:
# it's a scalar numeric value
else:
raise ValueError( "Can't handle {}".format(r) )
In passing a function that returns a list or a tuple should return a list or a tuple of length 0 or 1 to indicate that there was nothing or only one value to return. I have seen codes where you get None, a scalar, or a tuple/list, which makes using the result unnecessarily complex!
I have my program in python and I have used an external file with numbers in, I created a list for the numbers to be stored in and then I need to find the mean, standard deviation and the length of the list from this, at the moment my program looks like this:
data = open( "gauss.dat", "r" )
numbers=[]
for line in data:
numbers.append(line)
sorted(numbers)
def length(numbers):
length = len(numbers)
return length
def mean(numbers):
sum = 0
for element in numbers:
sum += element
mean = sum/length
return (mean)
def main():
global history
print (length)
print('The smallest number is ' + numbers[0])
print ('The largest number is ' + numbers[-1])
print(mean)
return True
if __name__ == "__main__":
main()
When I run the program
It doesn't sort the numbers correctly? I am new to python so I don't know if there is an obvious error
It prints out the mean and length as < function length at 0x039475B0 >, < function mean at 0x03947630 >. I have no idea how to change this into a number?
Hope you can help.
regarding 1)
A powerfull tool: the interactive shell combined with the help-command:
>>> help(sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
So we need either
numbers = sorted(numbers)
or
numbers.sort()
(see help(numbers.sort) for details)
regarding 2)
as stated by mgilson: you have to invoke the function:
print(mean(numbers))
regarding comment
with
for line in data:
numbers.append(line)
you read the file line-by-line as a string. But to do some calculations, you need a numeric type. One way to do this would be:
for line in data:
numbers.append(float(line))
This converts the text in line into a floating type. Leading or trailing spaces are cropped (at least in my python-interpreter) but you may run into trouble with empty or erroneous lines.
You need to call the function length and/or mean :
print(length(numbers))
print(mean(numbers))
In python, functions are objects themselves. So they have a representation that gets printed. You can assign them to different names in your current namespace, pass them to other functions, etc. e.g.
MeAn = mean # This is a violation of PEP 8!
print(MeAn(numbers)) #same as `print(mean(numbers))`
In other words, when you tell python:
print(mean)
It prints information about the function object mean. It doesn't run the function however, so there is no way to get at it's return value (After all, how should it know what to use as input arguments?)
sorted returns sorted version of iterable, but doesn't change it, you need one of those:
numbers = sorted(numbers)
or:
numbers.sort()
About functions, you need to call them, with necessary arguments - eg:
mean = sum/length(numbers)
You have this bug in several places in your code.