简体   繁体   中英

Creating a function with a condition in Python

I need to create a function named 'Bernoulli' that should take 2 input variables 'rr' and 'p' and should return a value of 1 if rr is less than or equal to p and a value of 0 if rr is greater than p.

The code I have produced so far is this:

rr=float(input())
p=float(input())
def bernoulli(rr,p):
  if rr<=p:
    return 'X=1'
  else:
    return 'X=0'

I am not sure how correct this is.

Upon running tests I get this feedback: Your program took too long to execute. Make sure that it isn't waiting for input and that there is no infinite loop.

rr=float(input())
p=float(input())
def bernoulli(rr,p):
    if rr<=p:
        return 1
    else:
        return 0

x = bernoulli(rr,p)
print(x)

However, if you are simply checking if one number is bigger than the other, it might make more sense down the line to use True and False because comparing them will be a shorter line of code later on. if x == False That being in the logical sense that we understand true to be positive and false to be negative. You might forget which way round the 1 and the 0 are ordered :)

Swift answered this in the same way I would approach this. The reason your code is not executing, is because it is never used. You must call a function to use it.

Here is how I did it:

rr=float(input())
p=float(input())
def bernoulli(rr,p):
  if rr<=p:
    return 'X=1'
  else:
    return 'X=0'

function_response = bernoulli(rr,p)

print(function_response)

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