I'm making my way through the Intro to Computation and Programming test by John Guttag and he gives these small exercises to practice gearing up into computational thinking. As of chapter two, we've covered basic input and print commands as well as some simple iteration stuff.

The question is as follows:

Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.

counter = 0
ans = 0
while counter < 10:
    x=int(raw_input('Please enter an integer: '))
    if x%2!=0:          #Checks if the input is odd 
        if ans < x:     #If it is, is the input larger than the held value for 'ans'?
            ans = x     #If yes, replace the value for 'ans' with the input
            counter +=1 #Move the counter up by one, ending at 10
    else:               #If it wasn't odd, add 1 to the even counter and to the integer counter, keeping ans the same
if even == 10:          #if all numbers entered were even, this counter would be 10, and thus would give this response
    print 'All numbers were even'
else:                   #if at least 1 odd number was entered, the even counter would not be 10 and it would print the answer
    print 'the largest odd number entered was ', ans

Is there a more efficient way of writing this out? I wonder if I can word my if statements to include more parameters to cut down on the number of ifs and elses? Also keep in mind this text uses python 2.7 and that I'm not super far into the book. I'm mainly trying to get the whole computational thinking thing down.

  • \$\begingroup\$ I have edited your tags. I'm not sure you really wanted to put machine-learning there because your question isn't related to it. If you feel like this edit wasn't good you can rollback it. Otherwise I think this is a great first question, congratulations and welcome to Code Review :) \$\endgroup\$ – IEatBagels May 29 at 16:31
  • \$\begingroup\$ Thank you! I appreciate you looking out. \$\endgroup\$ – TheBestDakota May 29 at 16:51
  • 1
    \$\begingroup\$ If you're just starting to learn Python now, I suggest learning Python 3. Python 2 is obsolete. \$\endgroup\$ – 200_success May 30 at 4:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.