Chapter 1 Exercises
Exercise 1.1: C) Store information for the long term–even beyond a power cycle.
Exercise 1.2: A sequence of Python statements that have been crafted to do something.
Exercise 1.3: An interpreter reads the source code and interprets right away, translating one line at a time. A compiler needs the entire program file before running, translating from high-level language to machine level language and then putting in a separate file to execute later.
Exercise 1.4: A) The Python interpreter
Exercise 1.5: There is a syntactical error in the line that holds the reserve word, “primt” which should be written as “print”.
Exercise 1.6: B) Main Memory
Exercise 1.7: B) 44
Exercise 1.8: -Central Processing Unit: Like the human brain? or “The heart of (any computer)” (p.15) -Main Memory: Your short term-memory -Secondary Memory: Your long-term memory -Input Device: You ears when listening or putting food in your body -Output Device: Your mouth when speaking
Exercise 1.9: Check your “grammar” of the reserve words or legality of variables used in your program.
This above page is intended as a place for students to work out solutions and answers to the exercises from the textbook. Please do not post answers to exercises that are actual graded assignments.
Why We Program
Computers are very powerful and very simple at the same time. They can be given sets of instructions in human readable languages that can be translated into the computer’s native binary language. Python is one of those languages. The language of Python gives the user a simple way to program. Python can be considered an easy language used to program complicated things. This famous language was created by Guido Van Rossum.
Some nice quotes from our professor Charles Severance:
- “This is not a regular class. This is a class where you’re supposed to learn something.”
- “Humans are great at eliminating bad solutions really fast”
- “Maybe I’m talking to computers, maybe you are all computers. I’m certainly not a computer.”
- “Probably most of you said: “I don’t care. This is such a hard problem, it’s a stupid problem”
- “Computers need a strategy. We need to give them a strategy.”
- “Instead of thinking of the program Python is some kind of evil, demonic monster that hates you, think of it as a dog.”
- “Any questions? You can’t do questions!”
Windows/DOS Commands
These are commands that may be used in the default command interpreter, cmd.exe
, as well as Powershell.
- cd – display current directory. Short for “change directory”.
- cd .. – move up the directory tree one level. Doing this from C:\Users\JohnSmith\Desktop will take you to C:\Users\JohnSmith, for example.
- cd %userprofile%\Desktop – takes you to the currently logged in users desktop on most versions of Windows
- cd C:\Users\JohnSmith\Desktop – takes you to the desktop on Win 7 and 8. Replace JohnSmith with your logon or profile name.
- cd C:\Documents and Settings\JohnSmith\Desktop – takes you to the desktop on Windows XP
- cd \ – brings you back to the root of the current drive
- X: – takes you to the last used location on drive X (typically, use C: or D:). It defaults to the root directory if you have not previously cd’d to anywhere on that drive.
- dir – Display a list of files and folders, very fast.
- dir /p – Display´s long lists of files and folders per “pages”. Slower.
- dir /? – Shows commands for folders and subfolders in the current folder/directory.
- cls – Clear the screen
- Up arrow – display previous commands within that session. Enter to select the command or Escape to get back to the prompt
- Tab – Toggles through existing files and folders in current directory, will auto complete the typing of a file or folder name once the first letters are typed.
- dir > myfile – creates a text file named myfile containing the directory listing. To open it with Notepad, just type “Notepad myfile” at the prompt.
- exit – Closes the command window. It has the same effect that closing the window with the “X” button (at the top right corner).
- F3 – repeats previous command (i.e. if you typed “ping 10.10.10.10” and pressed Enter. It would show “ping 10.10.10.10” again without having to retype it.
Mac & GNU/Linux Commands
These are commands that may be used in a common command interpreter, bash
, which is installed by default on most Mac or GNU/Linux systems, but may not apply 100% in other command shells, such as fish
, or zsh
for instance.
- pwd – short for “print working directory.” Displays the directory you are currently in.
- cd – a quick change directory back to $HOME directory. Short for “change directory”.
- cd .. – move up the directory tree one level. Doing this from /home/johnsmith/Desktop will take you to /home/johnsmith, for example.
- cd $HOME/Desktop – takes you to the currently logged in users desktop on most versions of Mac & GNU/Linux
- cd ~/Desktop – takes you to the currently logged in users desktop on most versions of Mac & GNU/Linux
- cd /home/johnsmith/Desktop – takes you to the desktop on Mac & GNU/Linux. Replace johnsmith with your own user.
- cd / – brings you back to the root of the current drive
- ls – Display a list of files and folders, very fast.
- ls | more – Displays long lists of files and folders per “pages”. Slower.
- ls –help – Shows info about listing files and folders.
- ls -l – Displays a detailed list of files and folders.
- clear – Clear the screen
- Up arrow – display previous commands within that session. Enter to select the command or Ctrl-C to get back to the prompt (In some terminals the Up arrow is not correctly mapped, thus look for an alternative in your terminal documentation)
- Tab – Toggles through existing files and folders in current directory, will auto complete the typing of a file or folder name once the first letters are typed (in some terminal/shell sessions the tab is not working, please refer to the terminal/shell session documentation you are using)
- Ctrl+A – Go to the beginning of a line.
- Ctrl+E – Go to the end of a line.
- Ctrl+F – Character forward (walk in line by characters).
- Alt+F – Word forward (walk in line by words – if the shortcut is always used, you can try Alt+Shift+F or Alt+Win+F).
- Ctrl+B – Character backward (walk in line by characters).
- Alt+B – Word backward (walk in line by words – if the shortcut is always used, you can try Alt+Shift+F or Alt+Win+F)
- Ctrl+L – Clear screen. It clears all text above the actual line.
- Ctrl+D – Delete characters in current position.
- Ctrl+T – Transpose characters (change positions).
- Alt+T – Transpose words (change positions).
- Ctrl+K – Cut till the end of the line.
- Ctrl+U – Cut till the beginning of the line.
- Ctrl+W – Cut previous word.
- Alt+D – Cut next word.
- Ctrl+Y – Paste recently cut text.
- Ctrl+C – Delete whole line.
Python commands
- quit() or exit() -ends Python on Windows.
- ctrl + z – suspends python process on Mac and GNU/Linux, resume with fg command
- quit() or ctrl + D -Tells “End Of File” to Python on Mac and GNU/Linux.
- quit() or ctrl + C -Kills Python process on Mac and GNU/Linux.
Conditional Steps, repeated steps, loop
- Conditional Steps – if … elif .. else
if (expression): (command) elif (expression): (command) else: (command)
- Conditional Steps (Multi elif) – if … elif .. else
if x < 0: x = 0 print 'negative changed to zero' elif x == 0: print 'zero' elif x == 1: print 'single' elif x == 2: print 'double' else: print 'more'
- Repeated steps – while (Don’t forget to modify the variable used in the conditional, otherwise this will run forever!)
while i < 6: print "At the top i is %d" % i
- Repeated steps – another example
Assign a value to i which is greater than 2
while i > 2: print "Right now i is %d" % i i=i-1
- Loop – for
for (y) in (x): (command)
Here is an excerpt of my notes from the first week of class. Please build and tweak as you all see fit! ~ Kendra
3>’s ~ What’s next? (If you write it out here, the page puts it in a blue box without the symbol. It executes it.) Response from Scott: Thank you for sharing your notes! By the way, here’s a tip: If the wiki renders a section of what you typed differently from how you expected, it’s probably because what you typed contains special meaning within the Markdown markup language (similar to the concept of reserved words for Python). One way to work around this is to use the backslash escape character (“\”). For example, if you really want to display three right arrows in a row, you would type this: ‘\>\>\>’ which renders like this: ‘>>>’. Here is a link to a page that contains more examples of Markdown:http://www.unexpected-vortices.com/sw/rippledoc/quick-markdown-example.html.
Assignment Statement
x = 2
Assignment with Expression
x = x+2
Print Statement
print x
Atif : Reserved words rearranged in Alphabetical Order
I just rearranged reserved words in alphabetical order. Feel free to edit it, if there are any mistakes. I added a few more sections to the Notes.
There are reserved words that are a part of python language. Use these reserved words to instruct Python.
and as assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield
If you use the reserved words without meaning to, they will not throw off your intentions, but most likely they will cause error reports. You can create your own commands using variables.
I came up with a way to remember the 31 reserved words easily (for me). Everyone has their own types of mnemonic devices that work for them. If this is not helpful to you, please feel free to ignore it. I am sharing it in case it could be useful to anyone. I am new to programming. My groupings might not be logical to anyone else, but it worked for me.
I chunk the reserved words and just remember how many there are in each section.
5 two-letter words 6 three-letter words + 4 words. 5 other four-letter words 11 longer words strung in an ungrammatical but memorizable pseudo-sentence.
total: 31 words.
5 two-letter words
- as
- is
- in
- if
- or
6 three-letter words
- and
- def
- del
- for (“for” triggers its opposite, “from”, which somehow triggered the obvious computer operations): 1. from 2. break 3. return 4. print
- not
- try
5 other four-letter words (not including from) (put in an order that almost sounds like a sentence to me. What is exec elif? How do you pass with it? I don’t know, but it’s easy to remember.)
- else
- pass
- with
- exec
- elif
11 longer words in an ungrammatical pseudo-sentence. I know it doesn’t make sense, but it almost sounds like it could, so it made it easier for me to remember than alphabetical order.
finally assert global class raise, except yield while continue lambda import.
- finally
- assert
- global
- class
- raise
- except
- yield
- while
- continue
- lambda
- import
Just another creative way to remember 😉
Read this as a sentence a few times… If you are from finance background, the first sentence will be easy to remember although its final meaning is obscure..
” with global yield finally in break, assert and continue for import raise or try def return. while del exec (think of Dell Executive… lol…) is not from lambda class except elif, print pass as if… else… ”
All 31 reserved words are covered without repetition… there seems to be some meaning to the statements but… it is not so clear… 🙂
Indented ~ Loops and Conditional statements
Cody W’s Note for you!
I’d like to add that the METHOD our teacher is using for us to understand the material is amazing. Pay attention to that!
The mindset he is trying to teach makes absolute sense and I’m glad I am a part of the class.
Lecture Notes
- Computers are programmed.
- Programmers are people who write programs.
- A program is a set of instructions that tells a computer what to do.
- To learn to program, one must move from a user (on the “outside”) to the “inside” of a computer.
- One reason to learn to program is build stuff for people to use.
- Professional programmers build things for others to use.
- Script, software, code, and program are words that can be used interchangeably; they all refer to a set or sequence of stored instructions for a computer.
- Instructions need to be explicit because computers do exactly what we say to do and not what we mean to do.
Hardware Architecture
- CPU (central processing unit) – runs the program; not the brains exactly; very very fast
- RAM (random access memory) – main memory; fast, small, temporary storage; lost on shutdown or reboot
- ROM (read only memory) – secondary memory; slower, large, permanent memory; lasts until deleted; examples are disk drives and memory sticks
- input devices – used to give data to the CPU; keyboard, mouse, touch screen
- output devices – screen, speakers, printer, DVD burner
- network – retrieve info from network, but not always available; almost like a secondary memory, slower and less reliable
Python as a language
- Programs live in the main memory.
- The CPU pulls programs from the main memory.
- Computers do not execute source code, which is made up of language human programmers can understand.
- Computers execute machine code, which is made up of binary code; ones and zeros.
- The Python interpreter translates from the Python source code into machine code.
- Python is the language of the Python interpreter, and those who can converse with it.
- An individual who can speak Python is known as a Pythonista.
- Python was developed by Guido van Rossum, who was inspired by The Monty Python’s Flying Circus skits for the name.
Elements of Python
- vocabulary/words – variables and reserved words
- sentence structure – valid syntax patterns
- story structure – constructing a program for a purpose
- Reserved words – cannot be used as variable names/identifiers
Keywords in Python tutorial – Explains the usage of each reserved word.
and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print
- sentences – single lines of code
- paragraphs – multiple lines, or blocks, of code
Python Scripts
- Interactive Python is good for experiments and programs that are 3-4 lines long
- Most programs are much longer, so we type them in a file, and then tell Python to run the commands in the file
- As convention, the suffix “.py” is added to the file name to indicate it contains Python
- To run the program from the command window, remember to cd to the directory that contains the file, type the file name including “.py” (Just in case someone other than myself was running from the interpreter, hopefully, this will help.)
Interactive vs. Script
- Interactive – type directly into Python one line at a time and it responds
- Script – enter a sequence of statements (lines) into a file using a text editor, and then tell Python to execute the statements in the file
Program steps or Program flow
- Like a recipe or installation instructions, a program is a sequence of steps to be done in order
- Some steps are conditional – they might be skipped depending on the circumstances.
- Sometimes a step or a group of steps are to be repeated
- Sometimes we store a set of steps to be used over and over as needed in several places throughout the program
- Loops (repeated steps) have iteration variables (counters) that change each time through the loop and often go through a sequence of numbers
Type of Errors
- Syntax Error: it is a mistake made in the grammar, while writing a python statement. The line and character that Python Error indicates is usually the starting point, to figure out the syntax error.
- Logic Error: there is an error in the way python statement was written. Usually, it is related to the order of the words used in the statement.
- Semantic Error: The python statements are written correctly, but it does not perform the task it was it designed to do.
Download Resources
Here are web links to some of the software downloads relevant to this course.
- Python Tutor – Enter your code into here and watch how it executes step by step – http://pythontutor.com/
- Emacs, Great Editor supports Python syntax highlighting. Windows & GNU/Linux Versions: http://www.gnu.org/software/emacs/
- Text Editor: http://notepad-plus-plus.org/download/ (for Microsoft Windows only)
- Python: http://www.python.org/downloads/
- Python Portable (WinOS): http://portablepython.com/ (for Microsoft Windows only)
- Dr. Chuck’s resource: http://www.pythonlearn.com/install.php (Note – if you use the Microsoft Window’s Instructions, content is only covered for Windows XP, Vista, and 7. It is possible to extrapolate from these instructions how to download and access Python, Notepad++, and the Command Prompt in Windows 8, but may take a few moments.)
- Microsoft Visual Studio Code: https://code.visualstudio.com/ and then you can install the Python extension for syntax highlighting for your Python scripts.
- Microsoft Visual Studio Express: http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx has a nice Plug in for Python scripting(Python Tools for Visual Studio): http://microsoft.github.io/PTVS/
- Microsoft Visual Studio Community 2015: http://www.visualstudio.com/products/visual-studio-community-vs (for Microsoft Windows 7 Service Pack 1 to Windows 10 and server editions.)
- Sublime Text http://www.sublimetext.com/ (For Mac, GNU/Linux & Windows)
- TextWrangler: Programmer’s text editor http://www.barebones.com/products/textwrangler/ (For Mac)
- Interesting blog post if you’re interested in using vim on GNU/Linux: http://www.jeffknupp.com/blog/2013/12/04/my-development-environment-for-python/
- Free Python IDE PyCharm by JetBrains. The community version is free and it’s more than enough to complete the course.https://www.jetbrains.com/pycharm/download/
- Python extension for Chrome: Access Python within your browser. http://goo.gl/Vvml4T
- Repl.it, an online environment for interactively exploring programming languages, including Python (after following this link, to get to Python 2.x, on the main home page, click to expand Practical and choose just “Python” not “Python 3”): http://repl.it/
- Online IPython shell. http://www.tutorialspoint.com/ipython_terminal_online.php IPython is an alternative enhanced interactive shell for python with many neat features that don’t exist in the original python shell. Tutorialspoint site allows you to experiment with this shell(along with other shells for many other languages) without having to install anything on your local hard drive.
- Atom Editor, available for Mac OS X Mountain Lion or later, Windows 7 or later, RedHat Enterprise or Ubuntu GNU/Linux https://atom.io
- TextWrangler for Mac can be downloaded from the App Store – no need to download packages or install manually. TextWrangler at the App Store is for Mac OS X 10.8.5 or greater. If you have an older Mac, you’ll need to get an older copy of TextWrangler from the publisher’s website:http://www.barebones.com/support/textwrangler/updates.html.
Python bundles for MS-Windows
- Anaconda download link https://store.continuum.io/cshop/anaconda/ Anaconda include many libraries for Python such as SciPy, NumPy, etc. Anaconda installation does not affect other Python program installed in your computer because it does not change Windows registry. It is highly recommended to install Anaconda to your local directory such as C:\Users\<your user name directory>.
18:16, 4 June 2015 (UTC)1eafbe516789c6225a4bea5e70f1ce2c 18:16, 4 June 2015 (UTC) Interested in the history of software? I’ve been reading “Alan Turing: The Enigma” by Andrew Hodges and it’s been very interesting to learn a little about how people like Turing and John von Neumann thought about what it would mean to have a “machine” that can sit around and wait for instructions, and then with those instructions do almost anything. I know I’m not doing Hodges’ book justice in that single sentence; I’ve just been fascinated to consider a time when the notion of software or programming didn’t exist. If I were to condense it to its root, I’d say that the ideas developed from philosophy and mathematics, not engineering or other science. In any case, I highly recommend the book, although it is long and will take time and concentration to get through it. (Lee Katterman, Ann Arbor) 18:16, 4 June 2015 (UTC)1eafbe516789c6225a4bea5e70f1ce2c 18:16, 4 June 2015 (UTC)
Raspberry Pi
From Wikipedia: “The Raspberry Pi is a series of credit card-sized single-board computers developed in the UK by the Raspberry Pi Foundation with the intention of promoting the teaching of basic computer science in schools.”[1]
This board is a full computer built on a small PCB, designed to be maker friendly. The base “computer” is a board, a power adapter and a SD card with an OS installed. There are many different OS’s available to run this board, most of them based on Linux. Standard personal computer input/output peripherals can be used with it(depending on the model), such as: USB keyboard/mouse, HDMI video for a monitor, an RCA(composite video) for an analog video display, a wired network port, audio and a camera port. Other USB devices such as wireless networking and external hard drives may also be used.
The Raspberry Pi also has a General Purpose Input/Output(GPIO) header for lower level interaction with various components. These can be accelerometers, gyroscopes, motor controllers, LEDs, I2C and SPI communications, etc.
Raspberry Pi’s are used in various projects. They are used as the controllers for 3D printers, robots, home entertainment centers, autopilots for UAV/drones, game consoles, laptop computers, etc. Youtube and many maker-hacker blogs are full of projects featuring Pi’s. A Raspberry Pi can be a powerful tool to bridge the gap for those learning computer programming and interfacing with electronics.