To create a list of numbers given by user we use a for-loop with input
to ask for numbers as you almost did correctly (do not forget to cast to int
):
numbers = []
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
numbers.append(number)
You can also do this with list comprehension, which will make it shorter but maybe a little harder to understand at the begining (this has exactly the same result as the previous code):
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
Now, to get the largest odd number from a list of numbers you can:
- Set a variable with the minimum possible value or to
None
- Iterate over your list
- Update the value of the variable, if a number is an odd number and larger than the one saved in your variable
Let's see this in action considering you have your list of numbers numbers
.
odd_largest = 0
for number in numbers:
if number % 2 != 0 and number > odd_largest: # If number is odd and larger
odd_largest = number # update value
print(odd_largest)
What is the difference of setting odd_largest
to 0
vs None
? If you set it to 0
and the final value of odd_largest
is 0, you wouldn't know if it was updated at all, is it a number in the list or just the original value? Imagine the case there is no odd number in the list, for example.
When using None
as initial value you will be sure if it was updated. You also need to add an additional condition:
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
When you put everything together you get what is needed.
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
Here some questions arise. First: are we using the list numbers
for any other actions? If the answer is yes, then our code is enough. But if this is all that is needed we can actually do better.
Find the largest odd number by comparing the numbers right after input by the user, without even creating a list. Let's check it out!
odd_largest = None
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
if number % 2 != 0 and (odd_largest is None or number > odd_largest):
odd_largest = number
print(odd_largest)
What do we gain with this? Iterating just once over the numbers instead of twice, saving memory since we are not saving all numbers input just one. Cool uh?
If you have any more questions do not hesitate. Happy coding!