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 even=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 even+=1 counter+=1 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.