Reputation: 332
# this code I don't understand
def cls(): #if statement freaks me out
os.system('cls' if os.name=='nt' else 'clear')
I understand that it works but not WHY it works. After several hours of perusing google, python docs, and stackoverflow, I am none the wiser. I have been unable to find anything explaining that manner of using an IF statement in a function call like this. I have run it under 2.7 and 3.5 so it does not appear to be specific to a particular version. I have seen similar stuff done with for loops sort of get that it might be a standard way of doing things. I kind of like it myself. Just don't understand how it works.
I am confused about how the IF statement is evaluated within system call and I am especially confused about the syntax of the IF statement. I have not seen that syntax in any of the documentation I have read.
Python is completely new to me. So forgive me if this is bonehead simple. But I don't get it.
Upvotes: 3
Views: 98
Reputation: 31885
A if C else B
This first evaluates C; if it is true, A is evaluated to give the result, otherwise, B is evaluated to give the result.
This shortcut conditional expression syntax was added since Python 2.5 Check it here
There's similar syntax in other languages, taking Java for example:
min = (a<b)? a: b
which checks whether a is smaller than b, it returns a if a is smaller, otherwise returns b. BTW, it is call ternary operator in java.
In your case:
'cls' if os.name=='nt' else 'clear'
it checks whether os.name
equals to string nt
, if it is, it returns cls
, otherwise it returns clear
Upvotes: 4
Reputation: 1554
this inline if - else
is the python
version of ternary operator.
in languages like C/C++/Java/JavaScript you would write
a = b > c ? 10 : 20
in python you would write the same as
a = 10 if b > c else 20
you can use the same construct to pass parameters to functions.
in C/C++
foo(b > c ? 10 : 20)
in python
foo(10 if b > c else 20)
Upvotes: 3
Reputation: 17721
The if
expression is not executed inside of the system call. It is executed before the system call. Your code is equivalent to
command = 'cls' if os.name=='nt' else 'clear'
os.system(command)
The if expression itself is only a short form for the if statement
if os.name=='nt':
command = 'cls'
else:
command = 'clear'
os.system(command)
Upvotes: 3
Reputation: 15009
If you are more familiar with C-like languages and their ternary operator, Python's a if b else c
is similar to b ? a : c
. Therefore, the code above says:
if we are on NT/Windows
then use `cls`
else (for Linux, etc) use `clear`
The result is then passed to the os.system()
command to perform the OS-specific operation.
Here is some tutorial information on this subject.
Upvotes: 4