Thursday, October 28, 2021

Strings

A string consists of characters inside 'single quotes' or "double quotes". It can be any length and can contain letters, numbers, symbols, and spaces!!

A string can be considered a "list of characters".


Slicing a string: 

What a helpful diagram this is! 


If you want the letters b and l:
        print(favorite_fruit[0:2])

It works like a number line - from 0 to 2 inclusive. It doesn't include any numbers from 2.01 and up, so the only numbers inside this slice are b and l.

Open ended selections work like this:
        print(favorite_fruit[:4])  #this will print everything from 0 up to 4
        output: blue

        print(favorite_fruit[4:]) #this will print everything from 4 to the end of the string
        output: berry


Slicing with a function:



Printing the last character of a string using len():
        You write the following code:
            last_character = favorite_fruit[len(favorite_fruit)]
            print(last_character)

And you get an error... why? It's because the length of the string is 8 characters, and with a zero index it's 9. There's no character in the 9 position. So what do you do?
        last_character = favorite_fruit[len(favorite_fruit)-1]
        print(last_character)
        
        Output will be y (for the word blueberry)

You can also slice the last few characters like this:
        length = len(favorite_fruit)
        last_characters = favorite_fruit[length-4:]
        print(last_characters)

        Output will be erry (the last 4 characters from blueberry)

It took many iterations for this to work out. It's ok, I think I get it now:


First, define the function to accept 2 items. 
        def password_generator(first_name, last_name):

Then assign a variable to accept the thing that you want: the last 3 letters of the first name and last name using the slicing method we learned just above:
        temp_password = first_name[len(first_name)-3:] + last_name[len(last_name)-3:]

Then return whatever password this generates:
        return temp_password

Then call it to use on the first_name and last_name entered above:
        temp_password = password_generator(first_name, last_name)

Using negative indices to slice


The exercise for negative indices:



Strings are immutable

"Immutable" means that it cannot change once created. "Mutable" data types can change, and "immutable cannot be changed. 

Example of trying to fix a string but it won't work: (Change name from Bob to Rob)


Have to do it a different way:


Escape characters

Escape characters are ones that have some kind of special meaning in python. If you accidentally end a string before including everything you need to, you can use the backslash to include it again. Here is an example:

        fruit = "My favorite fruit" is blueberry ""

This can happen accidentally sometimes, so you add a backslash to the parts you want included in the string:
    
        fruit = "My favorite fruit\" is blueberry\""

Still need some practice on this one:


This didn't work the first time because I forgot to return the counter! 


Other things we can do with strings:



Two exercises with commentary:




Monday, October 18, 2021

Loops (update labels for this post)

There has to be an easier way than this!!


Loops are the way! A loop is a definite iteration.

For loops: in each iteration, we perform an action on each element of the collection.

The general structure of a for loop consists of the following:

for <temporary variable> in <collection>:

      <action>

Where:

"for" means the start of a for loop

<temporary variable> represents the value of the element in the collection the loop is currently on

"in" separates the temporary variable from the collection used for iteration

<collection> is what the loop applies to

<action> is doing something on each iteration of the loop

An example of a for loop:

colors = ["red", "blue", "orange"]

#skip this line because pretty code

for color in colors:

print(color)


Additional notes about temporary variables: the temporary variable's name is arbitrary and doesn't have to be defined beforehand. You can use anything for temporary variable name.

Best practices say to name the temporary variable something descriptive and representative of what we are working on.

In Python you can conserve lines and put the entire for loop on one line:

 for color in colors: print(color)

My first for loop on line 8! 


Using a range inside loops:


Then I got the idea to add this and see what happens:

print("I will finish the python loops module! This is iteration " + str(prom + 1))

And then this happened. I seems to run through everything in the for loop before starting again:



While loops: an indefinite iteration. It performs iterations as long as the given condition exists as true. Here is the basic structure.

while <conditional statement>:

    <action>

While loop walkthrough with printout, and my own loop!


This is what happens when the loop can't figure out if it is at the end:


And the teeny-tiny thing I did to fix it. Do you see it?

(I removed the = sign from the while loop)

**Note to self: avoid writing infinite loops because the computer will run the program forever and bad things happen! If this happens, hit ctrl + c to end the program.**

Stopping a loop with break: break goes on a line by itself.


We want the loop to break before we print the statement that we have found our dog breed.

I tried something else here to avoid printing the dog breed every time it checks until it finds the one I want. It can check the list and confirm it found the dog breed:


Continue statement: ignore what you found and move to the next item in the list. Here is an example:



sales_data contains data for 3 locations:



Writing more "elegant" code: (i.e. fewer lines of code)

It really does end up more "elegant" when we use fewer lines in the code. Everything stays together closely and it takes less time to read.


It's not hard with some more practice. Can you say the statement 3 times fast? 

Well, I guess this is what it's supposed to look like, as I finished this assignment:

In this exercise I had to get the first character of each name using an index number, and I surprised myself by getting it on the first try.


Reversing booleans:


This one threw me for a loop but I think I get it now:

In the above code, I copied the solution from the program itself. Initially I had made a very complicated code that was 5 lines long and tried to figure out how to do a for loop inside another for loop. It was too messy. The solution suggested by the program is very simple and elegant indeed. This line:

product = [e1 * e2 for (e1, e2) in nested_lists]

names the elements inside the brackets e1 (left) and e2 (right) and then multiplies them together. I misunderstood the directions, and I thought it meant multiply it across like a matrix, and then I panicked, because I didn't know how to do it. 

I did this one on my own without hints or help, and extended thinking about the example directly above. 


Well, I thought I was on a roll here, but this happened when trying to get the first element only to be listed:


Well, this is infuriating: code was correct but the brackets!!! I still don't understand when to use which bracket! 


(Here is where I finally remembered that I can comment and explain what I'm doing.)

Again with the brackets! But I did get it on multiple iterations by myself without help in any form!


My code was correct and did the correct output, but I kept getting an error saying zip needs to support something something:


Again:


And now with accidentally calling a defined variable vs a temporary variable:


Thought I had it completely done right the first time! 


Final project for loops lesson:



Wednesday, October 6, 2021

Python Lists

Today's lesson in 11 (!) parts is Lists. Seems pretty important if they use 11 lessons to accomplish this.

Lists:

  • Begin and end with square brackets [ ]
  • Each item is separated by a comma , 
  • For readability and cleanliness I will insert a space after each comma

This is a list


A list without comma separators will not run.

Lists can contain any type of data available in Python! :)

You can just create an empty list like this:


"Method" is a built-in functionality in Python to create, manipulate, and delete data. For lists, this is the 
form: list_name.method(), where the method's input goes between the parenthesis. 

.append() allows us to add an alement to the end of a list.



When using .append() the new item is added to the end of a list.

my first .append()


Combining two lists: 


First location on a Python list is 0, not 1. 

Calling the last item on a list using [-1]


Replacing an item on a list:



Using .remove() to remove an item from a list:


Note: the .remove() method removes the first matching item in a list.

2D lists: creating and appending to


The last place on the last list is called with a [-1][-1]


Changing a 2D list:


Last project for part 1 (of 11): 



Combining lists with the zip() function

names_and_heights = zip(names, heights)

If we print this we'd get this:

<zip object at 0x7f938fj6848>

What this means is that this is where the zip object is stored in the computer memory.

Use list to display the zipped object like this:

converted_list = list(names_and_heights)

print(converted_list)

When doing this, we get the following output (partial):

[('Jenny', 61), ('Alexus', 70), ...

Note that the inner item is a parenthesis and not a bracket. This means it's been converted to a tuple. From the python documentation here, a tuple consists of a number of values separated by commas. 

Got the challenge on the first try! 


Python Lists: Medical Insurance project


Insert function

The .insert() method uses two inputs: the numerical index and the value you want inserted there.

grocery_list = ["mango", "pineapple", "banana"]

grocery_list.insert(0, "berries")

print(grocery_list)

Output becomes:

                    ['berries', 'mango', 'pineapple', 'banana']

Exercise here:


The .pop() method removes a single item from the specified index.

Using .pop() without an index removes the last element in the list

When printing this list it will actually list the removed item below the list

Using .pop() with an index and without:



range() = takes a single input, generates numbers starting at 0 and ending at the number before the input (because it uses 0 as a number). Example below:

my_range = range(10)

print(list(my_range))

When you create a range, it is an object. When you call it, you'll have to use list() to convert it.  

 


Range, continued: You can define a range to start at a specific number and end before your specified number and skip numbers like this:

skip_by_five = range(1, 50, 5) 

This means start the list at 1, go up to 49, and list all numbers that fit the rule of skipping by fives


Finding length of a range is not hard using len() method:


Slicing a list:

Use brackets with a beginning and ending index to determine slice. Remember that the end is one more than you actually need. 


More slicing: only displaying last 2 elements and slicing off last 3 elements, in order:


Counting in a list with .count() 


Sorting a list with .sort()

The difference between .sort() and sorted()

sorted() comes before a list, and makes a new list rather than modifying the one that already exists

 


Practicing lists:

Many iterations to get here. The # under function def is what I had originally tried and made too complicated. I got it to return 3, but I couldn't figure out how to get it to append the 3 to the list. I need to get into the mentality of writing less... I am in the baby stages of learning right now. It's ok. 


Got this one on the second time because I didn't read the directions about doing it 3 times at first:


Again, not reading directions has me redoing work. I missed the part about the length of list.


This was very easy to do, but I didn't think of it as the easy way in the beginning:



Had to refresh myself on how to use sorted() by scrolling up on this post, but I got it! 


Had to get help on this one.


Large project: I did get about 60% of this on my own. Slicing is an issue for me. 


More about tuples:

It's like a list, but you cannot change anything in the tuple after creation. 

When creating a one element tuple, you have to add a comma after the single element:

one_element_tuple = (4,)

You use tuples where you don't want the order to change, or when things need to stay in one way.  

And that is the end of the lists lesson....

Strings

A string consists of characters inside 'single quotes' or "double quotes". It can be any length and can contain letters, ...