Skip to content

Instantly share code, notes, and snippets.

@badlydrawnrob
Created November 6, 2016 19:15
Show Gist options
  • Save badlydrawnrob/1cb518cbc459f1509f1fbb2d11a9b502 to your computer and use it in GitHub Desktop.
Save badlydrawnrob/1cb518cbc459f1509f1fbb2d11a9b502 to your computer and use it in GitHub Desktop.
Learn Python the Hard Way

Python symbols

Python symbol Description
print print "Something". print "This", 25 the , allows us to join a string and another string, number or variable together. , also allows us to join things on the same line (space separated): print "this",; print "that".
""" Can be used as either a code block (wrap with three """ or to print a block of text print """)
== != Equal to, Not equal to
< > <= >= Less-than, Greater-than, less-than-equal, greater-than-equal
+= -= Original variable with + or - the value to the right of the symbol. E.g x = 1 so x += 1 is now equal to 2
; The semi-colon allows us to write commands on one line, e.g variableOne = 1; variable2 = 2
%d %s %r %f String formats. Integer, String, Raw, float (integer with decimal point)
% Set the string formats. print "%d" % 20 or number = 1; text = "string"; print "%d %s" % (number, text)
true or false Boolean operators
\ \n \t \ escapes a character, \n is newline, \t tab. There are quite a few more but find them when needed
int() float() For converting into integers or floated numbers (0 or 0.0). e.g. int(raw_input())
import x Generic import. i.e. import math => math.sqrt()
from x import y Import module from a library. from sys import argv
from x import * Imports all functions from module, but without the need for module prefix. i.e. from math import sqrt => sqrt()
argv Holds the argument variables. i.e. script, first, second, third = argv (doing this unpacks argv and assigns these variables to it)
open() Open a file. open("file.txt",'w') (there are various flags you can use)
read() Read the file open("file.txt").read() parameters are r, w, a as well as r+, w+, a+.
close() Close the file. You should always close the file, but if you use a variable such as read = open('file.txt').read() Python should automatically close the file once that variable has been used. When you're separating the open() and read() functions, you'd need to close the file after
seek() "Seek" through a file, so you can perform actions on it. Default returns beginning of the file
readline() Reads the current line, and sets next readline to read the next newline.
truncate() Delete file contents (not required if open(file,'w') parameter is used)
write() Write to the file
return Return something within the function for later use
*args Pass all arguments to the function (note the *)

Other symbols

These are from Codecadamy so just keep them in mind.

Python symbol Description
lower() upper() str() Like len() these perform actions on a string. convert to lowercase, uppercase or a string. e.g variable.lower() variable.upper() str(variable)
datetime from datetime import datetime and use now = datetime.now() to get current time/date. You could then grab now.year,.month,.day, .hour,minute,.second
not and or and checks if both statements are true. or checks if at least one statement is true. not gives the opposite of the statement. They are evaluated in this order: not, then and, then or (if you use parentheses you can execute in whatever order you like)

Python built in functions (no module required)

Python symbol Description
.upper() .lower() Text transform
str() Converts an object to a string
max() Returns largest item. Use on integers/floats, not strings
min() Returns smallest item

Python module examples

You need to import the math module first.

  • generic import: import sqrt = math.sqrt(x)
  • function import: from math import sqrt sqrt(x)
Python symbol Description
sqrt() math module function. Find the square root of a number

Notes

String notation and dot notation:

  • You use len(string) and str(object), but dot notation is "String".upper()
    • This is because dot notation only work with "Strings"
    • Whereas other formats (like len()) work with other data objects

Generic, Function and Universal imports

  • generic import: import sqrt => math.sqrt(x)
    • Always prefix the function with the module name
  • function import: from math import sqrt => sqrt(x)
    • You can be more specific. No module prefix.
  • universal import: from math import * => sqrt(x)
    • Not a good idea to use this incase of function naming clashes (module vs custom)

README

Terminal commands

Basic commands:

Terminal command output
pwd Print working directory
hostname My computer's network name
mkdir Make directory
cd Change directory
ls List directory
rmdir Remove directory
pushd Push directory
popd Pop directory
cp Copy a file or directory
mv Move a file or directory
less Page through a file
cat Print the whole file
xargs Execute arguments
find Find files
grep Find things inside files
man Read a manual page
apropos Find what man page is appropriate
env Look at your environment
echo Print some arguments: echo "This is a test file." > test.txt creates a file with content.
export Export/set a new environment variable
exit Exit the shell
sudo DANGER! become super user root DANGER!
Writing with VIM
vi file Open file with vi filename.txt Edit: i Exit edit: esc; Save: :w Quit: :q Save + quit: :wq

Some nice extras for speed

Terminal command output
cd [..] [../somewhere] [~/Path/From/Home] Also tab for quick find
&& or ; Multiple commands, e.g. mkdir 1 && touch 1/ex1.py

Python commands

Terminal command output
Working with files
python Run python python ex1.py
pydoc Generate documentation pydoc raw_input (q to quit)
open Open file and create file object: open(file, r) (default) opens in read mode, w write mode, a to append to file. Other methods are available.
read Reads the contents of the file
close Close file once you're done with it
readline Read just one line of file
truncate Empties the file Careful: erases contents!
write('stuff') Writes "stuff" to the file
Python interpreter
help(function) Quick help guide, e.g: help('len') — press q to quit
CTRL + C Quit any running python script with ctrl-c

Some notes on oddities:

  • Python uses the Pemdas system of mathematics order.
    • Parentheses first
    • Exponents (ie Powers and Square Roots, etc.)
    • Multiplication and Division (left-to-right)
    • Addition and Subtraction (left-to-right)
  • Modulo returns the remainder of the division
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment