Question
If statements vs else if statements. I am confused why the statement order gives different outputs. For example) * In my first problem (below) I
If statements vs else if statements.
I am confused why the statement order gives different outputs.
For example)
* In my first problem (below) I have all if statements. The program gets the right answer, but also includes the else statement, \"That is not a valid operator, try again,\" which it should not be doing.
* In my second problem (below) I have a mix of If and Else If statements. The program gets the right answer and does not include the else statement, \"That is not a valid operator, try again,\" which is correct!
* Why does the order of return statements matter, don't if and else if statements do the same thing? I am confused why the problem works correctly in the 2nd example vs the first example.
1) num1 = float(input(\"Enter first number: \"))
operator = input(\"Enter the operator (+, -, *, or /): \")
num2 = float(input(\"Enter second number: \"))
if operator == \"+\":
print(num1 + num2)
if operator == \"-\":
print(num1 - num2)
if operator == \"*\":
print(num1 * num2)
if operator == \"/\":
print(num1 / num2)
else:
print(\"That is not a valid operator. Try again.\")
Output: Enter first number: 9 Enter the operator (+, -, *, or /): + Enter second number: 9 18.0 That is not a valid operator. Try again.
2) num1 = float(input(\"Enter first number: \"))
operator = input(\"Enter the operator (+, -, *, or /): \")
num2 = float(input(\"Enter second number: \"))
if operator == \"+\":
print(num1 + num2)
elif operator == \"-\":
print(num1 - num2)
elif operator == \"*\":
print(num1 * num2)
elif operator == \"/\":
print(num1 / num2)
else:
print(\"That is not a valid operator. Try again.\")
Output:
Enter first number: 9 Enter the operator (+, -, *, or /): + Enter second number: 9 18.0
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started