Like A Girl

Pushing the conversation on gender equality.

Code Like A Girl

Ch 1 — Intro to Python: Writing Your First Program

Welcome back! By now, you should have installed Virtual Box and have Ubuntu 18.04 running on your virtual machine. Ubuntu 18.04 already has Python3 installed, so you don’t have to worry about that. You should also have Atom downloaded on your virtual machine. If you haven’t done these things, refer back to my previous article where I explained how to do these things.

Some Background on Programming

Assuming you may be an absolute beginner, let’s start by asking the question: What is programming? Programming is basically talking to your computer and asking it to perform certain actions. This is done through Terminal, in which you can directly write commands to your computer, as well as run programs you write in a text editor. The big issue here is that the computer doesn’t speak English, Spanish, or any language traditionally used to communicate between humans. Different programming languages like Python, C, Java, etc. have been created to develop complex programs, as well as perform simple commands that computers can understand. It’s common to be confused and frustrated when learning a programming language for the first time because it requires us to approach problems in a different way. In many introductory Computer Science courses, professors will ask students to explain how to make a peanut butter and jelly sandwich. The students will respond with simple commands such as, “open the bag of bread, then take out two slices, spread peanut butter on one slice, spread peanut butter on the other”, etc. The issue here is that they’re assuming the person listening understands that to spread the peanut butter, you need to open the jar, insert the knife, get some peanut butter, grab a slice of bread, and evenly spread throughout. When writing code, think of your computer as something that will only do exactly what you tell it to, in the order you tell it to. This takes some getting used to, but before you know it, you’ll automatically start thinking this way and your mind will be set to solve problems efficiently.

Writing Our First Program

When learning a new programming language, it’s traditional for the first program to be the “Hello World” program. This program prints out the outputs the words “Hello World” into Terminal. The book advises us to do a slight variation of this, but it’s still the same concept.

With Python, we can either write a program in a text editor and then run it on Terminal or we can use Python’s Interactive Interpreter and type commands directly in Terminal. First, we will write in the Python Interpreter. To do this, open Terminal, type in the following, and click enter:

Starting Python Interpreter
python3
Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

This is what should come up. We can now write directly into the Python Interpreter and if used properly, it should be able to run code one line at a time and in the order we write them. For example, let’s try the “Hello World” program.

Printing “Hello World” on Python Interpreter
>>> print("Hello World")
Hello World

Here we see the print() function. Anything inside the parentheses and between the quotes will display in the Terminal. If we leave it blank, it won’t print anything.

What is a String?

In this example, “Hello World” is the String being printed by the print() function. A String can be printed using single quotes (‘Hello World’) or double quotes (“Hello World”).

To use quotes inside of Strings, we can start the String with single quotes and have the double quote inside the String or vice versa.

>>> print('Hello, they call me "Gaby" around here.')
Hello, they call me "Gaby" around here.

Writing Code in Atom

Now that we’ve explored the Python Interpreter, we can start to write our code in the text editor and actually run it in Terminal. This way, we can write more complex code all in one place, rather than asking the interpreter to do what we want it to do, one line at a time.

To start, you should create a folder where you can save your code in order to keep it organized. It’s important to note the path to this folder because when you run your code on Terminal, you must be in the right directory to find the files.

Files Icon in Ubuntu Desktop

To create a folder, click the files icon on the left side of your desktop.

Creating a new folder

Next, click “Desktop” on the left side and then right click in the blank space. Select, “New Folder”.

Naming your new folder

Finally, give your folder a name and click “Create”.

Next, you can open Atom. For this tutorial and the ones to come, we will be using Atom as our text editor. A good tip for using Atom, when you create a new file, save it immediately. This way, it will color code your code (this is called syntax highlighting) and help with formatting (this will make more sense later).

Opening Atom

When you open Atom, click “File” on the top left corner and click “New File” or use the keyboard shortcut Ctrl + N to create a new file.

Save File

Next, click “File” again, but this time select “Save As” or press Ctrl + Shift + S on your keyboard to save the file in the folder you created.

Saving file in selected folder

In this screen, find the folder you created. I saved mine in the Desktop, so I selected “Desktop” then “Python Practice”. Next, I named the file on the top input box. When naming a Python file, you have to make sure you use the format “filename.py”. The .py at the end represents the Python file extension.

Now we can write the same program we wrote on the interpreter, but on Atom instead.

Hello World Program

I used the same print() function and entered a String between the quotes just like we did previously. You may have noticed there’s a blue dot on the file tab next to the name. This dot means that you edited the file and haven’t saved it. If you click on “File” and select “Save” or press Ctrl + S on your keyboard, it will save the file and the blue dot will go away. This is something important to do as you go because if you want to run your program and check if it’s working right, it will only run the last saved version.

Let’s try running this program now. Switch screens to Terminal.

As mentioned before, to run a program, we have to make sure Terminal is in the correct directory to find the file. To do this, we are going to type the following into Terminal and click enter. If you named your directory something different, then replace your directory path below.

cd Desktop/Python Practice/

Now let’s break this down, “cd” means change directory. If we were to type “cd ~” by itself and click enter, it would take us back to the home directory. In the commands above, I changed the directory to Desktop and the folder Python Practice inside the Desktop folder. To do this easily, first type cd. Then when you’re going to type Desktop, just type “Des” then hit tab and it should finish the word for you. Same with the next folder, type Python then hit tab, and it should finish typing it.

