My functions are not running - python

Working with random functions and doing 3 things with 3 different functions, the first gives me values from 1,10 randomly displayed in a list of 10 integers. The second gives me a list values 1,10 and squares them. Then last but not least the third singles out numbers that can be divided by three. The problem is my program is not running while on eclipse the program has no errors, yet my program terminates without printing anything. Please help me...
import random
def main():
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
if __name__ == '__main__':
main()

You are just calling main() not any of the functions nested inside main(),
Using if __name__ == '__main__': does not magically call all your functions.
If your main function was like:
def main():
squareint_()
div3()
rand10()
then you would be calling the other functions as it is, main does nothing or returns nothing.
As far as your methods go, squares.append(random.randint(0,10))**2 is not valid, you cannot use ** on a list method.
It needs to be inside the paren squares.append(random.randint(0,10)**2)
Also num is a list so you cannot use if num % 3 == 0:
You could use something like:
def div3():
divlist = []
num = range(1,10)
for n in num: # loop over the list elements
if n % 3 == 0:
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist

There are two current problems with the code:
You're defining your functions inside main(), which is allowed but it's not very good coding practice. If you do this, then you can only ever use these functions from inside main().
You're not actually calling any of your functions, you're just defining them. They need to be called with rand10(), squareint_() or div3().
Try this bit of code instead, which fixes both issues:
import random
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
def main():
rand10()
squareint_()
div3()
if __name__ == '__main__':
main()
Of course, if your functions are invalid, then they will need to be fixed on their own. This just solves the issue of nothing happening when you execute your code. Now when you run the project in Eclipse, you'll see some errors and be able to fix them properly.

Related

Change result by function - python3

I need to generate random number with 4 various literature,
so i wrote this program:
import random
def rand():
i=0
n=""
while i<4:
a = str(random.randint(0,9))
if a not in n:
n +=a
i+=1
return n
print (rand)
The content of the function is correct, but the function cause to strange result :
<function rand at 0x000001E057349D08>
what am I missing?
You are printing the reference to the function itself instead of invoking it. To invoke it, you need to follow it with parenthesis (()):
print (rand())
# Here ----^

Setting up a simple function in Python

I'm trying to write a function which takes my input as amount of dicerolls, gets a random number between 1,6 for that amount of dicerolls, and then appends these to a list.
I've tried different return messages, but I can't seem to to make it append to a list, and can't really think of what else I can do with my code.
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print(terninger)
I'm expecting the code to append the random number 1,6 into my list above (terninger), but I'm only receiving an empty list.
you forgot to call your function => terning_kast()
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print('before', terninger)
terning_kast() # this is the line which you have missed
print('after', terninger)
There are few points that you need to correct in your logic. Meantime, following is probably that you want.
import random as rnd
def terning_kast(count):
terninger = []
for x in range(count, 0, -1):
resultat = rnd.randint(1, 6)
terninger.append(resultat)
return terninger
if __name__ == "__main__":
cnt = input("Hvor mange terningekast? ")
if cnt.isdigit():
print(terning_kast(int(cnt)))
else:
print("Invalid entry")
In order to use the random module, first you need to import it into your module.
Though you are appending the generated random number to list, you never attempt to return that list. What you are returning is the last instance of result from the randint(x,y) function call.
You are defining your function as part of your module/script. In order to execute that function, you must either call it within module or import it to some other module. If you look at my example the if __name__ == "__main__": instruct the python interpreter to run your script if you were to execute from same module. If you were to consume this module (importing) from some other then you don't need to mentioned this if __name__ == "__main__":

Python: Why does return not actually return anything that I can see

