I tried searching this up before asking it here, but from what I have searched it does not seem to be asked in the form that I am thinking.
For a simple example, imagine a situation where I have a list of integers [1, 2, 3, 4, 5] and I want to iterate through the list and save the largest number that is divisible by 2. (And yes, if the list was not ordered this code wouldn't work, but for the sake of example imagine all the lists are in numbered order)
nums = [1, 2, 3, 4, 5]
for number in nums:
if number % 2 == 0:
max_num = number
print(str(max_num))
In this example, I would be able to print max_num without issue. However, if the list nums was [1, 3, 5] for example, max_num would never be set, and I would be referencing a variable I never instantiated.
My question is how would I properly set the variable prior to the loop? To state it otherwise, would you ever need to describe the data type of a variable prior to setting it, akin to Java and C++? Is it even necessary?
What I have been doing recently is something like this:
nums = [1, 2, 3, 4, 5]
max_num = None # <- added this
for number in nums:
if number % 2 == 0:
max_num = number
if max_num is not None: # <- added if statement
print(str(max_num))
But I feel like there would be a better way of doing it. I also had the idea to try this:
nums = [1, 2, 3, 4, 5]
max_num = int # <- this was changed
for number in nums:
if number % 2 == 0:
max_num = number
print(str(max_num))
The issue with this way it it makes max_num type(int), which I don't believe is correct either.
Any feedback would be greatly appreciated.
EDIT: I am not specifically looking for a solution to the example I have, but instead a pythonic way of setting a variable.
Your first example exactly does what you need. It does assign a default value None
to max_num
.
You don't need to specifically check if max_num
is not None
. If at all the list contains any value that is divisible by 2, it will be assigned to max_num
. If not, max_num
will be None
( the default value) which means - No number divisible by 2 exists in the list.
nums = [1, 3, 5]
max_num = None # <- added this
for number in nums:
if number % 2 == 0:
max_num = number
print(max_num)
The above code, if
nums = [1, 3, 4, 5] - Returns 4 -> Max. number divisible by 2 exists
nums = [1,3,5] - Returns None -> No number divisible by 2 exists.