0

I have to ask the user how many numbers they want to generate and then i can generate integers according to them in the range of 0 to a 100. If the user wants 5 numbers I have to generate 5 random numbers, but have no clue how.

input("How many numbers should the string consist of? ")  #The user gives a number

for i in range(4):                 # I used a 4 but its going to be the users input
    print(random.randint(0, 100))  #The integers will print

Afterwards I have to calculate the total of all the integers generated, The total is: sum of generated integers.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    It's seems you're just one tiny step away from the answer. You seem to know how to ask the user for input. You seem to know how to loop `x` number of times. You're just missing the link. Save the input to a variable and use that as your `x` – Tomerikoo Jun 16 '20 at 15:27

3 Answers3

0

Change the for i in range loop iteration count to the number of integers the user wants:

num = int(input("How many numbers should the string consist of? "))

for i in range(num):                 
    print(random.randint(0, 100))  #The integers will print

Afterwards I have to calculate the total of all the integers generated, The total is: sum of generated integers.

Add a variable to count all the integers, in this case it is count:

num = int(input("How many numbers should the string consist of? "))  
count=0

for i in range(num):                 
    randomnumber = random.randint(0, 100)
    print(randomnumber)
    count += randomnumber

print(count)
0

Looks like i posted at the same time as Daniil

To add to Daniils answer: You could also do a validation for when the user does not enter an integer it gets promted again.

import random

while True:
    try:
        user_input_str = input("How many numbers should the string consist of?")  #The user gives a number
        num = int(user_input_str)
        break
    except ValueError:
        print(f"{user_input_str} is not an integer, please enter an integer)")

total_sum = 0

for i in range(num):        # I used a 4 but its going to be the users input
    random_int = random.randint(0, 100)
    print(f"#{i} Random int: {random_int}")
    total_sum = total_sum + random_int

print(f"Total sum: {total_sum}")
Gerrit Geeraerts
  • 924
  • 1
  • 7
  • 14
0
from random import randint

def random_generate(count: int):
    for _ in range(count):
        yield randint(0, 100)

for num in random_generate(20):
    print("random number is:", num)
Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34
  • You don't seem to be answering the actual problem OP is asking about. It is evident from the question that he knows how to iterate and print some amount of random integers. He doesn't know how to print the amount given by the user... – Tomerikoo Jun 16 '20 at 15:38