What Have I Learned?

Before my adventure into Python, I knew nothing. I knew that my passion was technological, but I did not know what to do. I had researched the different programming languages and I landed on Python (well, as seen in my first post, it was Swift but that was not for me).

I went from having zero knowledge regarding Python to creating long paragraphs of code! One major accomplishment of mine is the troubleshooting I have accomplished. Whenever my code did not work, I simply dove in a tried to fix it. When that did not work, more often than not, I dove deep (into Google) to find a solution. With programming, once you’ve learned the basics of one language, you can learn any other language.

The biggest hurdle between languages is syntax – how do you create this or how do you do that. Now that I have a good understanding of Python, the only thing I need to do is change some concepts and then I can do any other language. For example, when creating functions in Python, it’s: def function_name():[Insert code here] but in C++ it’s void function name{[Insert code here]}. Once I Google learn the syntax, I can develop a basic understanding of any programming language.

Just like learning any speaking language, you have to learn the basic words before you can form sentences. Then you have to learn punctuation before paragraphs, etc. Personally, I would like to see myself in the essay stage: I can develop an idea then actually implement it and share it here. One day, I hope to be “writing books” (to keep the analogy going – not actually writing books) and being able to use them in my daily life.

I am very thankful for this blog and project to open my eyes to the wonder of programming.

Future Plans With Python?

Python, like any other programming language, is a necessity to know in some workplaces. Software Engineers, Software Developers, and Security Analysts are a few to name. My goal is to not only learn python but other programming languages such as C++, Java, and SQL. Once I know enough of these (I doubt I will master these anytime soon), I want to get a job as an Information Security Analyst.

Information Security Analysts have an average annual salary of $90,120 as of 2015. The world around us is covered with technology and new tech is being developed all the time. Information Security Analysts are paid to basically try to break software. They look for ways that the bad guys could use to use something maliciously, once they do that, they fix the problem.

Learning Python and other programming languages is crucial to being an Information Security Analyst. I want to work for a big company such as Google, Palantir, Amazon, etc. To further my education, I plan to do dual enrollment in college: a Bachelor’s Degree in Electrical Engineering and a Master’s in Computer Science.

My sister, a statistics major, had to take a computer science course in which she learned both Python and C++. By starting now, I have created a solid foundation which will help me later in college. Students that have not learned programming beforehand may have a hard time in class, or at least, I will be ahead of the curve.

I am glad that I have embraced my passion early on which will help me later in life. I plan on continuing to learn Python, C++, and any other language that interests me – the more the better!

Final Project

Since I have made a lot of small programs, I wanted to have a way to quickly open and close them. It was a pain to have to open Windows Explorer, navigate to the proper directory, and then select the one I wanted. While sure, this does not take too long, I know it can be faster. I used Tkinter to create a GUI (Graphical User Interface) to navigate between my programs easily.


from random import *
from turtle import *
from tkinter import *
from tkinter import scrolledtext
import sys
import os

'''
These Functions Open Previous Projects
'''

def rps():
    os.system("RockPaperScissors.py")

def med():
    os.system("MessageEncrypterandDecrypter.py")

def dice():
    os.system("Dice.py")

def iss():
    os.system("ISSLocation.py")

def art():
    os.system("TurtleArt.py")

def race():
    os.system("TurtleRace.py")
'''
Defining Various Variables
'''

winx = 700
winy = 600
xcoord = winx/2
wincolor = "Dodger Blue"
btn_bg = "Snow"
btn_fg = "Black"
'''
Creating The Window
'''

window = Tk()
window.title("Please Select An Item")
window.geometry('700x500')
window.configure(background = wincolor )
'''
Instruction Label
'''

lbl_rps = Label(window, text = "Select an Item to Run", font = ("TkHeadingFont", 20), bg = wincolor)
lbl_rps.place(x = xcoord, y = 50, anchor = "center")
'''
Placing Buttons
'''

btn_med = Button(window, text = "Message Encrypter / Decrypter!", command = med, bg = btn_bg, fg = btn_fg)
btn_med.place (x = xcoord, y = 150, anchor = "center")

btn_rps = Button(window, text = "Rock Paper Scissors!", command = rps, bg = btn_bg, fg = btn_fg)
btn_rps.place (x = xcoord, y = 200, anchor = "center")

btn_dice = Button(window, text = "Roll Dice!", command = dice, bg = btn_bg, fg = btn_fg)
btn_dice.place (x = xcoord, y = 250, anchor = "center")

btn_iss = Button(window, text = "Where Is The ISS?", command = iss, bg = btn_bg, fg = btn_fg)
btn_iss.place (x = xcoord, y = 300, anchor = "center")

btn_art = Button(window, text = "Create Art!", command = art, bg = btn_bg, fg = btn_fg)
btn_art.place (x = xcoord, y = 350, anchor = "center")

btn_race = Button(window, text = "Race Turtles!", command = race, bg = btn_bg, fg = btn_fg)
btn_race.place (x = xcoord, y = 400, anchor = "center")

'''
mainloop Used To Keep Window Open
'''
window.mainloop()

I was going to attach a phot of the code, but normally I do this to show the indentations. First of all, I figured out how to indent it on here earlier, plus, there is almost no indentation done here.


from random import *
from turtle import *
from tkinter import *
from tkinter import scrolledtext
import sys
import os

Nothing new imported here, except for “scrolledtext” which allowed me to create text that scrolled acorss the window. In my opion, it did not look good, so I took it out (and left it in the imports in case I wanted to add it in later). Orignally, I had done something like this: import [python file] as a way of bringing in the other programs (so when buttons are pressed, it runs a program) but then I googled discovered that I can do this:


