Generate 2 random numbers in a loop that have a range of -5 and 5 and have to be displayed from smallest to biggest

364 Views Asked by At

My given instructions: Write a program that continually generates 2 numbers between -5 and 5. After each number is generated, display each pair from smallest to biggest along with the sum of the pair. The program stops when the program generates a pair that is the negative of the other (for example, -5 and 5 or -2 and 2) At the end of the program display the sum of all the numbers that were generated.

Here's my code: My problem is I don't know how to display each pair from smallest to biggest along with the sum of the pair. I also am not sure about displaying the sum of all the numbers that were generated.

`

import random
i = 0
while i < 1:
    number1= random.randint(-5,5)
    number2= random.randint(-5,5)
    print("(", number1, ",", number2, ")")
    
    if number1 == -number2:
        break

        if number2 == -number1:
            break

`

2

There are 2 best solutions below

0
Dariush Mazlumi On

I think my code below is self-explanatory. yet if you had any doubts or questions, I'm happy to explain

# random is a python built-in library which has multiple functions regarding random events
import random

total_sum = 0

# a while loop with a final break statement is the closest idiomatic way for a do-while AFAIK 
while True:
    # the randint functions takes two numbers, and generates a random integer in the given range (inclusive)
    a, b = random.randint(-5, 5), random.randint(-5, 5)

    # I'd like to have A as the smaller one. therefore, if this is not the case, we can simply swap them
    if a > b:
        a, b = b, a

    print("generated pair:", a, b)
    print("sum:", a + b)

    total_sum += a+b

    if a == -b:
        break

print("total sum:", total_sum)
0
Richard Neumann On

You can use the fact, that both numbers are the negation of each other exactly if their sum is zero (yes, I also count 0 / 0, since -0 == 0):

from random import randint


def main() -> None:

    total = 0

    while True:
        numbers = [randint(-5, 5), randint(-5, 5)]
        total += (s := sum(numbers))
        print('Numbers:', *sorted(numbers), '/ Sum:', s)

        if s == 0:
            break

    print('Total sum:', total)


if __name__ == '__main__':
    main()