Python Forum

Full Version: Help with simple code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a project where I have to provide a code that calculates the largest and smallest of three integer values given. I think that I have the code pretty much written out but for some reason when I run it, the largest output never reads back correctly. I am not sure what is wrong and could use a bit of help...

# LargeSmall.py - This program calculates the largest and smallest of three integer values.

# initialize variables here.
firstNumber = -50;

secondNumber = 53;

thirdNumber = 78;

largest = None
smallest = None

# Write assignment, if, or if else statements here as appropriate.
if firstNumber > secondNumber:
    if firstNumber > thirdNumber:
        largest = firstNumber
elif secondNumber > firstNumber:
    if secondNumber > thirdNumber:
        largest = secondNumber
else:
    largest = thirdNumber

if firstNumber < secondNumber:
    if firstNumber < thirdNumber:
        smallest = firstNumber
elif secondNumber < firstNumber:
    if secondNumber < thirdNumber:
        smallest = secondNumber
else: 
    smallest = thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
There are holes in your logic. For brevity I'm using A, B and C in place of firstValue, secondValue and thirdValue.

These are holes in your logic for largest.
No value is assigned if A > B and C > A
Incorrect value is assigned if A = B and A > C

And these are the holes for smallest.
No value is assigned if A < B and C < A
Incorrect value is assigned if A = B and A < C

I think your approach is wrong. Nested if statements should be avoided. They can be confusing (as you know) and they chew up horizontal spacing rather quickly. I would solve this problem without using else or elif. The resulting program is shorter than yours and easier to understand.

Instead of this:
print("The largest value is " + str(largest))
You should do this:
print("The largest value is", largest)
For performance reasons you should avoid using "+" to concatenate strings. Print works fine for this example. For more complex output you should use format strings (f'strings).
print(f"The largest value is {largest}, the smallest is {smallest}")