Installing Jupyter Notebook on an EC2 instance

I’ve just been introduced to Jupyter Notebook by a coding buddy. I’d heard about it, it’s used extensively on my campus, but since I wasn’t into Python, it never kept it on my radar.

Until NOW!

I decided to spin up an instance in AWS so I could practice Python from any computer. Here goes.

Log into the AWS Management Console. Select your region. Under Compute, click on EC2. On the EC2 dashboard, click on launch instance. This wizard will walk you through spinning up an Amazon Linux 2 AMI that we’ll install Jupyter Notebook on.

Launch An Instance

Step 1: Select the Amazon Linux 2 AMI

Step 2: Choose a free tier eligible instance type (t2.micro) and click Next: Configure Instance Details

Step 3: Select the VPC you wish to install your instance in. I’ve chosen the default_vpc for my installation as well as no preference for my subnet. Click Next: Add Storage

Step 4: Set the root volume size to 15GB. Click Next: Add Tags

Step 5: Add Tags. Assign meaningful tags to your instance. Click Next: Configure Security Group.

Step 6: Select ‘create a new security group’ and give it a name and a meaningful description. Add a custom TCP rule to allow port 8888 and HTTPS. Change the source on the SSH rule to your IP by clicking on the drop-down under the source and selecting My IP. Click Review and Launch.

Showing the security group rules for jupyter notebook

All you need are ports 22,443 and 8888

Create a key pair or select one that you already have. Check the box to confirm. Click launch.

Click view instances to see when your instance comes up. Once status checks are 2/2, copy the public IP of your instance and SSH into your instance using the pem you have or the one you created.  If you’ve just created a key pair, select the check box next to your instance, click on Connect. This will instruct you on how to log into your instance.

Instructions to SSH into instance

Connect to Instance and run updates

Terminal Window

Update the server with the latest patches and install vim and wget if they’re not already installed on your instance.
sudo yum update –y
sudo yum install vim wget –y

Install Anaconda

Head over the Anaconda website and download it with wget. To download it to your instance, right click on the download button  for Python 3.7 (the latest) and copy the  link location to your clipboard.

Anaconda Installer page

From your instance, type wget and paste the URL from your clipboard.
wget https://repo.anaconda.com/archive/Anaconda3-2019.07-Linux-x86_64.sh
This is the current version at this time, but your version may differ. Once the script is downloaded, install it by running:
bash Anaconda3-2019.07-Linux-x86_64.sh
Press ENTER to continue.

Press ENTER several times read and get to the end of the EULA.

Type YES to accept.

The installer will tell you where it’s going to install. Keep the default location and press ENTER. The installer will begin unpacking  and installing new packages. Once the install is finished, it’ll ask you if you’d like to initialize Anaconda3, type YES.

Configure your environment

Edit your .bashrc and add anaconda to your path. From your home directory, open .bashrc with vim.
vim .bashrc
Add the following to the top of the file.
# Jupyter Notebook
export PATH=/home/ubuntu/anaconda3/bin:$PATH

Adding path to .bashrc

Save and exit the file. To reload your shell, do this:
source .bashrc
Your prompt should change to (base). Check to see if python is in your path by running:
which python
If Anaconda was able to configure your environment while it was doing the installation, you may be pointing to anther path for python. Instead of /home/ubuntu/anaconda3/bin/python, your python path may be ~/yes/bin/python. Your mileage may vary.

Configure Jupyter Notebook

First, we’ll create a password for Jupyter Notebook by using the IPython library  and importing a module called passwd.
ipython
Then, import the module. Watch the case.
from IPython.lib import passwd
passwd()

Enter a password, then confirm it.
You’ll get a sha1 hash of your password, copy it to your clipboard as you will need it in the next step.

Running ipython commandNext, we will generate a Jupyter Notebook config file. This is where you’ll put configuration settings for your installation. Run:
jupyter notebook --generate-config
Generate config command

This will create a config file in /home/ec2-user/.jupyter/jupyter_notebook_config.py. Open the config file using vim. At the top of the file enter the following:

vim .jupyter/jupyter_notebook_config.py