This can be used a lot, especially when you know the name of the file or folder you’re looking for and if you’re sure there isn’t another file or folder that could come up with that name. To learn more about the “cd ~” command, check out this article.

You may have also noticed the random backslash () after the word “Python” in the previous command. This character is used when writing code in Python and when typing in the Terminal. It is considered an escape character, meaning it causes the Terminal to ignore the following space as code. Instead, it treats it as part of the directory name. This is specific to the example above, however, backslashes can be used to escape other characters, but for brevity I’m just covering this example.

Changing directory and finding file to run

After you enter the above, it will change the directory and will now appear in bold blue letters as pictured. Since we are in the correct directory, we can run files in the Python Practice folder. To do this, you will type in the following and press enter (if you named your file differently, use filename.py as the format to run your program):

python3 helloworld.py
Hello World Program!

Yay! We wrote a program to print the words “Hello World!”. This might seem like it’s not a big deal, but this is the first step to writing many more complex programs that do so many cool things, I promise!!

Proper Coding Habits

Now that we wrote our first program, let’s talk about some proper habits to develop while writing code.

Comments

When you write any program, you should always start with a comment that describes the program. This is important because later on, when you have a million Python programs that are thousands of lines long, you might not remember exactly what it was for.

In addition, comments help other programmers understand your code. In the working world, developers have to modify other developers’ code. Imagine how hard this could be if their code is disorganized and has no comments explaining what it does. If you want to make a comment about a certain line or section of code, make sure to write the comment before the line of code you are talking about.

To make comments on your programs, type in “#” at the beginning of the line, and everything for the rest of that line will be considered a comment. Comments are ignored by the Python Interpreter and aren’t executed as code.

Example of comments in code

If you were to run the example above, it would only print the words “Hello World!” and ignore the comments. Try it!

# Hello World Program
# Prints the words "Hello World!"
print("Hello World!")

Now that we’ve learned a little bit about writing programs in Python, the Python Interpreter, and Terminal, I’m going to attempt and show the End-of-Chapter challenges provided by the book: Python Programming for the Absolute Beginner.

Challenges

Challenge 1

Create an error of your very own by entering your favorite ice cream flavor in interactive mode. Then, make up for your misdeed and enter a statement that prints the name of your favorite ice cream.

To start, I’ll open Terminal and start the Python Interpreter or Interactive mode and type in my favorite ice cream flavor.

Interactive mode error

As seen above, I typed in “chocolate” into the Python Interpreter and pressed enter. This created a NameError which means that I entered a Variable that hasn’t been previously defined. You can learn more about Python Debugging and errors in this article.

Now, let’s fix the error and instead print the name of my favorite ice cream flavor.

Printing the word “Chocolate” on Python Interpreter

This time, I wrote the following code to print the word “Chocolate”.

>>> print ("Chocolate")
Chocolate

To exit the interpreter, enter “exit()” and press enter.

Exiting Python Interpreter

First challenge done!

Challenge 2

Write and save a program that prints out your name and waits for the user to press the Enter key before the program ends.

The input() Function

To do this challenge, we’re going to learn about the input() function. The input() function is similar to the print() function because it outputs to the Terminal anything you write in between the parentheses and quotes, but it requires user input (typing something in and pressing enter) to move forward with the program or end the program if it’s the last line. Here’s an example:

Program with input() function
Hello World Program showing input() function
Hello World program after pressing enter

As you can see, this program didn’t end until I pressed enter. The first picture, shows the screen before I pressed enter and the second picture shows it after.

Now, let’s actually write the program the challenge asked us to.

Try it yourself!

# Name
# Program prints name and requires user input to end
print("My name is (insertyournamehere).")
input("Press the enter key to exit.")

Yay, it’s done!

Challenge 3

Write a program that prints your favorite quote. It should give credit to the person who said it on the next line.

For this challenge you can start by finding a quote along with the author.

# Favorite Quote
# Print quote and author on the next line
print('"Always code as if the guy who ends up maintaining your code will be a',
'violent psychopath who knows where you live."')
print("-John Woods")
input("Press the enter key to exit.")

Notice that the String in the first print() function is split into two with a comma. I used this feature because when I wrote the quote, the line was too long and splitting it into two lines makes the code easier to read. This is also an example of how to have quotes inside Strings.

When I run the program, it still outputs to Terminal all in one line because the comma just combines both Strings into one call of the print() function.

To get the author in the next line, I just had to call the print() function again in the next line with the String “-John Woods”. It’s good to note that if you wanted to add an extra line in between these two, you can add n at at end of a String before the end quotes. “n” means insert new line, for example:

# Favorite Quote
# Print quote and author on the next line
print('"Always code as if the guy who ends up maintaining your code will be a',
'violent psychopath who knows where you live."n')
print("-John Woodsn")
input("Press the enter key to exit.")

The only thing I changed in the code above is the “n” at the end of the quote and after the author’s name.

Using “n” to insert new line

This is useful to separate the output so it’s more organized and easier to read.

And… This is all for Chapter 1. You learned about the Python Interpreter, writing Python programs in Atom and running them in Terminal, some Terminal commands and syntax, Strings, the print() and input() functions, and some good programming habits!

If you want to see more, tune in for my next article on Chapter 2 in which you will learn more about Strings, Variables, more on the input() function, and doing math in your programs.

Follow me on Twitter @Gdijkhoffz for updates on my articles and cool programming stuff!

Thanks for reading 🙂