Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction to Wireless and Mobile Systems

Authors: Dharma P. Agrawal, Qing An Zeng

4th edition

1305087135, 978-1305087132, 9781305259621, 1305259629, 9781305537910 , 978-130508713

More Books

Students also viewed these Programming questions