I have the following code:
def is_prime(n):
limit = (n**0.5) + 1
q = 2
p = 1
while p != 0 and q < limit:
p = n % q
q = q + 1
if p == 0 and n != 2:
return 'false'
else:
return 'true'
But when I send in an integer, there is nothing returned. The console simply moves on to a new command line. What's wrong here?
EDIT 1:
The following are screenshots of different scenarios. I would like to make it such that I call the function with a particular number and the function will return 'true' or 'false' depending on the primality of the number sent into the function. I guess I don't really understand the return function very well.
Also, note that when I send in to test 9, it returns true, despite 9 being quite definitely a composite number...should the if/else bits be outside the while loop?
Key to below image:
1: this is the code as it is above and how I call it in the Spyder console
2: adding a print statement outside the function
3: this is a simple factorial function offered by the professor
image here
EDIT 2:
I made a quick change to the structure of the code. I don't really understand why this made it work, but putting the if/else statements outside the while loop made things result in expected true/false outputs
def is_prime(n):
limit = (n**0.5)+1
q=2
p=1
while p!=0 and q<limit:
p = n%q
q = q+1
if p==0 and n!=2:
return 'false'
else:
return 'true'
Also, I call the function in the console using is_prime(int_of_choice)
Thanks for the helpful suggestions
If you want to print something to the console you have to use a print statement. The return keyword means that you can use this value in a piece of code that calls this function. So to print something:
print (x)
For more information about the print statement see: https://en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings
Nothing is wrong, but you have to print out the return of your function.
Like this:
def Test():
if True:
return "Hi"
print(Test())
In this case python will show "Hi" in your console.

Issue with maps, for loops and list comprehensions

kn = input().split(" ")
n = int(kn[0])
k = int(kn[1])
niz = list(map(int, input().split(" ")))
newlis = []
def rad(o):
return sum(niz[num:(num+k+o)])/(k+o)
def posao(k):
return max(list(map(rad, range(0, n-k))))
for num in range(len(niz[0:(n-k+1)])):
newlis.append(max(list(map(rad, range(0, n-num)))))
#newlis = [max(list(map(rad, range(0, n-num)))) for num in range(len(niz[0:(n-k+1)]))]
print(max(newlis))
So I've got this working with a for loop and now I want to use the commented out list comprehension (or even map()) to make it faster. Problem is, it keeps returning that num is not defined when I use either. I'm completely aware the code is very messy and unclean, but if someone could tell me where I'm going wrong with this, I'd appreciate it. I'm only a beginner with python.
def rad(o):
return sum(niz[num:(num+k+o)])/(k+o) // I guess the problem should
// be here... as ^ num is not defined in this function and neither it is a global variable
Try passing num as argument
def rad(o,num):
return sum(niz[num:(num+k+o)])/(k+o)
newlis = [max([rad(x, num) for x in range(0, n-num)]) for num in range(len(niz[0:(n-k+1)]))]

recursive function in class in python

I don't know, why isn't working that code in python. The problem is, that I can get numbers, but sometimes some numbers are uniform. And I want to do 5 different numbers between 1 and 90.
class lottery:
def __init__(self):
self.price = 50
def list(self):
numbers = []
for i in range(0,5):
numbers.append(random.randint(0,90))
for i in range(1,5):
for j in range(0,i-1):
if (numbers[i]==numbers[j]):
game.list()
return numbers
game = lottery()
game.list()
Or is there any better way to solve my problem?
Thanks!
Use random.sample:
def list(self):
return random.sample(xrange(90), 5)
This is (especially for large values of 5) much more efficient than starting over every time your randomization creates a repeat, and also avoids the possibility of overflowing the stack.
First of all you should import the random module:
import random
The problem is that you are not returning the result that you get from the recursive call, therefore you are still returning the list with repeated numbers. It should be:
def list(self):
numbers = []
for i in range(0, 5):
numbers.append(random.randint(0, 90))
for i in range(1, 5):
for j in range(0, i - 1):
if (numbers[i] == numbers[j]):
return self.list() # return
return numbers
note that self is used to access to the instance of the class that calls the method. Also, don't forget to print the results:
game = lottery()
print game.list()
Note:
Don't use list as the name of a variable or method because it will hide the built-in definition of list.

Categories

Resources