conf = get_config()
conf.NotebookApp.certfile = u’/home/ec2-user/certs/mycert.pem’
conf.NotebookApp.keyfile = u’/home/ec2-user/certs/mykey.key’
conf.NotebookApp.ip = ‘0.0.0.0’
conf.NotebookApp.password = u’sha1:701b3d3e0043:2aae91606d863cbe6b27b736′
conf.NotebookApp.port = 8888
conf.NotebookApp.open_browser = False

This does a few things:

  • It assigns the get_config() function to a variable called conf.
  • Now that you have a reference to the configuration object, you can set some attributes that Jupyter Notebook will need
    • Set the location of your self-signed cert. We’ll do that next.
    • Configure the IP to 0.0.0.0.
    • Set your password to log in using the hash generated by running passwd()
    • Configure port that the app will listen on.
    • Tell the app not to try to open a browser when you launch.

 

Save the file and exit.

Create a self-signed certificate

In the root of your home directory, create a folder called certs.
cd ~
mkdir certs
cd certs
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mykey.key -out mycert.pem

Feel free to call your key and pem whatever you like, but remember, you’ll have to edit the config file to match it. Follow the prompts and enter whatever you like.

Create folders for your notebooks

From the root of your home directory, create a folder and name it whatever you like. I’m naming my folder, Notebooks.
cd ~
mkdir Notebooks
cd Notebooks

Run your Jupyter Notebook

From within your Notebook  directory:
jupyter notebook

Your server will start. The output from the terminal gives you information about how to connect to your server. Open a browser and point to the public DNS name of your instance. Append the port number to the end.

https://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:8888/

*NOTE* This URL will change every time you stop and start your instance.

Since this is a self-signed cert, you may get warnings. This is expected.  Log in with the password you chose during set up.

Jupyter Login ScreenJupyter Home page

Now I have to learn how to use it. Wish me luck!

Still learning Python, this time with a buddy

Yes, I’m still learning Python, no I’m not blogging about it as much as I should.

Here is a quick update:

I found a #codenewbie buddy who suggested we learn Python together. We started meeting via Zoom once a week. Learning from “Learning Python the Hard Way”. We set up repos for all of the exercises and we were off. I went on vacation in August and that was that. No coding or blogging or tech of any kind. Now that I’m back in the swing, we’re back to meeting once a week and discussing what we learned in the exercises.

I have another Twitter pal that saw that I was learning Python and she wanted to learn it also. So she and her friend joined us for the first time this week and it was amazing!

Since they hadn’t done any of the exercises and my regular coding buddy couldn’t make the session, we settled on working out of a book called, “Python Crash Course”. We picked chapter 4 (Lists) and were off. The guy that joined up was live coding in something called Jupyter Notebook. As we worked through the examples and bounced question off each other, I was pretty amazed at how this environment worked. He ran code right there, no REPL and could edit and re-run as much as he wanted to. We discovered new methods, walked through the code and even talked about other sysops type stuff (He’s a DevOps engineer and she’s a Ansible Consultant).

After our meeting, I did some digging and now I’m going to spin up Jupyter Notebook in AWS so can code from anywhere. I’ll be sure to write a post on how I set it up.

 

Star with text reading today I learned

Day 8 of Learning Python: lambdas

Part of the reason I’m learning Python is to do things in AWS Lambda. Most tutorials and examples use Python, that, along with it being an easy language to learn it is why I’m doing this blog. Another reason was I needed to do something in GSuite for work the other day, create a Python command-line application that makes requests to the Directory API. I got a strange error and had no idea how troubleshoot it or even how to fix it.  It felt like a job requirement at this point to learn what I could.

I was reading the functions chapter in “Python Programming Illustrated for Beginners and Intermediates” by William Sullivan. The ebook is $2.99 on Amazon and it’s short with quick read chapters to give context so I can use other resources with a better understanding.  I skipped right to functions and part way through, I’m reading about anonymous functions. This sentence popped out at me:

The anonymous functions are created using lambda expressions and cannot contain multiple expressions.

This is the first time I recall hearing anonymous functions are called lambdas! How did I not know this? Here is an example of a lambda.

>> total = lambda var1, var2, var3: var1 * var2 + var3
>>> print(total(2,4,6))
14

 

Wee Bay looking shocked

Mind Blown

Lambdas are just regular old anonymous functions; a single line of code. They don’t have names like when defining a function using the def keyword. They are more like expressions than functions. Lambdas have two rules:

  1. Lambdas must be only one expression.
  2. The expression being evaluated is always returned.
Syntax:  lambda argument : expressions

I’m not finished reading about functions and I haven’t completed the functions section in the Linux Academy yet. I just had to stop and drop this gem into the blog for perpetuity

,Animation of star over words today I learned

 

Day 7 of Learning Python: while loops

A roller coaster filled with loops

Photo by Priscilla Du Preez on Unsplash

While loops are the loops that can get you into trouble. It’s so easy to make create an infinite loop and make your code loops for what seems like forever, or until your machine crashes. While loops will run and run as long as the condition is true.However, not all infinite loops aren’t bad, they have their place in certain applications.

>>> age = 65
>>> while age >=65:
... print(age)  # don't hit enter!
65
65
65
^C
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>

While loops indeed have their place. They appear in most programming languages. You’re not a developer unless you’ve written an infinite loop by mistake, it’s like a rite of passage, but I digress. They are great for repeating something for a determined number of times or counting, but there must be a condition where the condition will change and at some point become false.

>>> age = 1
>>> while age <= 21:
... print(f"On my next birthday, I'll be {age} years old")
... age += 1
...
On my next birthday, I'll be 1 years old
On my next birthday, I'll be 2 years old
On my next birthday, I'll be 3 years old
On my next birthday, I'll be 4 years old
On my next birthday, I'll be 5 years old
...
On my next birthday, I'll be 21 years old

The iterator (age += 1) will change the number on each pass through the loop. Once the condition is false, the loop will stop.

There is more to talk about while loops like break and continue, but here are just the basics. I’m not sure what I’ll write about tomorrow, maybe functions. I have a bit of studying to catch up on first.

Day 6 of Learning Python: if, elif, else

Crossroad signs pointing in different directions

Photo by Javier Allegue Barros on Unsplash

Welcome back to my (semi) daily Python blog post about what I’m learning on my journey. Today is all about the if statements. Also, to not be outdone, elif and else too.  If statement rely on understanding conditional expressions; what’s true and what’s false.  If the statement is true, then your code will execute. if the statement is false, the code inside the statement will be skipped and move on.  Indentation matters in Python. If improperly indented, true code can even be bypassed.

>>>temp= 98
>>> if temp >=82:
...     print(f"It's {temp} degrees outside, turn the air conditioner on!!!!!")
... 
It's 98 degrees outside, turn the air conditioner on!!!!!

The code below is an example of a basic if statement. A condition is tested to see if it’s true, since the temp is greater than or above 82, Python will run the code inside and print the string.

Now we step it up a bit and move into the if/else statements. Like their counterparts, a statement must be true, but here is where the differ. If the statement is false, the code inside the block will not run, instead, the code in the else block will run. If this is true then do that, otherwise, do this. This too is a pretty common construct in most coding languages. The ability to execute code based on one condition or another is at the heart of even the oldest programming language.

>>> gas_tank = 3.25
>>> if gas_tank < 4:
... print("Stop at a gas station")
... else:
... print("Keep driving")
... 
Stop at a gas station

Next of the if statements is the one you use when you can have two conditions to evaluate; if-elif-else, also called chained conditionals. With the these statements, if at any point in the statement a condition is true, that code will run and the rest of the code will be skipped.

>>> shoes =29.99
>>> if shoes > 150:
... print(f"I\'m not spending ${shoes} on shoes")
... elif shoes <= 35:
... print(f"I\'m buying 2 pairs of shoes")
... else:
... print(f"I\'ll take them!")
... 
I'm buying 2 pairs of shoes

In this example, there are two conditions evaluate. If the first one is true, the rest of the code will not run. If the first statement is false, the elif condition will be evaluated.  If both are false, the else block is the default and will run if all else fails.

However, sometimes you have more conditions to test, not just one or two. That is where you add more elif blocks to your code and evaluate multiple conditions. Here is a quick scenario, say you’re out to eat and you’re deciding on which steak to order. You’re counting calories, so you evaluate each option on the menu and decide which one to order that will put you right at your proper protein macros for the day.

