I got some advice about the article I wrote last time (Let's find the maximum value python (correction ver)), so I tried to refactor it further. This time, I modified the code with an emphasis on readability.
-How to set variables during loop processing of for statement
The code is below.
num = int(input("How many pieces do you want to substitute?"))
value_list = [] #Prepare an array to store numbers
for i in range(num):
value = int(input("Substitute a number"))
value_list.append(value) #Add values to the prepared list
max_value = value_list[0] #Initialize with list elements
for value in value_list:
if value > max_value:
max_value = value
print(max_value) #Output maximum value
Change before
for i in range(num):
if value_list[i] > max_value:
max_value = value_list[i]
After change
for value in value_list:
if value > max_value:
max_value = value
This code is simpler and easier to understand. The more articles you write, the more discoveries you will make and it will be a great learning experience.
Recommended Posts