python - to dynamically generate variables using repetitive statements

Asked 2 years ago, Updated 2 years ago, 126 views

Python - Dynamically generate variables using repetitive statements

I'm a self-taught Python student

I want to make a multiplication game If you print out a question for one minute, you will write down the answer to the question and solve it in a set time.

When a * b is done, both a and b values are declared as random values. The problem is, for example, a1 * a2 or a2 * a3 * a4 would be random I don't know how to declare a variable.

defquestion(a): #Create a problem
    b = random.randomint(1,5) # b = random

    if(b == 2):
        i = random.randint(2,12)
        j = random.randint(2,12)
        print(i,'*',j)
        result = i * j
    elif(b == 3):
        i = random.randint(2,12)
        j = random.randint(2,12)
        k = random.randint(2,12)
        result = i * j * k
        print(i, '*', j,'*',k)
    elif(b == 4):
        i = random.randint(2, 12)
        j = random.randint(2, 12)
        k = random.randint(2, 12)
        l = random.randint(2, 12)
        print(i, '*', j, '*', k,'*',l)
        result = i * j * k * l

I'm currently trying to make it like this, but I'm asking if there's any other way. Thank you.

You are about to create multiple variables.

ex) You want to create multiple variables with integer values. I want to create multiple variables in a1, a2, a3, a4,... expressions at once.

python loops variable

2022-09-21 19:25

1 Answers

If you want to create multiple variables, you can write list. I think it's possible.

import random
import numpy as np
count = random.randint(2,5)
numbers = [random.randint(2,12) for i in range(count)]

# Convert numbers to str for output
print(" * ".join([str(i) for i in numbers]))
print("=",np.prod(numbers))


2022-09-21 19:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.