I'm working my way through the MIT Open Courseware class Introduction to Computer Science and Programming in Python and I've spent an embarrassing amount of time trying to wrap my head around the "Finger Exercise" from the textbook:
Write a program that examines three variables—x, y, and z—and prints the largest odd number among them. If none of them are odd, it should print a message to that effect.
I wrote a couple of solutions that didn't quite work, missing odd numbers if there were larger even numbers. I finally threw in the towel and searched here for solutions that others people working on this class had asked. This solution from AFDev seemed to be the simplest to me (in the context of what the intent of the exercise was and how concise the solution was.) I combined that with my user input to get the following:
x=int(input('Enter your first number:'))
y=int(input('Enter your second number:'))
z=int(input('Enter your third number:'))
largest = None
if x%2:
largest = x
if y%2:
if y > largest:
largest = y
if z%2:
if z > largest:
largest = z
if largest:
print ('The largest odd number is', largest)
else:
print ('There are no odd numbers.')
This works great, as long as x is an odd number. If x is zero or an even number, I get the following error:
TypeError: '>' not supported between instances of 'int' and 'NoneType'
The little bit of Googling I did said that Python 2 was a little more liberal in allowing comparisons between NoneType and integers. I changed the line to initialize largest = 0, but then realized that this would give invalid results if the user input a negative number.
I tweaked the code to the following:
x=int(input('Enter your first number:'))
y=int(input('Enter your second number:'))
z=int(input('Enter your third number:'))
largest = None
if x%2:
largest = x
if y%2:
if largest == None:
largest = y
if y > largest:
largest = y
if z%2:
if largest == None:
largest = z
if z > largest:
largest = z
if largest:
print ('The largest odd number is', largest)
else:
print ('There are no odd numbers.')
Is there a better way to initialize (for lack of a better term) "largest" so that I can compare it to an integer or is the way I'm doing it good enough?
I understand that there are better ways to compare the numbers to find the largest (I found max when googling). I'm trying to baby-step my way through this stuff.
None seems fine if you're going to do it this way. (I'd say it's safer than using a large negative number.) You can get round the code duplication with None as e.g.
if largest is None or y > largest:
largest = y
Couple of things, compare to None with is. Second, if the first part of an or is True, the second part won't be executed (called short-circuiting), so you won't get an error trying to compare a None using >.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With