Python’s if-else statement is logical. Python does not use the ternary operator as other languages do for inline if statements. It instead provides a one-line code to evaluate the first expression if the condition is met. Otherwise, the second expression is evaluated.
Program To Write Inline If Statement in Python
inline if statement in Python:
In Python, the inline if-else expression contains two statements and executes one of them based on the condition’s evaluation. In Python, there are two kinds of if statements.
- Simple if statement
- if-else expression statement
In a simple, if statement, we write a condition, and the if block is executed based on that condition.
Syntax:
if condition: statement
if condition:
block
Let us write an inline if statement that will execute the expression if the condition is True.
Examples:
Example1:
numb = 12 if numb > 10: print("hello btechgeeks")
Output:
hello btechgeeks
Explanation:
Here the given number 12 is greater than 10. So, it prints the given statement "hello btechgeeks".
Example2:
numb = 32 if numb % 2 == 0 : print("The Given number is Even")
Output:
The Given number is Even
Explanation:
Here the given number 32 is Even. So, it prints the given statement "The Given number is Even".
inline if-else statement in python:
Python’s inline if-else expression must include an else clause.
Examples:
Example1:
numb = 10 temp = 3 print(numb if temp else 0)
Output:
10
Explanation:
Here it prints the given number value because the given if condition is True ( temp is not equal to 0 so, it returns True)
Example2:
numb = 15 temp = 0 print(numb if temp else 0)
Output:
0
Explanation:
Here it prints 0 because the given if condition is False (given temp is 0) suppose the temp given is any other number other than 0, then it prints the given number
User Input:
Example1:
numb = int(input("Enter some random number = ")) temp = 3 print(numb if temp else 0)
Output:
Enter some random number = 10 10
Example 2:
numb = int(input("Enter some random number = ")) print("Even" if numb%2==0 else "Odd")
Output:
Enter some random number = 13 Odd
Example 3:
gvn_str = input("Enter some random String = ") print("True" if gvn_str=="hello btechgeeks" else "False")
Output:
Enter some random String = hello btechgeeks True
Example 4:
gvn_str = input("Enter some random String = ") print("True" if gvn_str=="hello btechgeeks" else "False")
Output:
Enter some random String = hello world False