>>> if steak == "filet":
... print("Too little protein")
... elif steak == "ribeye":
... print("Way too much fat and protein")
... elif steak == "t-bone":
... print("I can't eat all that")
... elif steak == "sirloin":
... print("This is perfect for my macros")
... elif steak == "skirt":
... print("Almost, but not quite enough")
... 
This is perfect for my macros

I could have put an else and the end and had a default choice, but it’s not always needed.

Lastly are a combination of them all and that’s when you nest conditionals inside each other. Although it can be done, it makes for code that is harder to read. Unless you have a very good reason for using them,  try to avoid them, if possible.

 

 

Day 5 of Learning Python: int, float

Old LED numbers

Photo by Nick Hillier on Unsplash

Welcome back to my (semi) daily Python blog post about what I’m learning on my journey. Today is all about the numbers. To be specific, integers and floating point numbers. Integers are whole numbers, not fractions of numbers that can be either positive or negative. Floating point numbers  have numbers before the decimal (whole numbers) and numbers after the decimal (fraction of a number), they too can be positive or negative.

Something to note, when you’re computing numbers and any one of them is a float, you’ll always return a float, even if the answer is a whole number. (see division below)

We can do calculations and comparisons on numbers in Python using specific operators.

addition + >>> 17 + 4
21
subtraction >>> 9 – 2
7
multiplication * >>> 33 * 3
99
division / >>> 25 / 6.25
4.0
floor division (rounded down) // >>> 33 // 2
16
modulus  (remainder) % >>> 56 % 9
2
exponents  ** >>> 2 ** 10
1024
greater than > >>> 143 > 8
True
less than < >>> 54 < 55
True
greater than or equal to >= >>> 55 >=55.0
True
less than or equal to <= >>> 6 <= 8
True
equal to == >>> 0 == 0.0
True
not equal to != >>> 45 != 44
True

Numbers in Python follow traditional math rules, PEMDAS, to calculate. PEMDAS stands for parentheses, exponents, multiplication, division, addition and subtraction.

I’m using Python 3.7.2 in all examples

>>> 17 + 3 /4 +(125 * 4) - 3**5
274.75

Anytime you get input from the user, it comes back in a string. You won’t be able to do calculations on that input until you typecast it to a number. int( ) and float( ) are the methods that will change that string to the number type you choose. The method type( ) will return the data type. Below I’m confirming that the number I input was really a string and then, using int( ), confirming it was in fact turned into an int.

>>> num1 = input('what is your age? ')
what is your age? 56
>>> type(num1)
<class 'str'>
>>> num1 = int(num1)
>>> type(num1)
<class 'int'>

There are two other number types in Python, long integers and complex numbers. I haven’t had any experiences with them up to this point, but when I do, I’ll be sure to cover it in a future post.

Day 4 of Learning Python: Strings

Let’s talk about strings. Strings are just a list of characters; numbers, letters, punctuation, etc. Basically any item inside of quotes, be they single or double. The only time Python cares is if you have an apostrophe or single quote inside of a string with single quotes. That was a lot, I can show you better than I can tell you.

I’m using Python 3.7.2 in all examples.

>>> 'I love that there's a new Lion King'
  File "<stdin>", line 1
    'I love that there's a new Lion King'
                       ^
SyntaxError: invalid syntax
>>>

This is considered invalid syntax because the interpreter thinks you ended your string at the apostrophe and left a bunch of junk that it couldn’t make sense of at the end. You can use single quotes in this scenario, but you must escape the character in order for it to be understood. In Python, the escape character is the backslash (\).  To try that string again, but this time remembering to escape the apostrophe, we can use single quotes and not get an error.

>>> 'I love that there\'s a new Lion King'
"I love that there's a new Lion King"

No error. The same can be said for double quotes as well. Double quotes inside of a string must be escaped as well.

>>> "Kevin said, "please leave the beer where you found it". "
File "<stdin>", line 1
"Kevin said, "please leave the beer where you found it". "
^
SyntaxError: invalid syntax
>>> "Kevin said, \"please leave the beer where you found it\". "
'Kevin said, "please leave the beer where you found it". '
>>> 

It doesn’t matter which you use, just be consistent, end the string with the same type of quote you began it with.

Strings can also be accessed and manipulated via their index, starting from zero just like other data structures. A few days ago, I talked about lists, well, many of the same methods  can be used on strings as well. Below I used slicing to get characters from the string.

