Coding Lesson (13-17 January)

Monday

I learned about Getting Help in Kaggle. The help() function is incredibly useful. It gives you detailed information about how to use a function and what it does. For example:
help(print) shows you that print() can take several optional arguments like sep (which controls what gets printed between multiple values) and end (which controls what gets printed at the end of the line).
Also, there's a COMMON MISTAKES TO AVOID: Make sure you pass the function name itself to help(), not the result of calling the function.

Tuesday

I continue learning about Getting Help—defining functions—in Kaggle. Here's a simple function example:
def say_hello():
    print("Hello.")
def is the keyword that tells Python you are defining a function and say_hello is the name of the function. So, when you call say_hello it will print "Hello.". But, how about functions that take inputs? Here's the example:
def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3) #returns the smallest difference
    print(
        least_difference = (1, 10, 100)
        least_difference = (1, 100, 100)
        least_difference = (5, 6, 7)
Output: 9 0 1
You can also explain function with DOCSTRINGS. Docstrings are like notes you leave inside your code to help others understand what your function does. They appear right after the function header inside triple quotes. Usually, Python will automatically display docstrings when you use help() function. Here's the example of docstrings:
def least_difference(a, b, c):
    """Return the smallest difference between any two numbers among a, b, and c    
    Example:    
    >>> least_difference(1, 5, -5)
    4"""

    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3) #returns the smallest difference

Wednesday

I learned about functions that don't return in Kaggle. Functions that don't return a value are often referred to as "void functions" in programming. The term "void" signifies that the function does not produce a value or result that can be used after the function is called. For example:
def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    min(diff1, diff2, diff3)
    
print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7),
)
Output: None None None
Without a return statement, least_difference is completely pointless.

Thursday

Default Arguments

In Python, default arguments are values that a function takes as parameters if no arguments are provided by the user when the function is called. They are specified when the function is defined. For example:
def greet(name, message="Hello"): 
    print(message, name) 
    greet("Alice") 
    greet("Bob", "Hi") 
 Output: Hello Alice
              Hi Bob
In this example, greet function has two parameters which is name and message. "Hello" is the default value of message parameter. If no value provided for message when the function is called, it uses the default value.

Functions Applied to Functions

Functions that operate on other functions are called "higher-order functions." You can supply functions as arguments to other functions. Here's the example:
def apply_function(func, value):
    return func(value)
def square(x):
    return x * x
result = apply_function(square, 5)
print(result)  
Output: 25
Here, "apply_function" takes "square" and a value = 5. It then applies to "square" to 5, resulting in 25(5 * 5). But there are higher-order functions built into Python that you might find useful to call. For example, the "max" function. By default, "max" returns the largest of its arguments. But if we pass in a function using the optional "key" argument, it returns the argument "x" that maximizes key(x) (aka the 'argmax'). 
def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5

print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n', # \n is the newline character - it starts a new line
)
Output: 100 (the biggest number)
             14 (because the left over is 4)

Comparison Operations

Python has a type of variable called bool. It has two possible values: True and False. But, rather than putting True or False directly in our code, we will use boolean values from boolean operators. Here's the table and the example:
OperationDescriptionOperationDescription
a == ba equal to ba != ba not equal to b
a < ba less than ba > ba greater than b
a <= ba less than or equal to ba >= ba greater than or equal to b
def president_minimum(age):
    return age >= 40
print("Can a 36-year-old run for president?", president_minimum(36))
print("Can a 72-year-old run for president?", president_minimum(72))
Output: Can a 36-year-old run for president? False
             Can a 72-year-old run for president? True
Comparison operators can be combined with the arithmetic operators we've already seen to express a virtually limitless range of mathematical tests. For example:
def is_odd(n):
    return (n % 2) == 1

print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
Is 100 odd? False (the remainder is 0)
Is -1 odd? True (the remainder is 1)

Comparison Booleans Values

You can combine values by using and, or, not. With these we can make the president_minimum function more accurate.
def president_minimum(age, is_natural_born_citizen):
    return is_natural_born_citizen and (age >= 40)
print(president_minimum(36, True))
print(president_minimum(55, True))
print(president_minimum(72, True))
Output:
False
True
True
Here we already tried using and. How about or and not? Here's another example:
One day, I want to go to school. However, I need to check the weather. If it's shiny then go to school, if it's rainy I don't go to school and maybe... if it's raining a bit, i'll use umbrella or a jacket.
prepare_for_weather  = (
    have_umbrella
    or ((rain_level <= 5) and have_jacket)
    or (not(rain_level > 0 and go_to_school)

Friday

Boolean Conversion

In Python, the bool function is used to convert other values to boolean values (True or False). Here's the gist: For numbers, all numbers are considered true, except 0 which is false, and for strings, all strings are true, except the empty string (""). You can use non-boolean objects (like numbers and strings) directly in conditions, and Python will treat them as their corresponding boolean values. Here's the example:
if 0:
    print(0)
elif "spam":
    print("spam")
Here, the number 0 is false, so the if block is skipped. But the "spam" string is true, so the elif block is executed and "spam" is printed. As simple as that.

Indexing

In Python, you can access each item in the lists by using its position or "index". Think of a list like a row of numbered lockers, where each locker holds something valuable (in this case, the owner's name of each locker). Python uses what's called zero-based indexing which means the first item in the list has an index of 0. But, how about the last item? Well, Python uses negative indexing means -1 refers to the last item. Here's an example:
lockers = ['Emily', 'John', 'Adam', 'Alicia', 'Eve', 'Zack', 'Lkhagvasüren']

# Which lockers is closest to the class?
print(lockers[0])
# Which lockers is furthest to the class?
print(lockers[-1])

Emily
Lkhagvasüren

Slicing

Slicing almost has the same function with Indexing. What makes it different is you can ask the function to give you the list from the starting and ending indices that you want. For example:
lockers[0:3] # Output: 'Emily', 'John', 'Adam'
As you can see, the starting index is from 0 and continuing up but not including index 3. Also, if you leave out the start index (for example: lockers[:3]), It's assumed to be 0. And if you leave out the end index, it's assumed to be the length of the list.
We can also use the negative indexing like what we do before. Here's an example:
# All the lockers except the first and last
lockers[1:-1] # Output: 'John', 'Adam', 'Alicia', 'Eve', 'Zack'

Comments

Popular posts from this blog

Beasiswa New Zealand (continue on a new one)

Coding Lesson (18-22 Nov)

Coding Lesson (continue on a new one)