Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Q on syntax
#1
Hi,

The following 2 codes yield the same results.

What's the difference between them? If the first one is the traditional way of coding, what's the second? I'm puzzled.
TIA

a=1
if(a==1):
	p=8
else:
	p=9
print(p)
a = 1
print(8 if(a==1) else 9)
Reply
#2
https://python-forum.io/Thread-Basic-Ter...xpressions
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
HI THERE
In the first example you have assigned number 1 to letter a, in the condition it is truly equal to 1 and will print 8. change the value of a to another number then it will jump to else condition.

In the second Example:
it is the same value but it will not print else condition, since you didn't have used print.
Reply
#4
@nadim313

actualy it does print if you change the variable a. That's why I said that both codes yeld the same results.

try this...

 
 a = 1
 print(8 if(a==1) else 9) #prints 8
 
 a = 2
 print(8 if(a==1) else 9) #prints 9
Reply
#5
The crux of it is the first is a statement and the second an expression.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020