Python Introduction Workshop

From Hackers & Designers
Revision as of 13:11, 5 February 2016 by JBG (talk | contribs)

Workshop

Please keep in mind that Python cares about whitespace (spaces, returns, etc...), if you just paste the code in, be aware of what spaces you are also pasting in... ;-)

1.) Create a file

$ nano myprog.py

2.) Add the following line

print 'Hello World!'

3.) Save the file and exit. Ctrl+O, Ctrl+X

4.) Run the program.

$ python myprog.py

5.) Add a comment to the top of your program. Comments are to help people read your program.

# Program by [username]

6.) Create a variable to store input into the program.

# Import adds a library (addition functionality) to your program
# sys is the system library
import sys

# Read from stdin into a variable called instr
instr = sys.stdin.readline()

# Print message w/ variable
print 'Hello ' + instr + '.'

7.) Run the program, this time with input.

$ whoami | python myprog.py

8.) Use the input to alter the output, before your print message add:

if instr == 'jbg':
  instr = 'Programmer'
else:
  instr = 'Writer'

9.) Save and run.

10.) It doesn't work! This is because there is actually a return character in the string. Change the following:

instr = sys.stdin.readline().strip()

11.) Save and run.

$ whoami | python myprog.py
$ echo 'Ray Bradbury' | python myprog.py

12.) Create a new program (myprog2.py) which loops through all the lines coming from stdin.

 import sys

 for line in sys.stdin:
   print line.strip()

13.) Run it.

$ cat /pub/451.txt | python myprog2.py

14.) That's a lot of lines, how many exactly?

$ cat /pub/451.txt | python myprog2.py | wc -l

15.) Let's store those lines in an array.

import sys

lines = []
for line in sys.stdin:
  lines.append(line.strip())

print 'Stored ' + str(len(lines)) + ' lines.'

16.) 451 remixed via a function. Add the following to the top of your program.

def remix(lines):
  lines = reversed(lines)
  for line in lines:
    print line[::-1] # This is extended slice syntax. It works by doing [begin:end:step]

17.) Run it.

$ cat /pub/451.txt | python myprog2.py | more

18.) Try other splits.

print line[0:10]
print line[10:15] + line[0:10]

19.) A more powerful remix.

$ python /pub/shaney.py /pub/451.txt

20.) Scrape the internet into a file.

$ python /pub/scraper.py > internet.txt

21.) Eat the internet w/ eat.py

import sys

def eat(lines):
  new_lines = []
  for line in lines:
    if len(line) > 0:
      new_line = line[0:len(line) - 1]
      print new_line
      new_lines.append(new_line)
  return new_lines

lines = []
for line in sys.stdin:
  lines.append(line.strip())

while len(lines) > 0:
  lines = eat(lines)

22.) Run it.

$ cat internet.txt | python eat.py