-1

I'm writing a simple maths sketch. At this point I want to check if 2 random numbers, when divided, leave a quotient. If not then pass them onto the next part of the program. If the quotient is not 0 then go back and pick new numbers. The code works perfectly if the 2 numbers return a quotient of 0 first time through. The numbers are sent to the next function using return. If the numbers don't give a 0 quotient, the code picks 2 new numbers and rechecks. However, when the new numbers fulfill the criteria and are sent on, they are rejected with " cannot unpack non-iterable NoneType object". This has been sent by the same command that works if the numbers fulfill the criteria FIRST TIME!!

def gen(): import random #imports the random number generator rand1 = random.randint(1,100) rand2 = random.randint(1,10) return rand1, rand2 def source(): rand1,rand2=gen() ans = rand1/rand2 print (rand1,rand2,ans)# to check the random numbers come through if rand1%rand2!=0: source() elif rand1%rand2==0: nos=(rand1,rand2) return nos def receiver(): nos = source() print (nos[0]) print (nos[1]) 
New contributor
joe lennox is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
5
  • Thanks. I wanted to use a repeat until loop but don't know how in python. However, I am interested in why this code doesn't work. It's got me baffled. It's the fact that something changes once the recursion happens that prevents the code from passing the variables to the function" receiver". Commented 3 hours ago
  • "quotient" - You keep using that word. I do not think it means what you think it means. Commented 2 hours ago
  • Kelly Bundy You are right. I actually mean the remainder. Commented 2 hours ago
  • @joelennox the line source in the if statement, didn't change the value of rand1, rand2, you need to assign them again. Only to you understand, to your code work, you need to replace that line with rand1,rand2=source(). Commented 2 hours ago
  • @joelennox So please edit the question and fix it. Commented 10 mins ago

1 Answer 1

0

The error occurs because you didn't assign a value to rand1 nor rand2 inside the if, so it never enters in the else and the function returns nothing. With your code, you fall in a recursion. Unless you really want it, the code could work using a simple while loop:

def gen(): import random #imports the random number generator rand1 = random.randint(1,100) rand2 = random.randint(1,10) return rand1, rand2 def source(): rand1,rand2=gen() while rand1%rand2!=0: rand1,rand2=gen() nos=(rand1,rand2) return nos def receiver(): nos = source() print (nos[0]) print (nos[1]) 
Sign up to request clarification or add additional context in comments.

1 Comment

Eddi. Brilliant! that works. Thanks very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.