H
H
Herben2021-09-11 14:56:45
Python
Herben, 2021-09-11 14:56:45

Works not the if which should, what's wrong?

I made a generator in which the user can choose the interval, everything seems to work

import random

a = input("Введите ОТ скольки рандомизировать: ")
b = input("Введите ДО скольки рандомизировать: ")

c = random.randint(int(a), int(b))

print (c)


But if you enter the numbers in a different order, that is, not from 1 to 100, but from 100 to 1, then an error will occur, I made it so that the counting in the opposite direction also works

import random

a = input("Введите ОТ скольки рандомизировать: ")
b = input("Введите ДО скольки рандомизировать: ")

if b > a:
    c = random.randint(int(a), int(b))
else:
    c = random.randint(int(b), int(a))
    print ('Правильный порядок ОТ и ДО, а не ДО и ОТ как сделали вы! Но число всё равно сгенерировано')
print (c)

I enter from 1 to 100, it works, I enter from 100 to 1, it also works, but if you enter for example: from 100 to 7, an error immediately appears with a complaint about "c = random.randint(int(a), int(b ))", that is, to the usual order, although I entered it in reverse, how did the script even count that a = 100 is less than b = 7 ???

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    c = random.randint(int(a), int(b))
  File "/usr/lib/python3.4/random.py", line 218, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.4/random.py", line 196, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (100,8, -92)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-09-11
@Herben

if int(b) > int(a):

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question