Ask Your Question

Boolean conditional function

asked 2020-05-05 15:24:00 +0200

Cyrille gravatar image

I would like to construct a function with return the string "Vrai" or the string 'Faux' selon qu $x>y$ ou $x<=y$. I have tried

cond(x, y)= if bool(x<y)='True' then Print("Accepté") else Print("Rejeté")

but it leads to an error

edit retag flag offensive close merge delete


Could you please edit the question to make it more consistent:

  • decide between Vrai/Faux vs Accepté/Rejeté
  • "a function with" -> "a function which"
  • selon que ... ou ... -> according to whether ... or ...
  • decide whether it's "x > y" or "x < y" that should be "accepted"
slelievre gravatar imageslelievre ( 2020-05-06 01:09:52 +0200 )edit

I am confused to be able to write such inconsistent english

Cyrille gravatar imageCyrille ( 2020-05-06 04:38:41 +0200 )edit

2 Answers

Sort by » oldest newest most voted

answered 2020-05-05 16:04:44 +0200

tmonteil gravatar image

updated 2020-05-05 16:37:14 +0200

To construct a function, you have to use def Python statement.

def cond(x, y):
    if x<y:

EDIT given the comment, it seems that you do not want to only print the result, but you want the function to return the string. So, here it is:

def cond(x, y):
    if x<y:
        return "Accepté"
        return "Rejeté"

All this is pure Python. Let me suggest to read some introductions about this generic language, since Sage is based on it, and you will benefit a lot to make clever constructions out of Sage mathematical bricks.

edit flag offensive delete link more


tmonteil thanks for your reactivity

Cyrille gravatar imageCyrille ( 2020-05-05 16:14:38 +0200 )edit

A subsequent consequence of your formula. I have an error with the following code

essay = [[cond(a,b)],[cond(c,d)],[cond(e,f)]]

and when it works results are not displayed in the table

Cyrille gravatar imageCyrille ( 2020-05-05 16:29:14 +0200 )edit

answered 2020-05-06 01:05:23 +0200

slelievre gravatar image

To complement @tmonteil's answer.

In some cases a lambda function is also okay.

It takes up less lines than a def function.

sage: cond = lambda x, y: "Accepté" if bool(x<y) else "Rejeté"


sage: a, b, c, d, e, f = [1 .. 6]
sage: essay = [[cond(a, b)], [cond(c, d)], [cond(e, f)]]
sage: hc = ['test', r'A', r'B', r'C']
sage: table(essay, header_row=['résultat'], header_column=hc)
  test | résultat
  A    | Accepté
  B    | Accepté
  C    | Accepté
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-05-05 15:24:00 +0200

Seen: 74 times

Last updated: May 06 '20