[014] Introduction to Python Basics: Truthy vs Falsy, Ternary Operator

Koay Yong Cett
3 min readJul 23, 2020
Photo by Drahomír Posteby-Mach on Unsplash

Let’s talk about the idea of truthy and falsey in Python programming and what did they mean. Up till now, we used boolean which is pretty easy and simple. However, Python can do other thing as well. Let’s talk about it.

  • For instance, we changed the value of variable of the is_old and is_licensed. What do you think will happen here?
  • Why is this happening? That is because Python is actually convert the both the ‘hello’ and 5 to boolean for us.
  • What actually the Python doing is something similar to this which is the type conversion. Here we are converting the type of ‘hello’ and 5 to boolean.
  • As soon as we get to the if statement. Python will make sure that both the variable is boolean no matter what.
  • Here, we get true and this is what we call a truthy value in python. That is truthy value because when we run the boolean type conversion on it and it evaluates into true.
  • This is called falsely value and not actually false. However, it is falsy when we run boolean type conversion on both value ‘’ and 0 will appeared as False.
  • For example, a user has enter the username and password. Here, we are not checking whether the username and password is existed or not. We just want to make sure whether the user fill out the form and try to submit an username and password.
  • With the Truethy and Falsy concept, we don’t have to worry about converting it to a boolean. It will perform the boolean type conversion when the if statement is exist. This line of code which is more nicer and neat as both the value of variable get evaluated into truthy and falsy.
  • This feature is done to keep the Python nice and simple which are similar to English.

Ternary Operator:

There is another way to perform conditional logic which is called ternary operator. This is not something new but something that make your code a little bit cleaner. By the way, the these ternary operator can be called conditional expressions. This is an operation that evaluates something based on the condition being true or not.

  • In this example, the ternary operator is performed in one line with the if statement and else statement.
  • The ordering can be a little bit of confusing so you have to look at it couple times to really understand it.
  • This is a shorthand way to do something when a condition is either true or false.

Thanks for reading my stories 😄

--

--

Koay Yong Cett

A Bachelor CS student with major in Network Security (UniSZa). Every stories I shared is based on my personal opinion. Thanks you. Having my Internship now.