Don't like this style? Click here to change it! blue.css
For my solution to the daily challenge I learned how to synthesize music in python by using PySynth to read sheet music encoded in abc notation (a cool way to store music as text).
I wrote this C scale in abc notation and used python to create a .wav file. Here it is:
For a cool python program that I would be inspired to write I have this (which I worked on Friday and will work on this next Friday):
Write a stock screener which emails me a list of companies most likely to make a move within the next couple of hours. This should be because of information in the options chain.
So far we have run some commands in python, several different ways. In your labs you also asked a user for input and learned how to cast a string as an integer.
Today I would like to have you write a function which is a way of executing a set of commands as a group. You can execute a function on various inputs and at various times.
An anecdote from real life: I received an email this weekend from a student that looked like this:
Hi, this is John Doe, from section 060 of your Chem 103 class. I was just contacting you to let you know that I won't be able to attend class tomorrow, due to an emergency … I probably won't be going to your class anytime soon. I was extremely excited for your class, its too bad I won't be able to attend it. Thanks for teaching, and I'm sorry I can't learn from you anymore.
My apologies, John Doe
Of course I told the student that I was not a chemistry teacher, and he said "Oh man, I'm sorry. I was copy pasting because I'm lazy, I am in one of your classes sorry."
With permission, I'm using this as a great way to look at functions and variables in practice.
Mini-Task 1: What parts of this message must change from course to course? Can you add the professor's name in as a variable? How many pieces of information do you need?
Let's look at a simple homemade function:
Easy-Task 2: What does this function do?
Mini-Task 3: Can you change it to a function exponent(base, power)
which takes in a base and a power and returns base
raised to the power
? For instance
exponent(2, 4)
should return 16
.
So lets break this down a little bit:
def
lets python know that we are defining a function.
square
(or whatever) is the name of the function and it can be anything we want within reason.
:
defines a block of code in Python. After a colon Python expects to
see indented lines with commands.return
ends the program with one last value, I call the returned value the
output of the function.Sometimes I find the explanation more daunting than actually doing it. Like reading a book on riding a bike and expecting to be able to ride:
Now, let's write an email writing function. For this task you might consider using replace or concatenation. Here are some sample snippets:
There is even a very cool way to inject content into strings. This is called string formatting (more on this later).
You might see the old way every now and again too:
Mini-Task 4: Use the earlier email as inspiration and create a function which takes
as input prof_name
, course_number
, and section_number
, and returns a custom
email.
We want our code to be comprehensible, because that is the first step on the way to maintainability. The first step to comprehensibility is to break computational tasks into comprehensible chunks (represented as functions and classes) and name those. Such functions then provide the basic vocabulary of computation, just as the types (built-in and user-defined) provide the basic vocabulary of data. […]
The number of errors in code correlates strongly with the amount of code and the complexity of the code. Both problems can be addressed by using more and shorter functions. Using a function to do a specific task often saves us from writing a specific piece of code in the middle of other code; making it a function forces us to name the activity and document its dependencies.
So we've made a function. It contains a set of commands that can get executed whenever you want on whatever input you want. But up until now we haven't really touched the power of a computer. The real power of a computer lies in doing trillions of operations in just seconds.
We can tap into this power using a loop. A loop is just a set of commands that will get executed many times.
It acts a lot like a function but with some sort of repetition implied. Here is a while
loop, which
just repeats until something happens.
Group-Task 5: Talk to some people nearby and explain how that code worked.
Change it to run 20 times. Now change it to only process the first 20 even values of i
(2, 4, 6, …).
WARNING: be very careful with while
loops. You can end up with infinite loops.
Every time you write one make sure that you increment a counter or make progress towards ending the loop.
Easy-Task 6: What happens when you define i=501
on line 1?
Visual-Task 7: Change what is printed to make a growing pyramid. Like the following diagram:
*
**
***
****
*****
******
Nested-Task 8: Write a function which takes as input an integer,
n
, and which
then displays a pyramid n
layers tall. (Warning: in every Python block your indentation must be
consistent. You are about to nest two blocks so you'll need double indentation at some point.)
Take a moment to visit "Reeborg's World" a pleasant way to practice thinking in Python.
Side-Task: Visit http://reeborg.ca/world.html In the "world" dropdown menu select "Demo 1". Before you hit play, decide what you think will happen. Then click play and confirm. Later tonight go to the Maze and write a solution yourself with the fewest number of lines you can.
for
loopAnother type of loop is one which iterates through a list of values. Executing once per value. This is
called a for
loop, although various languages have different takes on this.
By the way, a list
is actually a data type in Python. So you can make a list of things simply by
surrounding them in square brackets: [1, "banana", 7]
. We will talk more about lists later. Without
further ado, the for loop:
Here have another:
Mini-Task 9: Loop through a list of your favorite foods and for each food display a nice sentence using that food.
Here is how that works:
for
tells Python we're beginning a for loop.varname
that next word can be anything you want, it defines a variable which your statements
have access to. in [1,2,3]
this tells the variable what its value will be in each loop. It also defines how
many loops will run.:
The comma lets Python know that you are going to begin a block of code.while
and def
,
Python will know that you are done with the loop when the indentation stops. (That is, it sees a line which
has a different indentation depth.)One last thing to tell you. Python comes with a very handy command called range
. It is a
function that generates sequences of integers. Most of the time you run a for loop you'll want to just iterate
over the values from 1 to n
. range(n)
produces values just like that:
0,1,2,3,…,n-1
(well off by one). In Python3 I have to cast the range into
a list
type if I want to just look at it.
But to make a loop from range I don't need anything:
Mini-Task 10: Write a function which takes in an integer n
and
displays the first n
square numbers (0, 1, 4, 9,…).
By the way, for
is happy to iterate through things other than lists. Like strings! Check this
out:
Look through the documentation
on string formatting in Python 3.4. Use what you learn to write a function that accepts an integer
n
and displays the binary representation of the first n
numbers.
Today we learned the following: