简体   繁体   中英

Select a number randomly and then select a higher number randomly python code?

I am trying to build a psychological experiment for my PhD thesis. I am pretty new to python. What I am looking for is that I need to select a number from a list of numbers and then again select a number which should in one case higher than the previous one and in another case lower than the previous one.

The main list of pool of numbers is:

digit = range(0,30)
if cong = 'yes':
## select a number for a variable d1 from digit and
## select another number for a variable d2 from digit which is higher than  
## d1
else:
## select a number for a variable d1 from digit and
## select another number for variable d2 which is lower than d1

I have tried solving this but I guess not that expert right now. Would be grateful if anyone could help me solve this.

PS: This is my first question so I am now much aware about the standard practice of forum participation.

Thanks Vatsal

LO, HI = 0, 30
d1 = random.randint(LO + 1, HI - 1) # Select a number between 0 and 30, exclusive
if cong == 'yes':
    d2 = random.randint(d1 + 1, HI) # Select a bigger number
else:    
    d2 = random.randint(LO, d1 - 1) # Select a smaller number

randint() and randrange() should do the job:

import random

num_range = a, b  #Specify the initial range here. (0, 30) for you.
num_0 = random.randrange(a+1, b)  #Boundaries aren't included.
if cong == "yes":
    num_1 = random.randint(num_0+1, b)  #Select a larger number.
else:
    num_1 = random.randint(a, num_0-1)  #Select a smaller number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM