Coding Lesson (27-31 January)

MONDAY

Continue learning Python on Kaggle.

Changing Lists

Lists are "mutable". You can modify your lists "in place". For example, I want to change the name of the locker owner. Well, Lkhagvasuren is a really hard name to type (I don't know why I choose that name at the first place). So, I'm going to change it.
lockers[6] = 'Amogus'
lockers
['Emily', 'John', 'Adam', 'Alicia', 'Eve', 'Zack', 'Amogus']
That's easier to read. We also can change two and more. Not just one. For example:
lockers[:3] = ['Aidan', 'Raito', 'Yelena']
print(lockers)
['Aidan', 'Raito', 'Yelena', 'Alicia', 'Eve', 'Zack', 'Amogus']

List functions

Python has several useful functions for working with lists, like len, sorted, sum, min and max
Example for 'len':
len(lockers) # Output: 7
Example for 'sorted':
sorted(lockers) # Output: ['Aidan', 'Raito', 'Yelena', 'Alicia', 'Eve', 'Zack', 'Amogus']
Example for 'sum':
age = [11, 16, 42]
sum(age) # Output: 69
Example for 'max':
max(age) # Output: 42

Interlude: objects

In Python, pretty much everything is an object. You can think of an object as a container that holds both data (like variables) and functions (like methods) related to that data.
Attributes and Methods:
Attributes: These are the data part. For example, numbers have an attribute called 'imag' which represents their imaginary part.
Methods: These are functions associated with an object. For example, the number type has a method called 'bit_length()'. bit_length is a method available for integer objects in Python. It returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.
Example with the numbers:
x = 12
Here, 'x' is an object type of integer. It has an attribute 'imag' which gives the imaginary part of the number. Since, 'x' is a real number, its imaginary part is 0.
print(x.imag) # Output: 0
That's simple. Here's the complex one:
y = 12 + 5j
print(y.imag) # Output: 5.0
Here if you create a complex number, it will have non-zero imaginary part (12 is a real part).
Example of Methods:
x = 12
print(x.bit_length) # Output: 4
The binary representation of 12 is 1100, which uses 4 bits. Therefore, x.bit_length returns 4. This method is particularly useful in applications that involve bit manipulation or optimization problems where you need to know the size of the binary representation of numbers.

TUESDAY

List Methods

list.append modifies a list by adding adding an item to the end. append is a method carried around by all objects of type list, not just lockers, so we also could have called help(list.append). However, if we try to call help(append), Python will complain that no variable exists called "append". The "append" name only exists within lists - it doesn't exist as a standalone name like builtin functions such as max or len. Example:
lockers.append('Sugoma')
print(lockers)
# Output: ['Aidan', 'Raito', 'Yelena', 'Alicia', 'Eve', 'Zack', 'Amogus', 'Sugoma']
You also can remove the last item from the list by using list.pop. Here's how to use it.
lockers.pop()
print(lockers)
# Output: ['Aidan', 'Raito', 'Yelena', 'Alicia', 'Eve', 'Zack', 'Amogus']

Searching Lists

list.index method is really handy when you want to find the position of an item in a list.
lockers.index('Eve') # Output: 4
But sometimes we don't know what's the item inside the list and we want to know if an item is in the list. Instead of using list.index, you can use the 'in' operator. For example:
"Aidan" in lockers? # Output: True
"Adam" in lockers? # Output: False

Tuples

Tuples are almost exactly the same as lists. They differ in just two ways. 
1. The syntax for creating them uses parentheses instead of square brackets.
t = (1, 10, 100) you can also write it like this: t =  1, 10, 100
2. They cannot be modified.
They are often used to return multiple values from a function. For example, we will use the x.as_integer_ratio():
x = 0.25
x.as_integer_ratio()
#  Output (1, 4)
These multiple return values can be individually assigned as follows:
numerator, denominator = x.as_integer_ratio()
print(numerator / denominator) # Output: 0.25
Last but not least, you can also swap two variables with tuples. Here's the example:
x = 1
y = 2
x, y = y, x
print x, y # Output: 2, 1

WEDNESDAY

Loops

Loops are a way to repeat a block of code multiple times. It's like telling the computer, "Do this thing, then do it again, and again, until I say stop."
for loop with lists example:
lockers = ['Aidan', 'Raito', 'Yelena', 'Alicia', 'Eve', 'Zack', 'Amogus']
for locker in locker: # This means "for each item (call it locker) in the lockers list."
    print(locker, end=' ')  # This prints each locker followed by a space, instead of a new line.
# Output: Aidan Raito Yelena Alicia Eve Zack Amogus
for loop with tuples example:
multiplicands = (2, 2, 2, 3, 3, 5)
product = 2
for mult in multiplicands:
    product = product * mult
product  # Output: 720
This loop goes through each number in the tuple multiplicands and multiplies them all together.
for loop with string example:
s = 'aiDan Ends the Short video after wAWa called him.'
msg = ''
for char in s:
    if char.isupper():
        print(char, end='')  # Only prints uppercase letters
# Output: DESAW

range()

range is used to generate a sequence of numbers, which is often used for looping a specific number of times. For example:
for i in range(3): # This means "for each number i from 0 to 2." (3 is not included)
    print("Si Kecil Lucu. i =", i)
# Output:
Si Kecil Lucu. i = 0
Si Kecil Lucu. i = 1
Si Kecil Lucu. i = 2

List Comprehensions

List comprehensions provide a concise way to create lists in Python. They are loved for their simplicity.
Here's basic example:
squares = [n**2 for n in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 
This creates a list of squares from 0 to 9. And without list comprehension:
squares = []
for n in range(10):
    squares.append(n**2)
You also can add conditions to your list comprehensions:
short_letter_lockers = [locker for locker in lockers if len(locker) < 6]
# Output: ['Aidan', 'Raito', 'Eve', 'Zack']
This filters lockers to include only those with names shorter than 6 letters. Also, list comprehensions can be combined with functions to solve problems concisely. For example, the 'sum' function:
def count_negatives(nums):
    return sum([num < 0 for num in nums])
This function counts the number of negative numbers in a list using a list comprehension.

FRIDAY

STRING

String Syntax

Strings in Python can be defined using either single or double quotations. For example:
x = 'You will success'
y = "You will success"
x == y # Output: True
Double quotes are convenient if your string contains a single quote character. If we try to put a single quote character inside a single-quoted string, Python gets confused. Well, we can fix that by adding slash like this example:
Wrong: 'Pluto's a planet!' (This is wrong, syntax here will be invalid.)
Fixed: 'Pluto\'s a planet!' (The output will be: "Pluto's a planet!")
Here's some important uses of the backslash.
What you type...What you getexampleprint(example)
\'''What\'s up?'What's up?
\"""That's \"cool\""That's "cool"
\\\"Look, a mountain: /\\"Look, a mountain: /\
\n
"1\n2 3"1
2 3
The last sequence, \n, represents the newline character. For example:
greet = hello\nguys
print(greet) 
# Output: 
hello
guys
You can also use triple-quoted to make a newlines (literally you just need to hit the Enter button on your keyboard rather than using the \n sequence and got confused). Here's the example:
greet_triple_quoted: """hello
guys"""
print(greet_triple_quoted) # Output:
hello
guys

Strings are sequences

Strings can be thought of as sequences of characters. Almost everything we've seen that we can do to a list, we can also do to a string.
1. Indexing
name = 'Aidan'
name[2] # Output: D
2. Slicing
name[-3:] # Output: dan
3. Length
len(name) # Output: 5
4. Loops
[char+'! ' for char in name]
# Output: ['A!', 'i!', 'd', 'a', 'n']
But, one major difference is that they are immutable, they cannot be modified. Even 'lockers.append' won't work on that.

String methods

1. Uppercase conversion:
claim = "Pluto is a planet!"
claim.upper()
Result: 'PLUTO IS A PLANET!' - The upper() method converts all characters to uppercase.
2. Lowercase Conversion
claim.lower()
Result: 'pluto is a planet!' - The lower() method converts all characters to lowercase.
3. Finding substring index
claim.index('plan')
Result: 11 - The index() method returns the position where the substring 'plan' first appears.
4. Startswith Method
claim.startswith('planet')
Result: False - The startswith() method checks if the string starts with 'planet', which it does not.                       

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)