Home > database >  count down from random number from 1-1000
count down from random number from 1-1000

Time:11-03

I need to get a random number from 1 - 1000. if the number is higher than 500 it counts up to 1000 from the random number. if the number is below 500 it counts down from the random number to 0. can someone help me do that?

if keyrsla2 == 3:
    daemi3_tala = random.randrange(1, 1000)
    if daemi3_tala <= 500:
        for count in range(daemi3_tala,500, -1):
            print(count)
    if daemi3_tala >= 500:  
        for count in range(daemi3_tala,500,  1):
            print(count)

CodePudding user response:

for count in range(daemi3_tala,500,  1):

Here you need to change it to

for count in range(daemi3_tala,1000):

What do we do here is make the count start from daemi3_tala which is the random number to 1000 which is the upper limit that you have decided.

CodePudding user response:

Here is a recursive solution that may be easy to follow.

Each number will be either be less than 500 or more than 500. If it's less than 500, we'll keep taking off one number until we reach 0. If it's above 500, we'll keep adding a number until we reach 1000.

from random import randint


num = randint(0, 1001) # Produce a random integer between 0 and 1001

def count(num):
    if num == 0 or num == 1000:
        return  #  Exit condition
    elif num < 500:
        print(num)
        count(num - 1)  # Call the recursive function with one less than the current number (count down by one number)
    elif num >= 500:
        print(num)
        count(num   1)  # Call the recursive function with one more than the current number (count up by one number)

 count(num)  # Call the function with the random number
  • Related