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.
Related
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.
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 have lists which consist of random letters..
def similarity(out_list):
i=0
count=0
while i<len(out_list):
if out_list[i][-1]==out_list[i+1][-1]:
count+=1
return similarity(out_list[i][:-1]) + count
elif out_list[i][-1]!=out_list[i+1][-1]:
return similarity(out_list[i][:-1])
i+=2
out_list=["ABABA","ACA","AGAGA","AAVA","XBX","ARAA","AADA","AAA","BABAB","ABA"]
similarity(out_list)
In my code I'm trying to find difference between list elements which are first and second, third and forth etc..
However since my function is recursive, the value of i is always 0 and I can't control other elements and I can't find the difference..
for ABABA and ACA the difference is 3 because first A and third A are the common in both words at same indexes.. so difference 5-2=3
what changes do my code require? Thank you.
Consider passing i as a parameter into your recursive function instead of setting it as 0 at the very start of the function. It's likely you would want to do something similar to count too.
I do not understand how the following code works in the function:
for i in range(len(s)-len(sub)+1):
if sub == s[i:i+len(sub)]:
Why cant I just pass range(4) for it to work?
write a function that takes two string parameters called 'sub' and 's' and returns the number of times sub occurs as a contiguous substring of s
s= "nickdick"
sub= "ick"
def function(sub,s):
count = 0
for i in range(len(s)-len(sub)+1):
if sub == s[i:i+len(sub)]:
count +=1
print(count)
return count
You can use 4 and it would be valid code if len(s)-len(sub)+1 happened to be 4 for those strings. However, the purpose of writing it using len is so that if you decide to change s or sub, the code still functions and you don't have to go through and manually change the "magic constant" 4.
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.