Trivial expression syntax error

Asked 2 years ago, Updated 2 years ago, 280 views

I am currently studying about the expression of the trinomial.

year=2000
val = 'It's leap year' if ((year%40) == 0) and ((year%100)!=0) or ((year%400)==0)
print(val)

If you type the code like this,

SyntaxError: invalid syntax

An error appears.

I was wondering if the grammar of the trinomial expression was wrong

#trinomial expression grammar
true_value if condition else false_value

I wrote it down according to this grammar.

#Write it like a grammar form
year=2000
val = 'It's leap year' if ((year%40) == 0) and ((year%100)!=0) or ((year%400)==0) else pass
print(val)

The error still appears.

SyntaxError: invalid syntax

I deleted everything because I was wondering if the "and" and "or" in the conditional sentence were the problem.

#and, or erase it all
year=2000
val = 'It's leap year' if ((year%40) == 0) else pass
print(val)

The error still appears.

SyntaxError: invalid syntax

I don't know why the trinomial expression doesn't work.

I would appreciate it if you could tell me how to apply the trinomial expression here!

python syntax-error

2022-10-15 01:00

2 Answers

Personally, I don't like this kind of code because it's not intuitive.

To make it easier to see,
a = 1
b = '1'
if a > 0:
    b = '2'
else:
    b = '3'

=>
You have to change it like this.
a = 1
b = '1' if a > 0 else '3'
Why
 error?
The code you wrote is expressed as follows.
a = 1
if a > 2:
    b = '2'
else:
    pass
print(b)
# Error because b value is not determined
Extra
The currently created code appears to be a valid configuration when configured in this way.
import datetime
try:
    datetime.datetime(2021, 2, 29)
    print ('2021 is a leap year')
except:
    pass


2022-10-15 01:00

To explain more intuitively why errors occur in beginner's explanation

year=2000
val = 'It's leap year' if ((year%40) == 0) else pass
print(val)

val = pass when else in code.
The reason for the error is that the val does not contain a normal value.


2022-10-15 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.