Python Introduction Workshop: Difference between revisions
(→Basics) |
No edit summary |
||
Line 20: | Line 20: | ||
# sys is the system library | # sys is the system library | ||
import sys | import sys | ||
# Read from stdin into a variable called instr | # Read from stdin into a variable called instr | ||
instr = sys.stdin.readline() | instr = sys.stdin.readline() | ||
# Print message w/ variable | # Print message w/ variable | ||
print 'Hello ' + instr + '.' | print 'Hello ' + instr + '.' |
Revision as of 11:00, 5 February 2016
Workshop
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 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.) Treat yourself well! 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
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
What to talk about...
- Variables (integers, arrays)
- Conditionals (if/elif/else)
- Loops (for, while)
- Functions (def function_name(args):)
- Exception handling? (try/catch)
- File I/O...reading and writing from files:
f = open('handd-book.wiki', 'w') # write img_file = open(filename, 'wb') # i think append? f = open('handd-book.wiki', 'r') # read