Ask Your Question
0

Boolean conditional function

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

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

Comments

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 +0100 )edit

I am confused to be able to write such inconsistent english

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

2 Answers

Sort by » oldest newest most voted
0

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

tmonteil gravatar image

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

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

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

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é"
    else:
        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

Comments

tmonteil thanks for your reactivity

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

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

a=1
b=2 
c=3 
d=4
e=5
f=6
essay = [[cond(a,b)],[cond(c,d)],[cond(e,f)]]
table(essay,header_row=[r'A',r'B',r'C')

and when it works results are not displayed in the table

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

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

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é"

Then:

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

Stats

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

Seen: 464 times

Last updated: May 06 '20