Back to Python Notes
Topic #73

Shorthand If

Python's one-line if writes a conditional on a single line for simple cases. Compact, but readability should decide when to use it.


Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

a = 5
b = 2
if a > b: print("a is greater than b")

Note: You still need the colon : after the condition.


Short Hand If ... Else

If you have one statement for if and one for else, you can put them on the same line using a conditional expression:

Example

a = 2
b = 330
print("A") if a > b else print("B")

Note: This is called a conditional expression (sometimes known as a "ternary operator").


Assign a Value With If ... Else

You can also use a one-line if/else to choose a value and assign it to a variable:

Example

a = 10
b = 20
bigger = a if a > b else b
print("Bigger is", bigger)

The syntax follows this pattern:

variable = value_if_true if condition else value_if_false

Multiple Conditions on One Line

You can chain conditional expressions, but keep it short so it stays readable:

Example

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

Practical Examples

Ternary operators are particularly useful for simple assignments and return statements.

Example

x = 15
y = 20
max_value = x if x > y else y
print("Maximum value:", max_value)

Example

username = ""
display_name = username if username else "Guest"
print("Welcome,", display_name)

When to Use Shorthand If

Shorthand if statements and ternary operators should be used when:

  • The condition and actions are simple
  • It improves code readability
  • You want to make a quick assignment based on a condition

Note: Important: While shorthand if statements can make code more concise, avoid overusing them for complex conditions. For readability, use regular if-else statements when dealing with multiple lines of code or complex logic.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Shorthand If – FAQs

Quick answers about learning Shorthand If in Python.

This free note from Coding Now Tech Institute explains Shorthand If in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Shorthand If, is 100% free with no signup required.
With focused practice, most students grasp Shorthand If in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now