Housekeeping

  • HW: It doesn’t matter if you don’t finish the hw, but do as much as you can!
  • Schedule: Note that Data & Databases will run on a slightly different schedule than Foundations (due to upcoming holidays).

The Command Line

The command line is a more intimate way of interacting with your computer (than say, Finder on Mac or Explorer on Windows). We’ve already used it to install Python3, pip3, virtualenv and virtualenvwrapper during orientation (if you haven’t done that, go do that now). You might also hear folks referring to the command line as the shell, Terminal (on Mac) or Babun (on Windows).

Soma has compiled a ton of common shell commands! I won’t repeat them all here now, but remember pwd, ls, cd [foldername], cd .. are really helpful when you are moving around your computer using the command line. A few other things to keep in mind:

  • rm -rf: this deletes everything on your computer! So don’t use this. WHY AM I EVEN REPEATING IT HERE?
  • You can add flags to commands to instruct shell to do specific things or structure its output in a specific way. A few helpful flags to add to the ls command:
    • -l: displays more information about your files and folders (you’d enter it as ls -l in your shell)
    • -h: makes the displayed filesize numbers human readable!
    • -a: all, shows you hidden files, usually important stuff your computer doesn’t want you to deal with.
    • You can use a bunch of flags together ls -lh or ls -lha
  • A few helpful cd commands:
    • cd .. moves you “up” one directory
    • When you see ~ in terminal, it means you’re in your home directory.
    • cd ~: takes you directly to your home directory
    • cd ~/Downloads: takes you directly to your Downloads folder
    • cd [drag the folder from Finder into Terminal]: it’ll autocomplete the path to that folder! This only works on Macs.
  • If your command line is running something it shouldn’t be, use Ctrl+C to escape/exit.
  • clear will do exactly as it sounds; your Terminal/Babun shell will be cleared of all commands and output.
  • File and folder names have to be typed exactly as is! cd desktop and cd Desktop are different (you probably want to use the latter).

Exploring Folders & Files

In class, we downloaded a dictionary zipfile to test out our new commands! Extract the zip file, and then:

  1. pwd to see where you are
  2. ls see what’s there!
  3. cd ~/Downloads to change directory into your Downloads folder
  4. cd dictionary
  5. pwd to check you’re in the right place!
  6. cat [filename] to view the file contents!
  7. Typing the file name is super annoying though - write cat [first letter(s) of your filename] and then hit TAB to autocomplete the filename.

TIP: If pressing TAB does not autocomplete your folder or filename, then you may need to enter a few more letters to disambiguate which folder or file you mean.

Also, make sure that autocomplete gave you the ENTIRE folder or file name. Sometimes, you will have to enter the next letter hit TAB again, especially if there are spaces in your filename.

DON’T PUT SPACES OR APOSTROPHES IN YOUR FILE NAMES.

Besides using cat to see the entire file, you can also take a peak at the beginning or end of a file.

  • head -n 20 [filename]: see the first 20 lines; change the number to see more or less lines.
  • tail: use tail to see the end of the file; structure the command the way that the head command is structured directly above.

Treasure Hunt!

Okay, so there was no treasure in our downloaded zipfile, but the MOST IMPORTANT takeaway from this exercise is that you should use TAB to autocomplete folder and file names as much as possible. See above tips on using autocomplete/TAB.

  1. Navigate to where your downloaded (and hopefully extracted) zipfile is located.
  2. cat instructions.txt to see the treasure hunt instructions.
  3. You’ll notice that the folder and file names are cuh-razy. Use TAB/autocomplete to get your computer to do all the hard work for you.
    • \ indicates that the space character is actually part of the name you’re looking for! The \ is an escape character – because spaces can mean other things on Terminal, using the \ before a space lets Terminal know that you really mean it! You’ll see this structure appear with other “special characters” as well (not just spaces).

TIP: Use ↑ and ↓ on your keyboard to move through the other commands you’ve typed into Terminal/Babun.

