On 22 November 2012 12:55, Peter O'Doherty <m...@peterodoherty.net> wrote: > Hi list, > Firstly, apologies for the low-level nature of this question - it's really > quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and prints the > largest odd number. I've tried all sorts of variations and this is the > current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > > > A solution should be possible using only the simple operators and keywords > above, no functions, lists or any other form of iteration. (It's from p. 16 > of Introduction to Computation and Programming Using Python, and no, it's > not "homework"!)
x, y, z = 13, 14, 15 largest_odd = None if x % 2: largest_odd = x if y % 2 and y > largest_odd: largest_odd = y if z % 2 and z > largest_odd: largest_odd = z if largest_odd is None: print('No odd numbers!') else: print('Largest odd number is %i' % largest_odd) The code above is just an explicit expansion of what happens if you solve this problem the normal way (using iteration): # ValueError when there are no odd numbers largest_odd = max(v for v in (x, y, z) if v % 2) Oscar _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor