Asking for input
dialog.py
#!/usr/bin/env python3 food = input("What do you want to eat? - ") print("We don't have %s, we only have spam and eggs." % food)
Make the program executable and launch it as shell script
$ chmod u+x dialog.py $ ./dialog.py
read-file.py
#!/usr/bin/env python3 with open("data/history.txt", 'r') as hist_file: content = hist_file.read() print(content)
coin.py
#!/usr/bin/env python3 from random import random if random() >= 0.5: print("head") else: print("tail")
sort-file.py
#!/usr/bin/env python3 with open("data/history.txt", 'r') as hist_file: lines = hist_file.readlines() lines.sort() print(lines)
for elem in sequence
- iterate over elements in a sequence typefor.py
#!/usr/bin/env python3 with open("data/history.txt") as hist_file: lines = hist_file.readlines() lines.sort() for line in lines: print(line.strip())
while
- repeat a block as long as an expression is truewhile.py
#!/usr/bin/env python3 from random import random win_count = 0 while (random() >= 0.5): # head win_count += 1 print("head won %d times" % win_count)
sum.py
#!/usr/bin/env python3 def sum(*numbers): """Return the sum of the arguments.""" total = 0 for num in numbers: total += num return total print(sum(3, 5, 7.9))
random_student.py
#!/usr/bin/env python3 from random import choice class StudentPicker(object): def __init__(self, students): with open(students, 'r') as student_file: students = student_file.readlines() students = filter(None, students) students = [s.strip().split('\t') for s in students] self._students = ["%s %s, %s" % (s[0], s[1], s[2]) for s in students] self._initial_students = list(self._students) def pick_student(self): """ Return a student and remove that student from the list. """ try: student = choice(self._students) self._students.remove(student) return student except IndexError: return "no more students available; use 'reset' or 'quit'" def reset(self): self._students = list(self._initial_students)
matrix.py
#!/usr/bin/env python3 import numpy as np A = np.array((0, 1, 0, 2, 1, 3, 1, 0, 1)).reshape((3, 3)) B = np.ones(9).reshape((3, 3)) print(np.dot(A, B))
pdf.py
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab mu, sigma = 0.0, 1.0 fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(-4, 4.1, 0.1) y = mlab.normpdf(x, mu, sigma) l = ax.plot(x, y, 'r-', linewidth=1) ax.set_title(r'probability density function: $\mu=%f,\ \sigma=%f$'.format( mu, sigma)) ax.set_xlim(-4, 4) ax.set_ylim(0, 0.5) # plt.show() plt.savefig("data/density.svg") # also supports pdf, png, ...
shell.py
#!/usr/bin/env python3 import cmd import sys from random_student import StudentPicker class StudentPickerShell(cmd.Cmd): def __init__(self, students): cmd.Cmd.__init__(self) # initialize the base class self.prompt = "ST> " self._picker = StudentPicker(students) def do_quit(self, arg): sys.exit() def do_pick(self, arg): """Print a random student. The same student won't be selected again unless `reset` is called. """ print(self._picker.pick_student()) def do_reset(self): self._picker.reset() shell = StudentPickerShell("data/pioneers.tsv") shell.cmdloop()
qt.py
#!/usr/bin/env python3 import sys from PyQt4 import QtGui, QtCore from random_student import StudentPicker class StudentPickerWindow(QtGui.QWidget): def __init__(self, students, parent=None): self._picker = StudentPicker(students) QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Student Picker') pick = QtGui.QPushButton("Pick") reset = QtGui.QPushButton("Reset") textfield = QtGui.QLineEdit() self._textfield = textfield grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(textfield, 1, 0) grid.addWidget(pick, 1, 1) grid.addWidget(reset, 1, 2) self.connect(pick, QtCore.SIGNAL('clicked()'), self.do_pick) self.connect(reset, QtCore.SIGNAL('clicked()'), self.do_reset) self.setLayout(grid) self.resize(500, 50) def do_pick(self): self._textfield.setText(self._picker.pick_student()) def do_reset(self): self._picker.reset() self._textfield.setText("") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = StudentPickerWindow("data/pioneers.tsv") window.show() sys.exit(app.exec_())