'''
These Functions Open Previous Projects
'''

def rps():
    os.system("RockPaperScissors.py")

def med():
    os.system("MessageEncrypterandDecrypter.py")

def dice():
    os.system("Dice.py")

def iss():
    os.system("ISSLocation.py")

def art():
    os.system("TurtleArt.py")

def race():
    os.system("TurtleRace.py")

Simply typing os.system("[insert file name here]") allowed me to bring the other files in without a hassle. Throughout when I was typing this, I made comments explaining what each section did, to an extent.


'''
Defining Various Variables
'''
winx = 700
winy = 600
xcoord = winx/2
wincolor = "Dodger Blue"
btn_bg = "Snow"
btn_fg = "Black"

I was expirmenting with the window size, such as trying to find a good length where the buttons were centered well. winx and winy are the variables of the length and width of the window. xcoord is for placing the buttons later; it is half the width to put it in the middle. wincolor is for the background color of the window, btn_bg/fg are the background and foreground colors of the buttons. The whole list of colors is quite large:

tkintercolorcharts
Courtesy of http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter


'''
Creating The Window
'''

window = Tk()
window.title("Please Select An Item")
window.geometry('700x500')
window.configure(background = wincolor )
'''
Instruction Label
'''

lbl_rps = Label(window, text = "Select an Item to Run", font = ("TkHeadingFont", 20), bg = wincolor)
lbl_rps.place(x = xcoord, y = 50, anchor = "center")

To make the actual window, I did as we normally would for a Tkinter window, giving it a title and size as well as a background color. All the instruction label is, is the text at the top saying, “Select an Item to Run” (creative I know). Anchoring is exactly like an anchor, “where does this boat stop?” Choosing center simply means (can you guess it?) that the word is centered.


'''
Placing Buttons
'''

btn_med = Button(window, text = "Message Encrypter / Decrypter!", command = med, bg = btn_bg, fg = btn_fg)
btn_med.place (x = xcoord, y = 150, anchor = "center")

btn_rps = Button(window, text = "Rock Paper Scissors!", command = rps, bg = btn_bg, fg = btn_fg)
btn_rps.place (x = xcoord, y = 200, anchor = "center")

btn_dice = Button(window, text = "Roll Dice!", command = dice, bg = btn_bg, fg = btn_fg)
btn_dice.place (x = xcoord, y = 250, anchor = "center")

btn_iss = Button(window, text = "Where Is The ISS?", command = iss, bg = btn_bg, fg = btn_fg)
btn_iss.place (x = xcoord, y = 300, anchor = "center")

btn_art = Button(window, text = "Create Art!", command = art, bg = btn_bg, fg = btn_fg)
btn_art.place (x = xcoord, y = 350, anchor = "center")

btn_race = Button(window, text = "Race Turtles!", command = race, bg = btn_bg, fg = btn_fg)
btn_race.place (x = xcoord, y = 400, anchor = "center")

The second most time consuming part of this was placing buttons (the first was “discovering” how to connect files, the third was determing the amazing colorscheme of everything). I made each button follow the same template:


btn_[short name of function] = Button(window, text = "[Title of File]", command = [function name], bg = btn_bg, fg = btn_fg)
btn_[name[.place (x = xcoord, y = [whatever y coord I decided], anchor = "center")

The way I decided the y coordinates was a true feat of mathemtical reasoning. I guessed. I typed in the first one (in this case 150) and just added 50 per button – this way they are spaced out evenly. The command = [function name] is how we open the program. Once the button is clicked, it calls whichever function – and the function opens the program.

Finally, what good is a window that we can’t see? That is why I included the window.mainloop() (a built in Tkiner function) – so it loops the display until we quit.

In all the time it took to reserach and code, I could have opened each program about 10,000 times. Spend a lot of time now to save time later.

Rolling A Die

I made a “small” program through Python that will randomly roll a die. While it is very simplistic looking, it is a couple hundred lines of code, so it is longer than what I have done in the past. Thank goodness I just discovered how to insert scroll boxes, without it, the post took ages to scroll down past the code.

import os
import sys
import time
from tkinter import *
from random import *
from turtle import *
from PIL import ImageGrab
'''
Functions for placing the dots on the die
One for each number, 1-6
'''
def createdie():
  die = Turtle()
  die.ht()
  die.speed(100)
  die.pensize(5)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
def create1():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  #25,25 is the center of the die
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
def create2():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
def create3():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
def create4():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
  goto (15, 35)
  pendown()
  dot(radius)
  penup()
  goto (35, 15)
  pendown()
  dot(radius)
  penup()
def create5():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
  goto (15, 35)
  pendown()
  dot(radius)
  penup()
  goto (35, 15)
  pendown()
  dot(radius)
  penup()
def create6():
  circle = Turtle()
  circle.ht()
  radius = 8
  penup()
  goto (15, 13)
  pendown()
  dot(radius)
  penup()
  goto (15, 37)
  pendown()
  dot(radius)
  penup()
  goto (15, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 13)
  pendown()
  dot(radius)
  penup()
  goto (35, 37)
  pendown()
  dot(radius)
  penup()
def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)
def quitprogram():
    root = Tk()
    Label(root, text="Restart or Quit?").pack()
    Button(root, text="Restart", command=restart_program).pack()
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
'''
While statement for "rolling" the die
'''
while True:
    roll = randint(1,6)
    if roll == 1:
        hideturtle()
        createdie()
        create1()
        break
    elif roll == 2:
        hideturtle()
        createdie()
        create2()
        break
    elif roll == 3:
        hideturtle()
        createdie()
        create3()
        break
    elif roll == 4:
        hideturtle()
        createdie()
        create4()
        break
    elif roll == 5:
        hideturtle()
        createdie()
        create5()
        break
    elif roll == 6:
        hideturtle()
        createdie()
        create6()
        break
quitprogram()
tkinter.mainloop()

Truly, this program is very repetitive, a couple functions and statements but repeated for each outcome of a die roll.

import os
import sys
import time
from tkinter import *
from random import *
from turtle import *
from PIL import ImageGrab

As usual, we need to import our modules. Sinec this is our longest one, we have more imported modules because I wanted to use a lot of different methods to get this done. The sys and time modules were used for the end of the program. These were used to restart or quit the program, in conjunction with tkinter. The modules for visualizing the die were tkinter, turtle, and PIL. Finally, since rolling dice is “random”, random was imported so we can implement randomness.

def createdie():
  die = Turtle()
  die.ht()
  die.speed(100)
  die.pensize(5)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
  die.forward(50)
  die.left(90)
def create1():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  #25,25 is the center of the die
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
def create2():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
def create3():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
def create4():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
  goto (15, 35)
  pendown()
  dot(radius)
  penup()
  goto (35, 15)
  pendown()
  dot(radius)
  penup()
def create5():
  circle = Turtle()
  circle.ht()
  radius = 10
  penup()
  goto (15, 15)
  pendown()
  dot(radius)
  penup()
  goto (25, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 35)
  pendown()
  dot(radius)
  penup()
  goto (15, 35)
  pendown()
  dot(radius)
  penup()
  goto (35, 15)
  pendown()
  dot(radius)
  penup()
def create6():
  circle = Turtle()
  circle.ht()
  radius = 8
  penup()
  goto (15, 13)
  pendown()
  dot(radius)
  penup()
  goto (15, 37)
  pendown()
  dot(radius)
  penup()
  goto (15, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 25)
  pendown()
  dot(radius)
  penup()
  goto (35, 13)
  pendown()
  dot(radius)
  penup()
  goto (35, 37)
  pendown()
  dot(radius)
  penup()

These functions use the turtle module to create our die. The first function creates the square outline. Yes, turtle does have a built in square shape, but for me, the dots went under the square so I had to just outline a square in order to show the “pips” on the die. The next functions create the pips (the dots – you learn something new everyday).

To make the dots, we need the coordinates of where each one will go, according to what number is displayed. I made this expert diagram to demonstrate how I did it.

Dice layout

I started with the middle dot and guessed my way to the center-ish of the square. I decided to make (25, 25) the center. The rest of the dots were easy from there: To make a two, you subtract 10 and add ten to the center so it goes from (25, 25) to (15, 15) for the bottom left dot, and (35, 35) for the top right. For each of the 6 functions, it is just doing this simple math for each point so I won’t waste your time explaining them.

One hiccup I had when making these dots was it would draw lines connecting each dot. To avoid this, we made sure to, in our functions, have the pen up with penup() when it moved to the point, and then put the pen down once it reached the point.

Our next functions control the exiting of our A+ dice game.

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)
def quitprogram():
    root = Tk()
    Label(root, text="Restart or Quit?").pack()
    Button(root, text="Restart", command=restart_program).pack()
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()

Now, I had no idea these commands (python = sys.executable
& os.execl(python, python, * sys.argv)
) existed. A quick Google search led me to use these to close our program. All we are doing is saving the program as a variable, and then telling it to stop – when the function is called.

'''
While statement for "rolling" the die
'''
while True:
    roll = randint(1,6)
    if roll == 1:
        hideturtle()
        createdie()
        create1()
        break
    elif roll == 2:
        hideturtle()
        createdie()
        create2()
        break
    elif roll == 3:
        hideturtle()
        createdie()
        create3()
        break
    elif roll == 4:
        hideturtle()
        createdie()
        create4()
        break
    elif roll == 5:
        hideturtle()
        createdie()
        create5()
        break
    elif roll == 6:
        hideturtle()
        createdie()
        create6()
        break

This while statement simulates us rolling the die. This is where our random module comes into play. So, we want our if statements to be ready at all times, this is why we start it with: while True: meaning that while it is true, it will be ready. Since we did not give it any more parameters, it is always true (confusing concept, but think, something that is true…is true!) Even though dice are not technically random, we want it to be so we choose a random integer between 1 and 6 (this is the possible roll outcomes we could get).

if roll == 1:
        hideturtle()
        createdie()
        create1()
        break

If our die rolls a 1, then we need to display a one. If you forgot that we are using the turtle module, then the hideturtle() line might be weird, this is used because we drew out square instead of using the predefined one. When turtle draws, it has an unsightly pointer, we want to hide that and use the built in function to do so. Next we tell it to create our die and then place our single dot. Now this is done for each roll outcome, notice how they all end with “break” – what this does is force our code to exit the “while True” loop. Now we can get to the end functions:

quitprogram()
tkinter.mainloop()

Our quitprogram() creates a GUI (Graphical User Interface – the message box that prompts us to quit or restart). That functions then either restarts or quits, based on the user’s input. Finally we end with another built in tkinter function. What it completely does is beyond me, all I know is that without it, nothing works right! I had not included it and that caused our window with our die to close before it even finished! Once I put it in, it gave us plenty of time to admire the amazing craftsmanship that is our dice game.

Tracking The International Space Station!

I just now learned that there is a website that gives information about the ISS through JSON. JSON (pronounced JSON) is a programming language, like Python, which is simply Javascript in a human-readable format. The website has two sections (as far as I know), one for the International Space Station’s location and one for who is on board!

The website shows this: {"timestamp": 1524801325, "iss_position": {"latitude": "48.8868", "longitude": "113.9675"}, "message": "success"} for the location…
And this: {"people": [{"name": "Anton Shkaplerov", "craft": "ISS"}, {"name": "Scott Tingle", "craft": "ISS"}, {"name": "Norishige Kanai", "craft": "ISS"}, {"name": "Oleg Artemyev", "craft": "ISS"}, {"name": "Andrew Feustel", "craft": "ISS"}, {"name": "Richard Arnold", "craft": "ISS"}], "number": 6, "message": "success"} for the crew manifest.

Although we can read that, it still could look cleaner. So naturally, I wanted to implement this into my Python code and see what I can do (Side note: I figured out how to indent my code properly – it adds some grey highlight before and after the code but oh well!).

import json
import turtle
import urllib.request
from turtle import *
import os
os.getcwd()

#print ("Current working dir : %s" % os.getcwd())
url_astros = 'http://api.open-notify.org/astros.json'
url_iss = 'http://api.open-notify.org/iss-now.json'
responsea = urllib.request.urlopen(url_astros)
resulta = json.loads(responsea.read())
response = urllib.request.urlopen(url_iss)
result = json.loads(response.read())


print('People in Space:  ', resulta['number'])

people = resulta['people']

for p in people:
    print(p['name'], 'Is currently stationed in: ', p['craft'])


location = result['iss_position']
lat = float(location['latitude'])
lon = float(location['longitude'])
print('Latitude: ', lat)
print('Longitude: ', lon)

screen = turtle.Screen()
screen.setup(1200, 480)
screen.setworldcoordinates(-180, -90, 180, 90)
screen.bgpic('map.gif')


screen.register_shape('isssmall.gif')
iss = turtle.Turtle()
iss.shape('isssmall.gif')
iss.shapesize(311, 124)
iss.setheading(90)

iss.penup()
iss.goto(lon, lat)
#longitude goes first because coordinates are (x,y)


Here is what it looks like in a video.

I learned A LOT of new Python code tricks during this project – many of which would have been very helpful in the past. The biggest thing I learned was how to insert images into my Python code. I always tried in my other ones however I could never get them to load!

import json
import turtle
import urllib.request
from turtle import *
import os
os.getcwd()

You may have noticed: 1. There are more imported modules than my usual, and 2. There is a line of code that is not importing anything that I still included in this chunk. I included os.getcwd() because this simple line allowed me to get images into my code. What this (and the next line: #print ("Current working dir : %s" % os.getcwd())) did was show me where my code was happening and, more importantly, where to place my images. I always tried to place my images in the Turtle library or in the Tkinter library, this line told me to put it where I save my code and boom – it worked!

url_astros = 'http://api.open-notify.org/astros.json'
url_iss = 'http://api.open-notify.org/iss-now.json'
responsea = urllib.request.urlopen(url_astros)
resulta = json.loads(responsea.read())
response = urllib.request.urlopen(url_iss)
result = json.loads(response.read())

Now we need to define variables that are used in the “urllib.request” module – what this does is go to the website and grab the data it shows. Since we are dealing with two sites (one for location and one for crew members) we need two sets of the variables. We can’t have two variables with the same name, so, I named the first set with an “a” at the end, for “astronaut.”
The “urllib.request” module (we will call this the url module for ease) needs to know 2 things: The url it is going to, and the response it should be getting. Then we turn this into out resulta and result variables.

Now that our data is stored, we need to display it to the user:

print('People in Space:  ', resulta['number'])
people = resulta['people']
for p in people:
    print(p['name'], 'Is currently stationed in: ', p['craft'])

Ah yes! Another for loop – what a familiar sight! We use this for loop to display our crew data. We want to know who is on board and what spacecraft they are in (obviously it is the ISS, but if one were to do this across multiple crafts, this part would be more important). Our for loop counts everyone on board, and for every person listed on the website, puts their name and where they are stationed at.

Cool, so that was the main part because I first found out about the crew site only. Once I discovered that there were coordinates, too, I was all over that!

location = result['iss_position']
lat = float(location['latitude'])
lon = float(location['longitude'])
print('Latitude: ', lat)
print('Longitude: ', lon)

The website already called the ISS’s position ‘iss_position’, so we just grab that from the result. Then we make two more variables – latitude and longitude. Normally we see int (integer) values, but we need the numbers after the decimal places so we call them “floats” to ensure that we get everything.

screen = turtle.Screen()
screen.setup(1200, 480)
screen.setworldcoordinates(-180, -90, 180, 90)
screen.bgpic('map.gif')

Back to good ol’ Turtle, now that we can use images properly! Here we are just creating a screen as large as our map (it was 1200 pixels by 480 pixels so we make our screen fit it perfectly – *insert flat earth joke here*). Then we have to tell Turtle where the map coords are, since our coordinates go by -180,xyz’ and all that, we simply put the top values into our Python code. Then we make the background image our map – you know, so we can see it?

screen.register_shape('isssmall.gif')
iss = turtle.Turtle()
iss.shape('isssmall.gif')
iss.shapesize(311, 124)
iss.setheading(90)

Now we create a shape – since we want our ISS to look like the ISS, we grab the picture of it and choose that instead of, say, a square. iss = turtle.Turtle() tells the computer to use the built in Turtle functions – to save us time. The original image size was about 630ish by 480ish but that was way too large. So i mathematically guessed a size until it looked nice – we ended up with 311×124. Setting the heading ensure that we have our ISS oriented in the correct direction.

Finally, all we have to do now is tell our ISS to go to its true location, according to the map.

iss.penup()
iss.goto(lon, lat)
#longitude goes first because coordinates are (x,y)

Again, bringing the pen up prevents a line being drawn on our map, and then we put the pen back down to confirm the ISS’s location.

I learned SO much from this project. The bringing in of images took about an hour and a half to figure out – pretty good for when I spent longer in the past and still failed! Now I can use images in a lot more code – like the modern art code could have been real art (cheating I know)! So far, this may have been the most fun and the most beneficial project I have done so far!

Creating Art With Turtle!

Not only can we use Python’s Turtle to race turtles, but we can also create some cool art by using the same idea!
from turtle import *
from random import *
colormode(255)
def randomcolour():
red = randint(0, 255)
green = randint(0, 255)
blue = randint(0, 255)
color(red, green, blue)
def randomplace():
penup()
x = randint(-100, 100)
y = randint(-100, 100)
goto(x, y)
pendown()
def randomheading():
heading = randint(0, 360)
setheading(heading)
def drawrectangle():
randomcolour()
randomplace()
hideturtle()
length = randint(10, 100)
height = randint(10, 100)
begin_fill()
forward(length)
right(90)
forward(height)
right(90)
forward(length)
right(90)
forward(height)
right(90)
end_fill()
shape("turtle")
speed(0)
for i in range(1, 30):
randomcolour()
randomplace()
randomheading()
stamp()
def drawcircle():
radius = randint(5, 100)
randomcolour()
randomplace()
dot(radius)
def drawstar():
randomcolour()
randomplace()
randomheading()
begin_fill()
size = randint(20, 100)
#draw the star shape
for side in range(5):
left(144)
forward(size)
end_fill()
clear()
setheading(0)
for i in range(20):
drawrectangle()
clear()
for i in range(50):
drawcircle()
clear()
for i in range(20):
drawstar()

This project was created mainly by functions, so now we can break it down by larger chunks. As usual: below are some photos of both the code and the product(from a different run through than the video to show how random it is) of each artistic masterpiece, and here is a video of it all at once.

ArtIndent

Now for the code. To start we need to import the necessary modules.
from turtle import *
from random import *

Next is a line that I thought was unnecessary, however, the code did not work without it: colormode(255) This sets the color mode to standard RGB (red, green, blue, and their combinations). I thought this was implied but I researched it and there are other modes like “HSB” for Hue, Saturation, and Brightness.

Now that the basics are in place, we can define the functions that will paint for us.

def randomcolour():
red = randint(0, 255)
green = randint(0, 255)
blue = randint(0, 255)
color(red, green, blue)

As functions usually go, we do this so we do not have to type this later on in our code. What this does is make sure that, when it is called, each shape knows to make its color scale from 0-255 (again, standard RGB process). Since we do not want just all red shapes, we make each color a random integer with randint.

def randomplace():
penup()
x = randint(-100, 100)
y = randint(-100, 100)
goto(x, y)
pendown()

We also do not want our shapes to all be in the same spot, so we define this function to allow us top randomly place it. Turtle works by “drawing” each item with a pen – this is why we need to say penup() (otherwise there will be a line connecting every shape as if a pen were dragged across to move each one). Next we define our coordinates to be random for each shape between -100 and 100 for each. The boundaries can be nearly anything, but I chose these numbers to ensure that the art will be compact instead of spread across a whole window. Once we have our point(s), we tell Turtle to move the pen to that point and then pendown(), A.K.A. draw the shape.

def randomheading():
heading = randint(0, 360)
setheading(heading)

This quick function simply tells each shape that it can face a random heading, or direction. The heading is restricted to 360 degrees because more than that is simply redundant.

def drawrectangle():
randomcolour()
randomplace()
hideturtle()
length = randint(10, 100)
height = randint(10, 100)
begin_fill()
forward(length)
right(90)
forward(height)
right(90)
forward(length)
right(90)
forward(height)
right(90)
end_fill()

Now we have a larger function. This one draws the rectangular art piece(s). In it, we have some function-ception because we call functions inside of another function! We tell the rectangles to randomly place and color themselves and give them a random length and then fill them from corner to corner will the color (90 degree turns are for when the fill “turns” and go straight – the distance of the sides.

shape("turtle")
speed(0)
for i in range(1, 30):
randomcolour()
randomplace()
randomheading()
stamp()

Hooray! Now we start making art! The turtles are pretty quick so i did not define a function for them. I made a for loop to place randomly colored and placed turtles until it reaches about 30 turtles.

def drawcircle():
radius = randint(5, 100)
randomcolour()
randomplace()
dot(radius)
def drawstar():
randomcolour()
randomplace()
randomheading()
begin_fill()
size = randint(20, 100)
for side in range(5):
left(144)
forward(size)
end_fill()
clear()
setheading(0)

Dangit! I just realized a bad habit that I need to break: functions should generally always be defined at the start of the code; here I defined some after we made turtles! Oh well, no fatal error was produced this time.

I wanted the circles to be randomly sized as normal, but they obviously do not go by length and width which is less work, since we only have to define radius instead of a length and a width variable. Making a dot is more efficient than making shape("circle") because it is a built in function in Turtle – saving us work.

After all of our functions, we still need to place everything by calling the functions down below.

for i in range(20):
drawrectangle()
clear()
for i in range(50):
drawcircle()
clear()
for i in range(20):
drawstar()

The functions were called in for loops this way we can make a lot at the same time (20 stars, 50 circles, etc.). This art project taught me a lot about the uses and importance of not only functions but also for loops. They also go hand in hand together because once we create our functions, we can call them a lot of times with one simple for loop, as we did above. For loops and functions are used in every big python project because of their versatility – i am glad that I am getting familiar with them now!

Ciphers With Python!

My friends and I always enjoy encrypting short messages and then the other trying to decrypt it. I made a similar program with Python, and while it is simplistic and not necessarily secure, it is still fun and helps me learn Python.

alphabet = "abcdefghijklmnopqrstuvwxyz"
key = input('Please enter a number between 1 and 26 for your key: ')
newMessage = ''
message = input('Please enter a message:')
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (int(position) + int(key)) % 26
newCharacter = alphabet[newPosition]
#print('The new character is: ', newCharacter)
newMessage += newCharacter
else:
newMessage += character
print('Your new message is:', newMessage)
decrypt = input("Please enter string to decrypt:")
dkey = input('Please enter your decryption key: ')
dnewMessage = ''
for character in decrypt:
if character in alphabet:
position = alphabet.find(character)
newPosition = (int(position) - int(dkey)) % 26
newCharacter = alphabet[newPosition]
dnewMessage += newCharacter
else:
dnewMessage += character
print("Your decrypted message is:", dnewMessage)

It is simple in the sense that there is nothing to import, but actually making characters change and then change back in accordance with a number, was kind of hard.

A picture of the color coded, indented code, is below and a short video of it is here.
medindent

The way my program works is exactly like a Caesar Cipher: kwobs
You select your letter, then (using whatever key that was previously determined) you move the inner circle to get your next letter. To explain, if your letter was A, and you had a key of 19, you would move the circle over 19 times which makes A become T. Now that takes a while for a whole word, let alone a long message, hence why I figured I could speed the process up.

So to start, we need to tell Python what the alphabet is (Yes, we already know it, but the computer does not necessarily). To do so, we simply create a variable the same way as we have done in the past.
alphabet = "abcdefghijklmnopqrstuvwxyz"
The next variable to declare is newMessage, which is going to be used later so it is simply “blank” for now (that is why it is just quotes with no content: newMessage = '').

Okay, so we have a newMessage – our soon to be encrypted one, but where is the normal one? The message obviously needs to be input by the user so we create a variable to take it in: message = input('Please enter a message:')

Now that we have a message, we need to change each letter in it with a for loop and an if/elif statement. The for loop occurs for each character in the message.
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (int(position) + int(key)) % 26
newCharacter = alphabet[newPosition]
#print('The new character is: ', newCharacter)
newMessage += newCharacter
else:
newMessage += character

So the first line of the if makes sure that the letter is in the alphabet – but wait? Of course it would be in the alphabet, right? Sure, letters are, but punctuation like question marks and commas are not, so we have to exclude them. That is what the elif statement is for: newMessage += character
What this does is add the character into its place, like put a question mark at the end instead of trying to move it 19 characters. Back to the characters that are in the alphabet: position = alphabet.find(character) – this creates a variable, called position, then it looks at our alphabet variable and finds the letter that was entered in. The next line, newPosition = (int(position) + int(key)) % 26, creates the new position of the character after it was moved. It turns the position variable into an integer (a number value) and adds it to whatever our key is. The % 26 keeps the moved position between 1 and 26, since that is the length of our alphabet. newCharacter = alphabet[newPosition] is indexing our new character – this just means that it goes to the location of the letter in our alphabet variable. Now, if you just wanted to move one character (there is no point, truly, except for when I was testing this) then you would uncomment #print('The new character is: ', newCharacter) because it controls one character. The last line (newMessage += newCharacter) moves all the characters to their places and forms the new message.

At last, we “print” (this means display, since we are not actually printing this onto paper) our new message like so: print('Your new message is:', newMessage). This displays “Your new message is:” and then the new message.

Cool! Now I have a message no one can read – how useful! There needs to be a way to decrypt it so it makes sense. That part is simple, since we just have to change a few things in our encrypting for loop.

decrypt = input("Please enter string to decrypt:")
dkey = input('Please enter your decryption key: ')
dnewMessage = ''
for character in decrypt:
if character in alphabet:
position = alphabet.find(character)
newPosition = (int(position) - int(dkey)) % 26
newCharacter = alphabet[newPosition]
dnewMessage += newCharacter
else:
dnewMessage += character
print("Your decrypted message is:", dnewMessage)

The variable names for the decrypting loop are basically the same as before, but with “d” for decrypt at the beginning.

newPosition = (int(position) - int(dkey)) % 26 The only difference in this line is that now we are subtracting the key, this way we go backwards to the original message. After all that, we simply print the new message with our print statement.

In my demonstration, I used the message “Hello there! Testing, testing!” to test my python cipher. The whole process of inputting my key, my message, getting a new message, and decrypting it, took 41 seconds. When I did it by hand with the cipher circle, the first word alone took 50 seconds! While it is not the most intuitive cipher, since you can clearly see the original message and the key above it, it still is a timesaver, – and most importantly, it was fun to make and taught me a lot of the math behind moving characters and manipulating strings.

Rock, Paper, Scissors!

I made a small and fun interactive game of rock paper scissors. It is a simple text-based game with a computer opponent. The computer’s choice is random which means that the player has a fighting chance. Here is my (again, thanks to WordPress, poorly indented) code:

from random import randint
import sys
import time
##########
while True:
player = input('rock (r), paper (p) or scissors (s)?')
if player == 'r':
print('O', 'vs', end=' ')
#createRock()
elif player == 'p':
print('__', 'vs', end=' ')
#createPaper()
elif player == 's':
print('>8', 'vs', end=' ')
#createScissors()
chosen = randint(1,3)
if chosen == 1:
computer = 'r'
print('O')
elif chosen == 2:
computer = 'p'
print('__')
else:
computer = 's'
print('>8')
##########
if player == computer:
print('DRAW!')
elif player == 'r' and computer == 's':
print('You Win!')
elif player == 'r' and computer == 'p':
print('You Lose!')
elif player == 'p' and computer == 's':
print('You Lose!')
elif player == 'p' and computer == 'r':
print('You Win!')
elif player == 's' and computer == 'r':
print('You Lose!')
elif player == 's' and computer == 'p':
print('You Win!')
##########
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
sys.exit("Goodbye")

As usual, a photo of the normal code as well as a video:
rpsindent

To break it down:
from random import randint
import sys
import time

The usual elements to import: random for the random choice of the computer, sys for end of the program(stopping the game), and time was added in case I wanted to implement it however it was not needed.

while True:
player = input('rock (r), paper (p) or scissors (s)?')
if player == 'r':
print('O', 'vs', end=' ')
#createRock()
elif player == 'p':
print('__', 'vs', end=' ')
#createPaper()
elif player == 's':
print('>8', 'vs', end=' ')
#createScissors()

This while loop controls the player’s choice of rock, paper, or scissors. Since my game is ASCII (American Standard Code for Information Interchange – think of it as normal text) I used letters and characters to model the choices of both players. O is meant to be a rock, __ is paper, and >8 is scissors. After the beautiful text representation, it displays “vs” (to show my choice vs the computer’s). end=' ' leaves a space after “vs” so we can display the computer’s choice on the same line as our’s.

For each choice, there is a #create[rock/paper/scissors]() this was a part of my previous design which did not work. My overly ambitious plan was as follows: I wanted to physically create a picture of the choice (like in my Turtle Race where there were pictures on screen) but it did not work out due to the nature of my basic knowledge on the matter. I left it in so I explain what it “does” – that is why there is a hashtag at the start of each statement, so it becomes a “comment” and the computer does not try to execute that line.

That line of code was calling a function. A function allows me to write a bunch of code in one place, and then “call” it later so I do not need to type it again. Defining a function always happens at the beginning of the code, like so, def myFunction(): def = define and then the parentheses are for putting in parameters if need be. After the colon, I can write whatever code I need and then later on I would simply type myFunction() to call the function.

With that out of the way, we still have not discussed how the computer decides:

chosen = randint(1,3)
if chosen == 1:
computer = 'r'
print('O')
elif chosen == 2:
computer = 'p'
print('__')
else:
computer = 's'
print('>8')

“Chosen” is a variable, just like in math, a variable can store some type of data for later. The data that chosen held is a random integer between 1 and 3; it is between 1 and 3 to easily pick 1 for rock, 2 for paper, and 3 for scissors. Next is an “if, elif, and else” statement – If is self explanatory (IF this happens then…) but elif simply means else-if so (IF the last statement did not happen AND this happened, do this). Else is the last option possible. Back to elif, the two things happening are as follows: If 1 was not chosen and 2 was, then that means that the computer picked paper (since it did not pick 1 and it did pick 2). The last option for the computer to pick is 3, so else is used because it is what is left over.

Okay, so the computer can pick a choice and so can the player, but all this means nothing if one choice can’t beat the other. The logic behind rock paper scissors is nice and simple (simple to implement but not so much to understand – how does paper beat rock??). To decide who wins, we add this snippet of logic into the code:

<code.if player == computer:
print('DRAW!')
elif player == 'r' and computer == 's':
print('You Win!')
elif player == 'r' and computer == 'p':
print('You Lose!')
elif player == 'p' and computer == 's':
print('You Lose!')
elif player == 'p' and computer == 'r':
print('You Win!')
elif player == 's' and computer == 'r':
print('You Lose!')
elif player == 's' and computer == 'p':
print('You Win!')

More if statements, yay! So “==” is an operator, meaning that it has math behind it. Now, “==” is different from one “=” because == is used for comparing equality whereas = assigns a value. For example, we could make a variable like so: myName = 'Liam' (Fun fact: single quote and double quotes can be used interchangeably meaning that ‘Liam’ is the same thing as “Liam” BUT, ‘Liam” does NOT work because they are not the same). So, now myName has a string (text) which says, “Liam” but if we created another variable, yourName, and made it equal to Fred, then: yourName = 'Fred', now we can compare them. myName == yourName is false because ‘Liam’ is not the same as ‘Fred’, to make it true we use this: != meaning is not equal to.

So for rock paper scissors, if the player’s choices == the computer’s, then it is a draw. Simple. Now, rock beats scissors so we need logic for that. elif player == 'r' and computer == 's':
print('You Win!')
so if I were to pick rock and the computer picks scissors, then it displays that I win. This is done for all possible combinations of moves and also displaying who wins/loses.

However all good things must come to an end, so after each game, the player is asked if he/she wants a rematch.

while True:
answer = input('Run again? (y/n): ')

Now a variable takes in input from the player (y or n) and then an if/elif statement determines how to handle the answer.

if answer == 'y':
break
elif answer == 'n':
sys.exit("Goodbye")

If the answer == (for comparing the value rather than assigning one) ‘y’ then we “break” meaning exit this current while loop, as a result, restarting the game. However if the answer is no, then the game quits with sys.exit("Goodbye") The only problem about this is that “Goodbye” is not always displayed – maybe the computer is just mad that it lost!

Racing Turtles!

I just discovered the greatest thing that Python has to offer: turtles!

With a little code, it was easy to draw a race track and then add turtles to race each other. The best part is that I set their speeds to random numbers so it isn’t always one turtle winning – a true race!
Heres my code (WordPress is not the most intuitive for putting source code into, so it does not recognize indentations in the code. It is not a problem for viewing, but it is if this were to be used from here):

 from turtle import *
from random import randint
speed(10)
penup()
goto(-140,140)
for step in range(15):
write(step, align='center')
right(90)
for num in range(8):
penup()
forward(10)
pendown()
forward(10)
penup()
backward(160)
left(90)
forward(20)
billy = Turtle()
billy.color('red')
billy.shape('turtle')
billy.penup()
billy.goto(-160, 100)
billy.pendown()
for turn in range(10):
billy.right(36)
bob = Turtle()
bob.color('blue')
bob.shape('turtle')
bob.penup()
bob.goto(-160, 70)
bob.pendown()
for turn in range(72):
bob.left(5)
Tim = Turtle()
Tim.shape('turtle')
Tim.color('green')
Tim.penup()
Tim.goto(-160, 40)
Tim.pendown()
for turn in range(60):
Tim.right(6)
jim = Turtle()
jim.shape('turtle')
jim.color('orange')
jim.penup()
jim.goto(-160, 10)
jim.pendown()
for turn in range(30):
jim.left(12)
for turn in range(100):
billy.forward(randint(1,5))
bob.forward(randint(1,5))
Tim.forward(randint(1,5))
jim.forward(randint(1,5))

The video of the race can be found here, since WordPress does not want to cooperate. Also, a picture of how the code should look like (with the proper indentations is below).
turtleindent

As usual, I started with importing the necessary modules: turtle (for the turtles and workspace to put them on), and randint (random integer for their speeds.

speed(10)
penup()
goto(-140,140)

This part simply tells the computer where to start the pen to draw the racing lines.

for step in range(15):
write(step, align='center')
right(90)
for num in range(8):
penup()
forward(10)
pendown()
forward(10)
penup()
backward(160)
left(90)
forward(20)

This for loop is used to draw the track lines one after another. The range is 15 because I wanted 14 lines going down (the “align=’center'” aligns the line numbers with the vertical lines). Normally, the lines go left to right so, to make them go up and down, I rotated the lines right 90 degrees clockwise. The next for loop inside makes the lines dashed – normally they are solid. So it draws a line, picks up the pen, draws the next below it, and so on. The final pen movements are to switch lines.

billy = Turtle()
billy.color('red')
billy.shape('turtle')
billy.penup()
billy.goto(-160, 100)
billy.pendown()

So, creating the turtles was easy because I just had to copy and paste one as many times as I desired. The first turtle, the red one, is named Billy. The blue is named Bob, the green one is named Tim, and the orange one is named Jim. Unlike drawing the lines earlier, we don’t have to “draw” a turtle with a bunch of lines because Python comes with a turtle preset (how unusual but awesome!). Billy.goto(-160, 100) is self explanatory: Billy, go to point (-160, 100)
The next chunks of code are the same as above, except the only difference is the speed of their turn at the star, their Y coordinates, and their colors.

for turn in range(100):
billy.forward(randint(1,5))
bob.forward(randint(1,5))
Tim.forward(randint(1,5))
jim.forward(randint(1,5))

The final part of my Turtle Race Python code is the actual movement of the turtles (it would be a lame race without this part). The rang of 100 is the distance of the track we made. “[name].forward(randint(1,5))” is saying “move [turtle name] forward at a random speed between 1 and 5.

The Turtle module of python was a lot of fun to make a basic race with! It also comes with other shapes besides turtles like cirlces, squares, and triangles. I want to use these shapes in the future to create something cool as well. Both Tkinter and Turtle are good for drawing, Tkinter is better for free hand in my opnion, but Turtle seems to be the right choice for animation because it feels more intuitive.

Back To Normal

In late March, I picked up a book called The Linux Bible by Christopher Negus. It is an in-depth (almost 1000 pages!) book all about Linux and how it works. Linux is a computer OS (like windows) except it has more freedom because it has a heavy emphasis on the command line and programming. Nearly every job in Information Technology requires an understanding of Linux and how to use it. I have been reading this book in all my free time and I have read about half of it so far.

I’ve learned things such as: installing Linux, customizing it to meet my needs, learning basic commands, and also how to manipulate it to do what I want it to do. Lucky for me, I had an old laptop lying around collecting dust; I grabbed it, followed the book’s instructions on where to download the ISO file and then installed it. An ISO is a disk image file, so that is what is burned to a CD (generally DVD’s) and then installed onto the computer.

The Linux Bible recommends using an OS called Fedora, a distribution of Linux (there are more than 1000’s of different “flavors” of Linux – simply different OSes that work for different things). Fedora is a free, Red Hat OS; Red Hat is a big name in the IT sector, they provide multiple different certifications which are necessary to get an IT job – they use Fedora and customs Linux distros to certify users on. Its 27 chapters cover everything from security to enterprise management to cloud servers.

Linux is arguably better than Windows in nearly every aspect. Since I enjoy gaming, I use Windows because Linux is not as good for gaming. If it weren’t for my desire to play video games, I would use Linux instead of Windows for all of my daily tasks. Linux can also run some windows programs, and those that it can not run have their own off-brand designed for Linux.  Linux is better for security research and overall experimentation in the cyber world.

My dream job is to become an Informations Security Analyst (basically an ethical hacker – a company gives me permission to find security flaws in their systems) and Linux is going to be critical to that. Linux also has an amazing amount of resources to learn to program, in my case, I can code Python using Linux. Doing this will allow me to both learn Python and learn how to use Linux for my future job.

I am currently working on a lot of small projects and games that I am making with Python. This is another benefit of Linux is that I can code on my new Linux machine and still be able to send it over to my Windows laptop and play with it on there. For my final presentation, I am thinking about presenting all of my projects and all of the code with it to showcase what I have learned.