Jakob Nolda
Jakob Nolda

Reputation: 3

How to generate a random number with the amount of digits, the user enters?

I'm making a small math program for practice purposes.

The user is supposed to enter, how many digits the two summands should have.

I did this as shown below:

import random
digits = int(input("How many digits should the numbers have? "))
if digits == 1:
    while True:
        num1 = random.randint(0,9)
        num2 = random.randint(0,9)
        solution = num1 + num2
        print(str(num1) + " + " + str(num2) + " = ? ")
        question = int(input())

How can I automate the process, so that I don't have to manually add the digits as they increase?

Upvotes: 0

Views: 606

Answers (2)

Zunderding
Zunderding

Reputation: 61

I might assume there is a better option, especially with less type conversion, but on the top of my head, this would be the option to get an n-digit number:

import random
digits = int(input("How many digits should the numbers have? "))

list = []
for _ in range(digits):
    list.append(str(random.randint(0,9)))
                
number = int("".join(list))

That said, with a short search on Stack Overflow, there are even cleaner options available.

Upvotes: 0

random.randint includes both bounders, so i think you mean random.randint(0, 9) in your example.

I suggest use math to solve your problem. n-digit number is number between 10**(n-1) and 10**n.

so it will look like this

digigts = int(digits)
num = random.randint(10**(digits - 1), 10**digits - 1)

Upvotes: 2

Related Questions