>>> warmup = "jumping jacks"
>>> warmup
'jumping jacks'
>>> warmup[4]
'i'
>>> warmup[0:9:2]
'jmigj'
>>> warmup[-1]
's'

Concatenation is also allowed in Python. You can put strings together using the plus (+) sign  to combine strings together.  Note the space after the starting quote. That’s so a space will be in front of the word for the sake of readability.

>>> leg_day = " squats"
>>> warmup + leg_day
'jumping jacks squats'
>>> warmup + "&"+ leg_day
'jumping jacks& squats'
>>> warmup + " &"+ leg_day
'jumping jacks & squats'

A kind of cool trick you can do with Python is to use multiplication to return a string X number of times. I’m not sure where you’d use this, but I’m sure it has a use case somewhere.

>>> leg_day * 5
' squats squats squats squats squats'

There are methods that can be used on strings to bend them to your will. Here are 7 that I’m sure you’ll use regularly.

.strip() Strip the spaces surrounding the string. Great for making sure passwords don’t have spaces either at the beginning or end when setting a password.

>>> password = "tiwwe%# "
>>> password
'tiwwe%# '
>>> password.strip()
'tiwwe%#'

.lower() is for turning a string into lowercase.

>> bad_string ='yOU dOn\'T kNow hOW'
>>> bad_string.lower() "you don't know how"

.upper() will turn all characters in the string to uppercase.

>>> leg_day.upper() ' SQUATS'

capitalize() will target the first letter in the string and capitalize it.

>>> bad_string.capitalize()
"You don't know how"
>>>

.title() is great for full names. It will capitalize the first letter in each word of the string.

>>> full_name
'beyoncé giselle knowles'
>>> full_name.title()
'Beyoncé Giselle Knowles'
>>>

split() is pretty cool. It can split a string up by a delimiter you choose and turn it into a list.

>>> fruit = 'apple, orange, watermelon, pear'
>>> fruit
'apple, orange, watermelon, pear'
>>> fruit.split(',')
['apple', ' orange', ' watermelon', ' pear']

The last one and the one I think I’ll be using the most is len(). It returns the number of items in a object. Just like JavaScript, everything in Python is an object.

>>> fruit = 'apple, orange, watermelon, pear'
>>> len(fruit)
31

There are so many string methods to learn about, this is just a few I discovered. I’m sure more will cross my path as I learn more about Python.  Stay tuned for more on my journey to Python. Tomorrow I’ll go over numbers.

Day 3 of Learning Python: dictionaries

4 brass keys

Photo by Jen Theodore on Unsplash

Today I learned about dictionaries. Dictionaries are a collection of key-value pairs.  Think JSON, AWS tags and MongoDB. The key and value go together and the data inside the dictionary can be accessed via the key. The indexes aren’t accessed via their numerical, zero based index, they are accessed via their named indexes since there is no real ‘order’ to the data inside.

Dictionaries are created with curly braces, like objects in JavaScript. Each key-value pair is separated by a colon and each pair is separated by a comma.  {‘key’: ‘value’, ‘key’: ‘value}. Below, I’ve assigned a dictionary to a variable.

>>> students = { 'samir': 44824, 'aisha': 23438, 'jose': 29843}
>>> students
{'samir': 44824, 'aisha': 23438, 'jose': 29843}
>>> students['aisha']
23438

Here I just accessed aisha’s key/value pair by her named index.

You can also access they keys and the values by using the keys() and values() functions respectively.

>>> students.keys()
dict_keys(['samir', 'aisha', 'jose'])
>>> students.values()
dict_values([44824, 23438, 29843])

Dictionaries are a pretty big deal in Python and I need more time to play around with them.  I’ll be sure to either amend this post or come up with some more fun, new things I’ve learned.

Until tomorrow!

 

Day 2 of Learning Python: Lists, Tuples and Ranges

We’ve all heard that if you already know a programming language, learning another one will be easier. Well, as a JavaScript developer I must say, learning Python (again!) is going to be easier than learning PHP or JavaScript the first time around. I’ve tried learning Python years ago when my son became interested in programming and I sure wish I’d kept up with it. Going into day 2 of learning Python, I’ve be introduced to lists, tuples and ranges.  All examples in  this post are using version 3.7.2.

Lists

Lists are a built-in python data structure (sequence types). They are very similar to arrays in JavaScript, a list of items, separated by commas and surrounded by brackets.

Lists are mutable, meaning  they can be changed after it is created. They are an ordered sequence of items. holding a collection of things; strings, numbers, booleans, etc. They are zero indexed based structures. You can access an item by their index number which is their position in the list.

>>> my_list
[1, True, 3, 'candy', 3.4, 'Cardi B']
>>> my_list[5]
'Cardi B'
>>>

An easy way to always access the last item in the list is by using the len method. No matter the length of the list, you can have access to the last item.

>>> my_list
[1, True, 3, 'candy', 3.4, 'Cardi B']
>>> my_list[len(my_list)-1]
'Cardi B'
>>>

Since lists are zero indexed, you can always access the first item, no matter the length by the [0] index.

>>> my_list[0]
1
>>> my_list
[1, True, 3, 'candy', 3.4, 'Cardi B']
>>>

Slicing up a list is a great way to access a group of items from the list. Instead of just accessing an item one at a time, the slice object gives you access by where you want to start, where you want to stop and the steps in between.

[start index:end index: step]

>> my_list
[1, 2, 3, 4, 5]
>>> my_list[0:2]
[1, 2]
>>>

[0:2] starting at index 0 and up to, but not including index 2.  Also, you don’t need the 0, you can leave it off and it’s understood as 0.

>>> my_list[:7:2]
[1, 3, 5, 7]
>>>

[0:9:2] starting at index 0 and up to, but not including index 9 counting by 2s.

>>> my_list = [1,2,3,4,5,6,7,8,9,10]
>>> my_list[0:9:2]
[1, 3, 5, 7, 9]
>>>

To return a list that returns every other item (by 2s).

>>> my_list[::2]
[1, 3, 5, 7, 9]
>>>

Reverse a list.

