So, I wanted to post my solution to Finger Exercise 2.4 on pg. 20. This problem was a little bit harder than the first, but I was able to use some knowledge from Codecademy's online Python course, as well as some info accumulated from Stack Exchange.
Finger exercise: Write a program 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.
My Solution:
""" Write a program 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. """
# Ask user for input
raw_user_input = raw_input("Please enter ten integers with spaces between them: ")
# Create a list of integers called 'answers' (split based on spaces)
answers = raw_user_input.split(' ')
# create an array for the odd numbers
odd_numbers = []
# Iterate through each item in 'answers' array
for i in answers:
# convert type str to type int
i = int(i)
# find out if i is an odd number using modulo
if i % 2 != 0:
# append odd numbers to their array
odd_numbers.append(i)
if len(odd_numbers) == 0:
print "There are no odd numbers in this list."
else:
# print max odd number
print "The largest odd number in this list is", max(odd_numbers)
The hardest part of this problem for me was figuring out how to use the "for" statement. I looked back in Codecademy's course, and I thought that this made the most sense.
I also added the knowledge about arrays, or lists, in Python, putting all of my odd numbers into a list before selecting the max.
I found the .split(' ') method on Stack Exchange, and read some documentation on it in order to allow the user to enter 10 separate numbers at once.
And I also found the max() method on Stack Exchange, read up on it, and decided it was the best option for finding the maximum odd number.
No comments:
Post a Comment