Tips for programming are on How to Think about Programming.
I recommend using the
geany python IDE. Write code,
save it as a
.py file, then press
F5 to run it.
foo = bar(baz)is a code example which can be copy-and-pasted directly into a
.pyfile. Some of these examples will be an entire standalone file; other examples will be an exerpt which must be placed in the appropriate context.
By convention, the first thing to learn in a new programming
language is to print the text "
Although text isn't very exciting by itself, the ability to
output text is vital for debugging (fixing programs).
Most programming languages, including python, indicate text with
"double quotation marks": the first
" indicates the
beginning of text. The computer then treates everything until the
" as text.
This causes problems if you want to print an actual " symbol in the output. For that reason, we use escape sequences to represent symbols which are difficult (or impossible) to indicate with plain text.
In addition to telling a compiler how to create an executable file, source code should also tell future programmers why the code does what it does. If anything in the code is unclear, a programmer should add comments which explain the situation.
Printing text (complete example):
print "hello world!"
Selected escape sequences:
Sequence Name \n New line \t Horizontal tab \\ Back slash \' Single quotation mark \" Double quotation mark
# this is a comment print "hello" # print "this will not be printed"
Write a short self-introduction (not necessarily truthful!), and a list of items you would buy if given 1, 10, 100, or 1000 pounds. Example output:
Greetings! I am \Sir Percival\ of the Round Table, hailing from Vancouver, Canada. My fair city lies approximately 4,500 miles to the West. In my country, we say `eh?' a lot. Free money, you say? Well, let's see... Pounds Purchase 1 A packet of tea biscuits. 10 Second-hand DVDs of "Still Game", so I can learn Glasgow patter. 100 An external hard drive for my laptop. 1000 A visit to my family next Christmas.
Your program should:
\n \t \\ \' \"
(optional: make it funny. We'll like you more. You won't get any marks for being funny, but hey, you'll make a friend! Looking at these programming exercises gets really boring.)
Computers would be boring if they didn't do any computation, and variables make computation a lot easier.
Variables must be declared before you can use them. Unlike many other programming languages, python does not require that you specify whether the variable is an integer, floating-point number, string, or anything else.
Variables can be more than one letter long; in fact, this is very
heavily encouraged! Other than strictly mathematical variables
n, you should almost always
use long variables names. Use the underscore
join multiple words together.
Text variables are called strings, short for "a string of characters". Technically, they are stored as an array of characters, but that detail is not important to us.
x = 3 print "x is currently", x y = 4.001 print "y is currently", y print "Make that shorter: %.1f" % (y) print "Make that longer: %.8f" % (y) z = x/y z = x + z*y - y print "Why does z = %i ?\n" % (z) animal_name = "cat" cute_name = "kitty" combo = cute_name + animal_name print "We can do \"math\" on strings: %s" % (combo) print "We can print multiple", print "variables: %i %f %i %s\n" % (x, y, z, cute_name)
Save your introduction/story program from Exercise 1 with a new file name: we will be modifying it, but you don't want to lose all your hard work.
Modify the new version of your introduction/story so that your program:
(hint: converting units is an easy way to get some math in there. Change between miles / km, pounds / euros, pounds / kg, human years / cat years, etc. You may need to rewrite part of your self-introduction to introduce some units.)
d = d * 1.609344Instead, give them more descriptive names, like
distance_km = distance_miles * 1.609344
(optional: invent a new measurement (like "centi-flipsies") and convert into them.)
Programs would be pretty boring without user interaction. The easiest way to get information from the user is with the keyboard.
print "Enter an animal name:" animal_name = raw_input() print "You typed: %s" % (animal_name)
Reading numbers is slightly more complicated; you need to change the string into an integer or float.
print "Enter your age (as an integer):" user_input = raw_input() age = int(user_input) print "Enter a float:" user_input = raw_input() weight = float(user_input) print "You typed: %i, %f" % (age, weight)
Mad libs (similar to "ad-lib") is a popular party game in North America. Somebody writes a story, but removes a few nouns, adjectives, and verbs. Other people must supply words to replace them (often with a clue, such as "an animal name" or "a movement verb"), without knowing the context in which they would be used. The result is nonsensical and sometimes funny. For example:
One day, a ________________ went to _______ and _____________ a ______. name of animal place verb (past) noun (other people supply: "polar bear", "Russia", "ate", and "house".)
Write a program which implements a mad-lib game:
(optional: make it funny)
You are familiar with functions in mathematics -- you've handled functions like g(x) = x^2 + 2x - 3. In this case, the function returns a value. The returned value is computed based on the input. You have also seen functions with multiple inputs: h(x,y) = 5x - 6x + x*y.
We use functions like this in programming. We need to specify the number of input variables, do the math, then return the answer.
We also sometimes use functions which do not return any values -- these are useful if we want to repeat a few commands, or simply for program organization.
.pyfile") they are used.
Note that each function has its own scope of variables. In fact, you can re-use the same variable name in different functions!
Simple function. Note that functions must be indented with 4 spaces or a tab!
def g(x): return x*x + 2*x - 3 a = 3.2 b = g(a) print "g(%f) = %f" % (a, b) print "g(5) = %f" % (g(5))
def cat_years(human_years): y = human_years / 7.0 rounded_y = int(round(y)) return rounded_y def sum_of_squares(a, b): return a*a + b*b def p(years, c, animal): print "If I were a %s, I'd be" % (animal), print "%i years old.\n" % (years) print "The sum of squares", print "was %f units.\n" % (c) my_age = 18 x = 3.3 animal = "cat" years_a = cat_years(my_age) sum = sum_of_squares(x, 7.4) p(years_a, sum, animal)
As electrical engineering students, you are familiar with Ohm's Law (V = IR) and calculating the value of resistors in series (R = R1+R2) and parallel (1/R = 1/R1 + 1/R2). Consider the following circuit:
Write a program to calculate the overall current in this circuit.
parallel(...). A 4th function
parallel_three(...)is optional. Do not write functions like
r1=100; r2=200; r3=300; r4=400; r5=500; r6=600; r7=700;
(you may copy&paste this into your
The answer should be 124.6 mA.
r1=123; r2=234; r3=345; r4=456; r5=567; r6=678; r7=789;
The answer should be 107.6 mA.
(optional: you can call functions as inputs to other functions, i.e.
z = f( g(x,y), h(x,y) );Using this, calculate the current from voltage and Rx values in a single line.)
Move on to Lab 2
Unless otherwise noted, all materials on these pages are licenced under a Creative Commons Licence.