Exercise
Ternary Operator, Positive & Lesser
Objective
Develop a Python program that prompts the user for two numbers and uses the conditional operator (?) to determine the following:
If the first number is positive
If the second number is positive
If both are positive
Which one is smaller
Example Python Exercise
Show Python Code
# Ask the user for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Check if the first number is positive
result_num1 = "The first number is positive." if num1 > 0 else "The first number is not positive."
# Check if the second number is positive
result_num2 = "The second number is positive." if num2 > 0 else "The second number is not positive."
# Check if both numbers are positive
result_both = "Both numbers are positive." if num1 > 0 and num2 > 0 else "Both numbers are not positive."
# Determine which number is smaller
smaller = num1 if num1 < num2 else num2
# Print the results
print(result_num1)
print(result_num2)
print(result_both)
print(f"The smaller number is: {smaller}")
Output
Case 1:
Enter the first number: 5
Enter the second number: -3
The first number is positive.
The second number is not positive.
Both numbers are not positive.
The smaller number is: -3.0
Case 2:
Enter the first number: -2
Enter the second number: 8
The first number is not positive.
The second number is positive.
Both numbers are not positive.
The smaller number is: -2.0
Share this Python Exercise
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
This Python program prompts the user to input an integer and determines whether it is a prime number or not. A prime number is defined as a number great...
This Python program calculates the change for a purchase, using the largest possible coins or bills. The program prompts the user for the price o...
This Python program prompts the user for two numbers and performs the division operation. It uses a try..except block to catch potential errors such as ...
In this exercise, you will develop a Python program that prompts the user to input a number and then determines if the number is positive or n...
In this exercise, you will develop a Python program that prompts the user for a number. If the number is not zero, the program will ask for a second ...
In this exercise, you will develop a Python program that prompts the user for two numbers. The program will display their division if the second numb...