Now we are going to find the largest number in a list using a while loop in Python:
Simple code:
my_list = [3, 12, 8, 19, 1, 8, 10]
largest_num = my_list[0]
i = 1
while i < len(my_list):
if my_list[i] > largest_num:
largest_num = my_list[i]
i += 1
print("The largest number in the list is:", largest_num)
Output:
The largest number in the list is: 19
Code with comments:
# initialize the list of numbers
my_list = [3, 12, 8, 19, 1, 8, 10]
# initialize the largest_num variable to the first element of the list
largest_num = my_list[0]
# initialize the counter i to 1
i = 1
# continue looping until i reaches the end of the list
while i < len(my_list):
# check if the current element is greater than the largest_num variable
if my_list[i] > largest_num:
# update the largest_num variable to the current element
largest_num = my_list[i]
# increment the counter i by 1
i += 1
# print the largest number in the list
print("The largest number in the list is:", largest_num)
In the above code, we first initialize the list of numbers my_list and the largest_num variable to the first element of the list. We also initialize the counter i to 1.
We use a while loop to iterate through the list and check if the current element is greater than the largest_num variable. If it is, we update the largest_num variable to the current element.
We then increment the counter i by 1 and continue looping until i reach the end of the list.
Finally, we print the largest number in the list using the print() function.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.