Home > database >  How to return and print variable only when 'elif' was triggered - Python
How to return and print variable only when 'elif' was triggered - Python

Time:02-20

If I run this, it always prints "above 0.5" after 'elif' condition was met once. I want it only to return and print "above 0.5" only if 'elif' was currently triggered and run. Any suggestions?

def func(x):  
global return_value
    if x < 0.5: 
        pass
    elif x > 0.5: 
        return_value = "above 0.5"
return(return_value)

while True:        
    y = random.uniform(0, 1)
    text = func(y)
    print(text)

CodePudding user response:

I would write the code in this way, there is no need of that local variable within the function func

Also your while loop is eternal - there is break condition.

def func(x):    
    if x > 0.5: 
        return "above 0.5"
    else:
        return None

while True:  
    if (#some breaking condition#):
        break      
    y = random.uniform(0, 1)
    text = func(y)
    if text:
        print(text)


CodePudding user response:

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

So your codes meet your requirment: print "above 0.5" only if 'elif' was currently triggered

If you want different outputs for different inputs, use:

import time
import random

def func(x):    
    return_value = "below 0.5"
    if x < 0.5: 
        pass
    elif x > 0.5: 
        return_value = "above 0.5"
    return(return_value)

 
while True:        
    y = random.uniform(0, 1)
    text = func(y)
    print(text)
  • Related