>> my_list[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>

Lists are mutable. You can update and change them any way you like. Reference the index and assign a new item.

>>>my_list = [1,2,3,4,5,6,7,8,9,10]
> my_list[0] = 'a'
>>> my_list
['a', 2, 3, 4, 5, 6, 7, 8, 9, 10]

Functions

Loved the familiarity of these good old methods. Python makes these functions available for quick and easy data manipulation. First up:

.pop() returns and removes items from any position in the list. Using pop() without any index will remove and return the last item in the list.

>>> my_list
['a', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'bug']
>>> my_list.pop()
'bug'

Using .pop() with an index value, you can target any item you like to be popped off and returned.

>>> my_list= [1,2,True,'apricot',5,'Cardi B']
>>> my_list.pop(4)
5
>>> my_list
[1, 2, True, 'apricot', 'Cardi B']
>>>

.pop() can behave like either a queue or a stack. Both are data structures in programming and process data in very different ways. Queue is my favorite, I see FIFO, I think SQS (AWS), first-in first-out (FIFO). Any item added at the end (enqueue) will be the last one to be accessed (dequeue).  You have to do an awful lot of popping to get to the last one if your queue is contains a lot of items. pop(0) will make your list behave like a queue .pop() will make your list behave like a stack. A stack just what it sounds like, laundry. It is a first-in last-out structure. Any item added at the end of the stack will be the first out off the stack. If your favorite jeans are folded first and are at the bottom of the stack, you may as well grab the ones off the top and work your way down. You don’t want to look like you’re re-running your jeans, do you?

Learn more about queues and stacks here.

Next up is .remove() which is great when you want to remove an item by it’s value. Strange thing is, if that item is a Boolean, it’ll remove the item in the 0 index. I didn’t know that was a thing until I just tested it.

> my_list= [1,2,True,'apricot',5,'Cardi B']
>>> my_list.remove(True)
>>> my_list
[2, True, 'apricot', 5, 'Cardi B']
>>> my_list.remove(5)
>>> my_list
[2, True, 'apricot', 'Cardi B']

.reverse() is a handy for when you need to swap the order of the list.

>>> my_list ['a', 2, 3, 4, 5, 6, 7, 8, 9, 10] 
>>> my_list.reverse() 
>>> my_list [10, 9, 8, 7, 6, 5, 4, 3, 2, 'a'] 
>>> my_list.reverse() 
>>> my_list ['a', 2, 3, 4, 5, 6, 7, 8, 9, 10]

Sometimes you just want to throw an item on the end, .append() does the trick. Add the item inside the method and voila!

>>> my_list ['a', 2, 3, 4, 5, 6, 7, 8, 9, 10] 
>>> my_list.append('bug') 
>>> my_list ['a', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'bug']

Last one is .insert(). You can add a new item to any position you want to in your list. Specify the index and the value and insert away. It’ll make room and put your item right where you want it.

>>> my_list= [1,2,True,'apricot',5,'Cardi B']
>>> my_list.insert(2, 43.9)
>>> my_list
[1, 2, 43.9, True, 'apricot', 5, 'Cardi B']

Tuples

Tuples are immutable and fixed-sized, meaning they cannot be changed. They’re good for items that don’t need to change, like x and y coordinates. You can’t assign an item to an index, again immutable. To create a tuple, list items in parentheses, separated by commas. someTuple = (some item, another item, last item,…)

>>> coord = (4.0, 3.2)
>>> coord[1]
3.2
>>> coord[1] = 2.9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

You can create a tuple from a tuple.  This will not change the original tuple, just copy it’s values into a new one. Note the comma after the item in parens.

>>> coord = (4.0, 3.2)
>>> big_coord = coord + (0.8,)
>>> big_coord
(4.0, 3.2, 0.8)

Since tuples are immutable, modifying isn’t possible, but you can overwrite one.

>>> coord = (4.0, 3.2)
>>> coord
(4.0, 3.2)
>>> coord = (2.2, 5.1)
>>> coord
(2.2, 5.1)

This is pretty cool about tuples. You can unpack the items from a tuple and assign them to variables. As long as the number of items and variables are equal, you can easily unpack and assign those values.

>>> user_info=("Smith", "Rasheeda", "F", 342492)
>>> user_info
('Smith', 'Rasheeda', 'F', 342492)
>>> fn, ln, mi, id = user_info
>>> fn
'Smith'
>>> ln
'Rasheeda'
>>> mi
'F'
>>> id
342492

The last thing about tuples is that they remind me they can be used as template literals in that, you can  use a tuple to do string substitution.

>>> print("My favorite flavors of ice cream are %s and %s." % ("butter almond", "strawberry"))
My favorite flavors of ice cream are butter almond and strawberry.
>>>

Ranges

The last thing I covered was ranges. A great tool to quickly create a list of items in a range with just one method. Very similar to slicing, but way better if you want to create a quick list of  numbers. To get those numbers in to a list, use the list function. The values needed are the start, stop and the step. If you leave the step of, the list is in numerical order. range(start, stop, range)

>>> range(2,22,2)
range(2, 22, 2)
>>> list(range(2,22,2))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>>

Not a bad first few days with  Python.  Great stuff here and there is so much to learn. Stay tuned for tomorrows post. I think I’ll go over dictionaries.

 

Day 1 of Learning Python

I’m marking today and the official day I start to learn Python programming. I’ll be working my way through Linux Academy’s Intro to Python Development Course and sprinkling in some exercises from the book Python Crash Course, 2nd edition.

Day 1

I can’t tell you how many times I’ve forgotten how to exit the REPL in python. Well, that stops today.

>>> exit()

Either use the exit function or Ctrl+D.

At the beginning of a python script, you can place the ‘shebang’ on the first line. This indicates to the interpreter that you want to use the python version in your path.

#!/usr/bin/env python3.7

Now, you don’t need to hard code the exact path to the executable.

It’s a good idea to create a bin folder in your home directory. This can be a place you put your python tools. To run them without the .py extension, you can put your home/bin folder in your path, if it’s not already there.

Be sure to make the script executable.

chmod u+x
export PATH=$PATH:$HOME/bin
echo $PATH

Now you can run the  script from bin.

How to comment in python:

Add a hash before the line of code or as a trailing comment after a line of code, either in the REPL or in a script to comment it out.

Strings:

Strings in Python can be created with either single or double quotes.

>>>'This is a string'
>>>"This is also a string"

You can also create multl-line strings with triple single quotes.

With all the examples I’ve gone over today, the one most used is to clear the REPL. On my linux machine, I use Ctrl+L. On my Mac, I can use both Ctrl+L and Command+K to clear the screen.