Other fun commands

  • grep: allows you to search for a specific set of characters inside of a file
    • grep [search term] [filename]
    • grep "[search term]" [filename]
    • grep -r "[search term]" [directory or folder name]: this searches all the files in the specified directory for your search term
    • Note that the search terms are case-sensitive
  • man [command]: see the manual entry for that command. Ex: man wc
    • use q to escape from the manual
  • wc -l [filename]: get the line count for the given file

Piping a way of connecting different commands together on the terminal.

  • grep " n." [filename] | wc -l: displays the line count of the output of grep " n." [filename] (rather than the whole file)
  • More on piping.

How to write and run Python scripts

  1. Open up Atom and create a new file: File > Save “intro.py”
  2. In Terminal or Babun, cd into the folder where you saved intro.py.
  3. Type mkvirtualenv introductions into your shell.
  4. Type workon introductions.
  5. Let’s edit intro.py in Atom so that our script actually does things!

Remember: We use # to write comments within our code.

Printing

print("Hello world")
print('Hello world')
# Double-quotes and single-quotes work the same in python
# But don't mix them!


# These print statements won't print a space between "Hello" and "World"
print("Hello" + "world")
print("Hello", "world")

# These will:
print("Hello" + " world")
print("Hello", " world")

Arithmetic & Casting

# This will make your computer mad because it can't add a string to an integer.
print('10' + 10)

# Strings and integers are different data types!
# Cast your string into an int(ger)
print(int('10') + 10)
# Output is 20.

# Or cast your int into a string:
print ('10' + str(10))
# Output is 1010

print('Hello' + str(10))
# This gives you "Hello10" back.

Variables & Taking Input

# Store things in variables!
name = "Dennis"
print("Hello, " + name)

# Don't use spaces in variable names
last_name = Soma # This is okay
last name = Soma # This will not work
lastName = Soma # Works!


# Store user input in a variable!
name = input("What's your name?")
print("Hello, " + name)

If-Statements

year_of_birth = input("What year were you born in? ")
age = 2016 - int(year_of_birth)
print("You are roughly " + str(age) + " years old")

# Sample if-statement
if age == 33 or age > 100:
    print("So cool!!!! You get a free beer unit!!!!")
elif age >= 21:
    print("Here's your beer unit")
else:
    print("Nope, sorry")

print("Goodbye")

# Note that we don't use '=' in comparisons, we use '=='
# Indentation is meaningful! If something is not indented underneath the if/elif/else, it isn't associated with that particular condition.
# Only the first condition that is TRUE will be run -- it doesn't matter if another condition is also true further down the if-statement.

Now, type python intro.py into your shell to run your very first Python script! If there are errors in your Python script, don’t worry! Your shell will definitely let you know.

deactivate to shut down your virtual environment when you are done.

Common Errors

TIP: Pay attention to the errors you get when you run your Python script! Terminal/Babun will probably tell you exactly where you went wrong (the line number or character nearest to the error).

  • Make sure you have spelled and capitalized everything correctly!
  • Make sure you’re in the correct folder; pwd all the time/pay attention to the folder Terminal/Babun says you’re in.
  • Make sure you saved your Python script where you think you did.
  • Make sure you’re running Python 3! Run python --version to check
    • If you’re not running Python 3, you probably forgot to start up your virtual environment mkvirtualenv [name]
    • You can name your virtual environment anything you want.
    • When you’re done, close out of your virtual environment using deactivate
  • When writing code, make sure you don’t call a variable before you tell your code what the variable is! For example:
# This will work:
name = "Rashida"
print(name)

# This will not work:
print(name)
name = "Rashida"
  • In if-statements, make sure you’re ending ALL conditions with :
if n < 5:
    do something
else:
    do something different
  • In if-statements, make sure you are indenting correctly! If your “do something”’s aren’t indented underneath your condition, the logic of your code may not be what you think it is!
# These two if-statements will print different things!

# If-statement #1
if n < 5:
    print("n is less than 5.")
else:
    print("n is greater than 5.")
    print("Pick a smaller number.")

# If-statement #2
if n < 5:
    print("n is less than 5.")
else:
    print("n is greater than 5.")
print("Pick a smaller number.")