Home > Software design >  How can I set random to change at each loop in python
How can I set random to change at each loop in python

Time:12-14

I want to create a loop that generates a different equation for each loop. But when I tried to create a code, it only created the same equations several times.

import random
count=range(random.randint(1,10))
terms_range=range(1,11)
num_terms=random.radint(1,10)

#This is where the calculation will be written
calculation=''
result_from_user=''
signs=''

def sign_generator(x):
  #This function will randomly generate the sign
  sign=random.randint(1,4)
  if sign == 1:
     x = ' '
     return x
  elif sign == 2:
     x = '-'
     return x
  elif sign == 3:
     x= '*'
     return x
  else:
     x='/'
     return x

    

for x in count:
  while num_terms>0:
     terms=random.randint(1,9)
     terms=str(terms)
     signs=sign_generator(signs)
     if num_terms !=1:
         calculation=calculation terms signs
     else:
         calculation=calculation terms
     num_terms-=1
        
  print(calculation)
  result_from_user=input('= ')

How should I fix my code?

CodePudding user response:

It appears to work when I try, just fixed misspelling in line 5 num_terms=random.radint(1,10) to num_terms=random.randint(1,10)

CodePudding user response:

You're getting the same result over and over because you only build one calculation and then exhaust num_terms. To fix this you'd need to reset calculation and num_terms in each loop:

for x in count:
    calculation = ""
    num_terms = random.randint(1, 10)
    while num_terms > 0:
        terms = random.randint(1, 9)
        terms = str(terms)
        signs = sign_generator(signs)
        if num_terms != 1:
            calculation = calculation terms signs
        else:
            calculation = calculation terms
        num_terms -= 1

    print(calculation)

prints:

7 5-3/5-3
7 4*4
9/4/2
3-8/7-1*4*5-3*5/1
8*9-8
1/1*3 5 3/7
6-9 7-2*7-6
4/7*3-3*9/7*6-3
8*7/8*1 7/2*9/9/6

Going further, the overall code can be simplified quite a bit by using random.choice to generate the sign and iterating over a range to build the terms instead of using a while loop. That gives you way fewer variables to keep track of and makes the whole thing only seven lines of code:

import random


for _ in range(random.randint(1, 10)):
    calculation = ""
    for _ in range(random.randint(0, 9)):
        calculation  = str(random.randint(1, 9))
        calculation  = random.choice(" -*/")
    calculation  = str(random.randint(1, 9))

    print(calculation)
  • Related