- Ternary operator also called conditional operator.
- Syntax ⇒ x = firstValue if condition else secondValue
- If condition is True then firstValue will be considered else secondValue will be considered.
Example
Python
num1, num2 = 10, 20
num3 = 30 if num1<num2 else 40
print(num3)
Output
PowerShell
30
Question
Read two numbers from the keyboard and print minimum value
Python
num1 = int(input("Enter First Number:"))
num2 = int(input("Enter Second Number:"))
min = num1 if num1<num2 else num2
print("Minimum Value:",min)
Output
PowerShell
Enter First Number:12
Enter Second Number:17
Minimum Value: 12
Remark
- Nesting of ternary operator is possible.
- Program for minimum of 3 numbers?
Python
num1 = int(input("Enter First Number:"))
num2 = int(input("Enter Second Number:"))
num3 = int(input("Enter Third Number:"))
min = num1 if num1<num2 and num1<num3 else num2 if num2<num3 else num3
print("Minimum Value:", min)
Output
PowerShell
Enter First Number:12
Enter Second Number:17
Enter Third Number:16
Minimum Value: 12
- Program for maximum of 3 numbers?
Python
num1 = int(input("Enter First Number:"))
num2 = int(input("Enter Second Number:"))
num3 = int(input("Enter Third Number:"))
max = num1 if num1>num2 and num1>num3 else num2 if num2>num3 else num3
print("Maximum Value:", max)
Output
PowerShell
Enter First Number:12
Enter Second Number:17
Enter Third Number:16
Maximum Value: 17
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!