Python Forum
I am a newbie.Help me with this simple piece of code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I am a newbie.Help me with this simple piece of code (/thread-23606.html)



I am a newbie.Help me with this simple piece of code - feynarun - Jan-08-2020

I was watching this complete Python Tutorial by Mosh Hamadani on youtube.
I saw a small piece of code that he wrote and I wrote it in pycharm.
I got an output that was different from what he got.
This is a program to find the largest number.

This is the piece of code.

numbers = [11, 2, 23, 45, 67, 99, 101]
largest_num = numbers[0]
for number in numbers:
    if number > largest_num:
        largest_num = number
        print(largest_num)
The result was
Output:
23 45 67 99 101
But, The intended result was 101, the largest number.
Where did I go wrong?


RE: I am a newbie.Help me with this simple piece of code - buran - Jan-08-2020

you want line#6 out of the loop body (i.e. unindent it 2 levels).


RE: I am a newbie.Help me with this simple piece of code - feynarun - Jan-08-2020

(Jan-08-2020, 09:31 AM)buran Wrote: you want line#6 out of the loop body (i.e. unindent it 2 levels).

Thank you.


RE: I am a newbie.Help me with this simple piece of code - perfringo - Jan-08-2020

Maybe following can enhance learning process.

In programming same results can be achieved in different ways.

For example we don't need to compare all list items if we have assigned first value as max value. We can start from second item:

numbers = [11, 2, 23, 45, 67, 99, 101] 
largest_num = numbers[0]
for number in numbers[1:]: 
    if largest_num < number: 
        largest_num = number

# largest_num is 101
We can make an iterator from numbers and assign first item in list with next() as largest_num and then iterate over remaining items:

numbers = [11, 2, 23, 45, 67, 99, 101]
nums = iter(numbers)
largest_num = next(nums)
for num in nums: 
    if largest_num < num: 
        largest_num = num 
# largest_num is 101
After mastering finding largest number from list with own algorithm one can start using built-in max() (no need to invent wheel):

>>> numbers = [11, 2, 23, 45, 67, 99, 101]
>>> max(numbers)
101