Coding Basics
There are only two kinds of languages:
the ones people complain about and
the ones nobody uses. ECE 101
— Bjarne Stroustrup Week 2
Michael Huang
Outline
• Intro to programing
• Basics of operations
• Variables and assignments
• Different programming environments
• Basic Unix understanding and usage
• Function definition and invocation
ECE 101 -- Week 2: Coding Basics 2
Demo
>>> prompt
3**4 input
81 response
print ( “%.2e” syntax highlight
• Interpreted as you enter expressions (more next)
• Looks like a more advanced calculator
• Can do basic as well as advanced/custom operations
• Results can be stored to named variables and constants
ECE 101 -- Week 2: Coding Basics 3
What is an App: Compiled vs. Interpreted Programs
• To the user, an app (application, executable program) is associated with the
icon you tap on your phone/tablet
• A program is a creative product that often interacts with users (through
display and input devices) to get input related to a problem, solves the
problems, and produces some output
• What you just saw are a few programs, albeit very short ones
Ø They take some input (e.g., typing “3**4”) and produce outputs (e.g., “81” printed)
Ø They look semi-understandable to an untrained human, but utterly alien to the
computer and requires translation into a fundamental level code that
micromanages the switches inside (we’ll get to the switches in the 2nd part of the course)
Ø There are two basic ways to do this translation: interpretation or compilation
• Interpretation: translation on the fly, statement by statement
Ø Easy to play with at the beginning of learning but tends to be inefficient
• Compilation: a pre-pass to do a whole-program translation from high-level
language (closer to human) to “machine code”
Ø Gets a higher quality product, but more steps to get a program to run
ECE 101 -- Week 2: Coding Basics 4
A Tale of Two Programs
• The traditional first program is to print “Hello World!”
• With python, you can directly type the program up,
• Or save the program in a file to be loaded later
Ø “>>>” is the prompt of the python interpreter
Ø “imac:~%” is the prompt of the OS (as configured on my desktop)
• With C, you need to first save the program in a file
• Then compile it into another file, which is executable
Ø If there are errors, you have to fix all, before the code can run (in contrast, errors
in interpreted programs are reported only when the statement runs)
• Finally, the program can run by itself
Ø It doesn’t need an interpreter as python codes do
ECE 101 -- Week 2: Coding Basics 5
Illustration of the Two Environments
Coding Compiling Running
1
Compiled execution
A Running compiler 2 Running executable
3
B 1 2 3 4 1 2 5 6 1 2 3 1 2 5 6 1
4
C 5
6
Statements in
high-level Instructions in
language code machine code/
executable
Running interpreter interleaved w/ interpreted code
Interpreted execution
A 1 2 3 4 1 2 3 4 1 2
B
C
1 2 3 4
Machine code generated and executed on the fly
ECE 101 -- Week 2: Coding Basics 6
That Said …
• It is not a language characteristic but an implementation decision
Ø Though most languages tend to have one type of implementation
Ø We say “python is an interpreted language” as a short and imprecise form of
“python is a language that is typically implemented using interpretation”
• The distinction is operational so that you know what to do to run code
• Even then the distinction is not a strict one and may disappear in the future
(or reduced to irrelevance at any rate)
ECE 101 -- Week 2: Coding Basics 7
Basic Operations
• You can type expressions and get them evaluated
Ø E.g., 3*(4+5), 3e8*1e-9, 15//4 (for divide and integer round down), 43%3
(modulo), 4<<1 (left shift), etc.
Ø Any python document/site will give a complete list of native operations.
Ø But more importantly, a programming environment gives you custom functions
and libraries of previously created functions. E.g., import math gives you the
math module (for now don’t worry too much what import means), and you can
then do [Link]([Link]), [Link](4), [Link]([Link])
² To avoid repeatedly typing [Link], you can use: from math import pi, etc.
and directly use sin(pi)
• You can also store a value for later retrieval and repeated use
Ø You can think of that as the memory function of a calculator or symbolically
representing a common value as [Link]
Ø These symbols are called variables and can be assigned to with “=”
Ø E.g., x=2*[Link], diameter=4 (let diameter be 4)
Ø Short-hand update assignments: x+=4 (i.e., x=x+4)
Ø Variables names must be a letter (underscore “_” also counts) plus letters or
numbers and not a keyword/reserved word (e.g., import)
² Should be descriptive (NumCars is better than zP8_kj)
ECE 101 -- Week 2: Coding Basics 8
Operator Precedence: Order of Evaluation
• Given a sequence of operation, how does python (or any other programming
language) evaluate it?
Ø There are obvious precedence (* and / higher than + or -)
Ø For ambiguous ordering, use parentheses: (4>>2)+5
Ø Language specification has the complete ordering
ECE 101 -- Week 2: Coding Basics 9
Various Environments for Programming
• Command line
Ø Typically installed with UNIX variants (Mac OS, Linux etc. – a bit about it next)
Ø Two versions of python exist and you have to choose the right command (Python
3 is intended to change things without worrying about backward compatibility –
code written for python 2 would not necessarily work under python 3)
• Integrated development environments (IDEs)
Ø More GUI elements, e.g.,
² Syntax highlighting: different colors for different elements of programs such as
keywords, strings)
² Extra window for debugging monitoring
Ø A variety of them available, each with a different interface
• Online environment (interpreter housed on a website)
Ø Our recommended interactive textbook @
[Link]
ECE 101 -- Week 2: Coding Basics 10
A Brief Introduction to UNIX
• Created by Ken Thompson in AT&T’s Bell Lab
• Written mostly in C, thus more easily portable to different platforms
• Robust, well architected and tightly coupled with the internet
• Most widely used OS today (Android, iOS, Mac OS, Linux, AIX, Solaris…)
• With the POSIX standard, there is significant inter-operability across variants
• The only environment available in certain sectors (e.g., high-performance computing)
• As an electrical/computer engineer, not a bad idea to be familiar with it
Ø The GUI of OS varies depends on implementation and evolves somewhat quickly
Ø The underlying command interface is very stable
Ø We’ll get into it a bit and use it throughout the semester in the lab
Ø The programming practices do not necessarily depend on it, but it does help
quite a bit to gain a deeper understanding of the entire system – as you are
programming the OS environment for your work
ECE 101 -- Week 2: Coding Basics 11
A Few Handy Commands to Navigate the File System
• The storage system houses a large number of files including system files (e.g., all the
common programs) and user files (e.g., your homework and photos etc)
• Files are organized under directories (folders), which form a tree with a root
• A file or a directory is uniquely identified by its path from the root, e.g., /usr/bin/python
Ø Files belonging to a particular user are customarily housed under that user’s “home”
directory (e.g., /Users/Tom), which has a shortcut name “~” (e.g., ~/[Link])
Ø All directories except root has a parent directory named “..”
Ø At any given time in your terminal, there is a current/working directory “.” – any reference to
a file name without a path prefix is implicitly referring to the current directory
• Basic shell commands (all of them have options and many more ways of usage, see man)
Ø ls: list content in a directory, e.g., ls /usr, ls ~, ls .., ls
Ø pwd: print working directory
Ø cd: change working directory, e.g., cd ..
Ø mkdir: make a subdirectory, e.g., mkdir ~/ECE101
Ø rmdir: remove a directory (has to be empty)
Ø rm: remove a file, e.g., rm ~/ECE101/[Link]
Ø cp: copy, e.g., cp Lab1/[Link] Lab2/[Link]
Ø mv: mv a file/directory, e.g., mv ~/Lab1/[Link] ~/Lab2 (moves [Link] without renaming it)
• GUIs replace the shells to provide an intuitive but perhaps slower ways of doing these things
ECE 101 -- Week 2: Coding Basics 12
Saving and Loading Programs in Files
• In the terminal environment, the best way is to use a text editor to write and
save the program you write and run the program with “python [Link]”
Ø You can always copy paste code already typed into an editor
Ø In the terminal shell, a quick way to save copied content into a file is
Ø cat > [Link], then paste, and press Ctrl+D
Ø Note: some editors are a bit too smart for programming purposes as they will
replace/insert unwanted things such as changing quotation marks into prettier
versions (“ ”) that are actually different symbols and not recognized by python
• In IDLE, you can use the File menu to load a previously edited program into
the IDE
• In the interactive textbook site, every little code box allows you to save a
copy of the code typed in that box
• Now we are ready to write some small programs
ECE 101 -- Week 2: Coding Basics 13
A Slightly Longer Calculation: Revisiting the 60 Guilders
• Let’s calculate the hypothetical alternative return of the 60 guilders ($24)
• We can type 24*(1.08**(2014-1626)), but this is neither very readable
nor reusable to do a similar computation, so let’s improve
• We can define a custom function with variable inputs
def compounding (principal, interestRate, years):
total = principal * (interestRate ** years)
print (“Total is %.2e” % total)
compounding (24, 1.07, (2020-1626))
Function definition starts with keyword “def”, followed by
name of function, input parameter list, and a colon
Python uses space for scoping: the indented part indicate the
body of the function. This was intended for better readability.
The un-indented part indicated the outermost code or the starting
point. Here, it’s a simple invocation of the function
ECE 101 -- Week 2: Coding Basics 14
More About Functions
• Functions are not just convenient, it’s an essential component in system
building: it provides abstraction and reuse
• Python allows named parameters: you can use the name to assign value
and not by matching order (unnamed parameters must still be ordered and
before named parameters)
def compounding (principal, interestRate, years):
total = principal * (interestRate ** years)
print (“Total is %.2e” % total)
compounding (24, years=(2020-1626), interestRate=1.07)
• Python also allows default values for parameters (only the end of the list)
and (only) those parameters can be omitted during invocation
def compounding (principal, interestRate=1.07, years=10):
total = principal * (interestRate ** years)
print (“Total is %.2e” % total)
compounding (24)
ECE 101 -- Lecture 3: Functions 15
Syntax Errors
• You have to write statement in certain ways – different from natural
languages where the receiver is expected to be able to tolerate some errors
Ø When you play around with codes, especially at the beginning, you’ll see a lot of
“complaints” from the interpreter or the compiler
Ø Some are easy to understand (1st example below), others may be less so (2nd)
Ø No quick way around it, go through trial and error and you’ll be fine
def compounding (principal, interestRate=1.07, years):
^
SyntaxError: non-default argument follows default argument
File "[Link]", line 6
compounding (24, years= (2014-1626)), interestRate=1.07)
^
SyntaxError: invalid syntax
ECE 101 -- Lecture 3: Functions 16
Summary
• Basics of operations
• Variables and assignments
• Different programming environments
• Basic Unix understanding and usage
• Function definition and invocation
ECE 101 -- Week 2: Coding Basics 17