Python Forum
Please explain me step by step.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please explain me step by step.
#1
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.
Reply
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Last Step of my Project! Getting data from an API with a secret key card51shor 24 6,678 Jun-24-2020, 06:48 AM
Last Post: card51shor

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020