Command Line & Python Basics
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 (maybe) used it to install Python 3, pip, 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 PowerShell (on Windows).
I’ve 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:
- 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 asls -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
orls -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 directorycd ~/Downloads
: takes you directly to your Downloads foldercd [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
andcd Desktop
are different (you probably want to use the latter).
Exploring Folders & Files
In class, we downloaded a file from Slack to test out our new commands! Extract the zip file, and then:
pwd
to see where you arels
see what’s there!cd ~/Downloads
to change directory into your Downloads foldercd class-01
pwd
to check you’re in the right place!cat [filename]
to view a file’s contents!- 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. (OS X ONLY)
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 thehead
command is structured directly above.
Treasure Hunt!
So we found an awesome treasure in class! The MOST IMPORTANT takeaway from the exercise was that you should use TAB to autocomplete folder and file names as much as possible. See above tips on using autocomplete/TAB.
- Navigate to where your downloaded (and hopefully extracted) zipfile is located.
cat instructions.txt
to see the treasure hunt instructions.- 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 on the command line.
Other fun commands
grep
: allows you to search for a specific set of characters inside of a file (OS X ONLY)grep [search term] [filename]
grep -i [search term] [filename]
: case insensitive searchgrep "[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
sls
is the PowerShell equivalent of grep (Windows ONLY)sls [search term] [filename]
sls "[search term]" [filename]
man [command]
: see the manual entry for that command. Ex:man wc
- use
q
to escape from the manual, because it’s horrible
- use
-
wc -l [filename]
: get the line count for the given file (OS X ONLY) measure -lines [filename]
: get the line count for the given file (Windows ONLY)
Piping a way of connecting different commands together on the terminal.
grep bugs [filename] | wc -l
: displays the line count of the output ofgrep bugs [filename]
(rather than the whole file)sls bugs [filename] | measure -lines
: Windows equivalent of above- More on piping.
How to write and run Python scripts
- Open up Atom and create a new file: File > Save “intro.py”
- On the command line,
cd
into the folder where you saved intro.py. - 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 python3 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.
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
orpython3 --version
to check - 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 = "Georgia"
print(name)
# This will not work:
print(name)
name = "Georgia"
- 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.")