Python Forum
Please explain me step by step. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Please explain me step by step. (/thread-4146.html)



Please explain me step by step. - ITMani - Jul-26-2017

temp = [23,45,2,-2,0]

def f(b):
    n1 , n2 = b[0],b[0]
    for m in b:
        if (m >n1):
             n1 = m
        if (m < n2):
            n2 = m
    return n1, n2
print (f(temp))
I have several questions.
1. How can we say data type of f is tuple?
2. What is b? I assume it a sequence , if then what are the elements of this sequence?
3. What does the line 3 does?
4. What is the output?
5. I am a complete beginner and would appriciate any one who explains all the lines in detail.


RE: Please explain me step by step. - DeaD_EyE - Jul-26-2017

1. Data type of f is function type(f)
2. b can be everything. In your call b is temp and temp is a list. Python is a dynamic language.
3. A function definition
4. ASCII characters on your screen
5. I won't. I looks like a max, min output. The variable names are bad, I think the guy wanted to show the concept of finding a maximum and minimum value. But as an explanation it's a bad example.


def max_min(sequence):
    v_max = v_min = sequence[0]
    # get the first element of the sequence and assign it to the name v_max and v_min
    for value in sequence:
        # iterating over the sequence
        if (value > v_max):
            v_max = value
        if (value < v_min):
            v_min = value
    return v_max, v_min
We use Python because it's easy. Don't reinvent the wheel. If you want to get the max and min values from a list, just use the built-in functions.

temp_max = max(temp)
temp_min = min(temp)
You can also write it in one line:
temp_max, temp_min = max(temp), min(temp) 
Or if you want as a function:
def max_min(sequence):
    return max(sequence), min(sequence)
The first example of min_max has one benefit. This function has to iterate only one time over the list to get the smallest and highest value.
The type list has also a sort function. In this case you can do an inline sort and get the first element (min-value) and the last element (max-value) out of the list.

temp.sort()
temp_min, temp_max = temp[0], temp[-1]
Negative indices's means start from the right side of the list. -1 is the last eleemt, 0 is the first element.
You should start with the basics. You don't know very much at the moment. What you should learn are the built-in functions, data types, slicing, loops and functions.