The Professional Steve

The very important blog of a professional Computer Science undergrad and professional dork

Python if statements

In the last post we talked about Python strings and string concatenation. We even saw how we can get user input and use it in our program. But the use was very limited. If we want to do more we need to tell our programs how to make decisions. For that we need if statements.

Let’s have a look at the greeting program from last time:

print "What's your name?"
name = raw_input()
print "Hello " + name + "!" 

The first line simply prints a string, the second line gets user input, and the last line prints a concatenated string. That’s all fine and dandy but the program is still kinda dumb, I mean you could say your name was “zoosmell pooplord” and the computer wouldn’t know the difference.

What's your name?
zoosmell pooplord
Hello zoosmell pooplord!

Let’s make a little addition

print "What's your name?"
name = raw_input()
print "Hello " + name + "!" 
if name == "zoosmell pooplord":
    print "Hey wait a minute! That's not your name is it?!"

Now let’s try it again:

What's your name?
zoosmell pooplord
Hello zoosmell pooplord!
Hey wait a minute! That's not your name is it?!

Buh-wuh-buh? The computer is not fooled by my ruse? Maybe I should try being honest with the computer, at least for now…

What's your name?
Steve
Hello Steve!

I’m not sure I’m comfortable with the computer knowing so much about me….

Ok, let’s break this down. What’s going on with these last two lines?

if name == "zoosmell pooplord":
    print "Hey wait a minute! That's not your name is it?!"

The way if statements work is that they first test for a condition and then, if the condition is true, execute all the indented code underneath them. Python is a bit unique in that it uses indentation to determine what’s underneath an if statement. When you study other languages, you’ll find that they use other ways, but the bottom line is always this: if statements test for a condition, if the condition is true then the code within the if statement is executed. If the condition is not true then the condition is not executed..

In our case the condition is name == “zoosmell pooplord”. That double equals inbetween name and “zoosmell pooplord” is what’s called a comparison operator. We’ll talk more about them in later posts, but this one, the double equals, is checking if the thing on it’s left is equal to the thing on it’s right. If name is equal to “zoosmell pooplord” then the program prints our indignant message. If name is not equal to “zoosmell pooplord” then the indented code is not executed.

Also, and this is important, don’t forget to put a colon at the end of your if statements or they won’t work!

Social media is media

I just saw a post on Linkedin complaining about users treating the network as if it were facebook, i.e. complaining about users posting pictures of their meals, and math problems

I’ve personally not seen this, but it wouldn’t bother me that much. Sure, posting pictures of your food is a bit of a cliche, but math problems? Why object to that?

Linkedin may not be facebook, but it is social media. If you’re not posting engaging content, how do you expect to draw traffic (i.e. the eyeballs of potential employers and recruiters) to your page?

Python string concatenation

Last time on professionalsteve.com, special python addition, I showed you how to get user input and print it back out to the screen. But that’s just the start. Real programs take user input, do something with it, and then give us some useful (or fun) output. A big part of how programmers make a computer do that is with the manipulation of strings.

What is a string? Well, you know what a character is right?

This is the character “a”

a

This is the character “b”

b

You get the idea. But this is also a character

4

The character “4”

Most of the buttons on your keyboard (except for the ones like “caps lock” or “ctrl”) represent a character that can be printed to the screen. “7” is a character, “&” is a character, even the space ” ” is a character.

Strings are a bunch of characters lined up, a string of characters.

Here’s a string

32sldfawo3ha0os89dhg

This is also a string

Hello my baby, hello my honey, hello my ragtime gal

In python, and most other languages, strings are represented by surrounding them in quotation marks

Here’s that old “hello world” program again:

print "hello world"

The word print is what’s known as a function. It’s a command that, in this case, tells the python interpreter to print whatever comes next to the screen. “hello world” is what comes next. Because it’s enclosed in quotation marks, the python interpreter knows that it’s a string of characters.

Now open up a new file and type this:

print "hello " + "world"

Save it as hello_world2.py and run it like so:

python hello_world2.py

Your output should look like this:

hello world

So what does that plus do? It concatenates (or puts together) the strings “hello ” and “world”. Now you’ll be able to talk like a professional programmer. Whenever they talk about string concatenation, this is all they’re talking about. String concatenation is just putting strings together using the addition symbol. Simple, right?

String concatenation may be simple, but it also open’s up new possibilities. Like so:

print "What's your name?"
name = raw_input()
print "Hello " + name + "!"

Save that as greeting.py and run that sucker.

python greeting.py
What's your name?

Now the program wants to know your name! A little too nosy for my taste. Better user a fake name to throw it off the track.

What's your name?
Ronald McDonald

Now hit enter, that should fool ‘em.

What's your name?
Ronald McDonald
Hello Ronald McDonald!

So let’s look at this code:

print "What's your name?"
name = raw_input()
print "Hello " + name + "!"

Line 1 should give us no trouble. We know that from the hello world example. Line two is what we talked about last time. And the final line is just using a variable that holds a string to do some string concatenation.

Getting user input in Python

Last time I showed you how to use variables to vary the output of your programs. But that’s only part of it. You and I both know the magic happens when you can get user input. Awww yeah.

Open up a text editor and type the following:

user_input = raw_input()
print user_input

Now save it as input.py, navigate to the directory you saved it in, and type

python input.py

You should now see…. nothing!


The point is to get your input after all. Finally, you can make the computer listen to you. Go ahead and type whatever you want. I’m going to type “potato pancakes”.

potato pancakes

Now hit the enter key and watch what happens

potato pancakes
potato pancakes

Did you see that?! You have now programmed your own virtual parrot! Let’s try it a few more times:

Cookies are an all-the-time food
Cookies are an all-the-time food
I am so great!
I am so great!

You see! The computer has no choice! It has to repeat whatever you say!!

Variables in Python

In my previous post you learned about how to print “hello world”, but that’s a bit boring. I’m sure you want to learn to make programs whose outputs vary. That’s where vaiables come in.

Open up a new file called variables.py and type the following

greeting = "hello world"
print greeting

Now open the terminal, navigate to the directory that has the file, and type

python varables.py

Your output should be:

hello world

Well, that’s useless, I hear you saying. Ok Smarty McSmartypants, try changing your code to this!

greeting = "hello world"
print greeting
greeting = "Live long and prosper"
print greeting

Your new output should be:

hello world
Live long and prosper

Wha-wa-wuh? How can the lines 1 and 3 here do different things when they’re exactly the same?

greeting = "hello world"
print greeting
greeting = "Live long and prosper"
print greeting

It’s because the word “greeting” here is what’s called a variable. Think of it as a bucket whose contents vary.

For example, the following code:

greeting = "hello world"
print greeting
greeting = "Live long and prosper"
print greeting
greeting = "There's a hole in mah bucket"
print greeting
greeting = "Dear Liza, dear Liza"
print greeting
greeting = "There's a hole in mah bucket, dear Liza, a hole."
print greeting

Yields this output:

hello world
Live long and prosper
There's a hole in mah bucket
Dear Liza, dear Liza
There's a hole in mah bucket, dear Liza, a hole.

Think like a business owner

I can be pretty dumb about this kind of thing. I don’t think like a business person, I think like,  well not even a student or a scholar. I think, “Wouldn’t it be cool if I wrote an Android app in Scala? Or Haskell? Or Erlang?” And then I sit and dream, or go through tutorials for hours and hours.

Even if I do start a project (doomed from the start to never be finished), it’s seldom in a language or framework I already know. Or if I’m sensible about that for once, I spend too much time building something complicated when I should make the simplest app I can think of in the simplest and quickest way I can.

A business person looks at the assets they currently have and then figures out a way to turn them into money, using the least amount of time and resources.

Why am I spending time trying to build and install scaloid project when I could follow an Android tutorial and install a working “hello world” onto my phone in an hour or two?

Yes, we should absolutely learn new things, otherwise we’re all destined to be the future’s equivalent of today’s Cobol programmers. But we also need to leverage the skills we already have and make stuff now.

Hello world in python

This post assumes you’ve got a linux machine and know the slightest bit about how to get around in it.

Go to your terminal and type the following:

sudo apt-get install python.

Open your favorite text editor. (Gedit is fine for now.) Create a new file named “hello.py” and type this:

print "hello world"

Now save the file.

In the terminal, navigate to the directory that has your hello.py and type the following:

python hello.py

You should get this output:

hello world

Congratulations. You are now a python programmer. Now go forth and google inputs and if statements!

GO FORTH!!

How to make time for blogging

This post assumes you’re a loud mouth like me.

If the most writing you’ve ever done is in school you may have the wrong idea about it.

Writing is talking on a page.

I know you might be worried about rules, grammar, and all that crap. It’s not that important. Sure, if you want to be a novelist you might want to look into it. But this is blogs we’re talking about. It’s no big deal.

Writing is just talking on a page.

If you’re a loud mouth like me, you can’t stop talking. If you want to blog, just write the same way you talk. Give yourself 15-30 minutes max per post. Write about a paragraph’s worth. Write it just like you were talking to a friend.

Write each word, one after another, in the same way you talk, one word after another.

Don’t worry about grammar, or if it makes sense, just put your mind in the same state as if you were talking to someone. Someone who is patiently listening to everything you say, and will wait until you’re finished.

It’s a loud mouth’s dream.

But. But. Once you’re done, read what you’ve written and ask yourself if it makes sense. If someone comes across the post you’ve just written, and they don’t know you or how you think or how you talk, are they going to understand what you’ve said? If not, edit it until they would. Don’t stress too much over the details. Just edit enough so it makes sense.

Do that a bunch of times. Congrats, now you’re a blogger. Remember that each post doesn’t have to be long. The shorter the better, really.

Of course you can always get better at writing. The learning never stops, but this is great way to start.

Do it faster

I was a lazy kid. Something my mom used to say, when we needed to get ready and go somewhere or do something, was “every time you think about it hurry!” I tried, after a fashion, to follow this advice, when I wasn’t in the mood to be even more obstinate and lazy than usual.

Now I think about it a lot. And every time I do, I hurry.

I’ve made mention of the fact that I’m a big fan of the Self publishing Podcast and one of the things they often talk about is writing speed. They write thousands of words a day. They time themselves, track their stats, hit their word count goals, and then raise the bar.

Far from reducing writing quality they believe this improves it. Going fast forces them to turn off their internal editor (which they later turn on during the editing phase, much more useful ;) ) and to get into a flow state.

Thing is, this doesn’t just apply to writing. We should be trying to achieve speed and a flow state in all our activities. In Stephen King’s On Writing he says that he writes as fast as he can while still remaining comfortable. I think speed can be like that. Of course you’re comfortable doing something at a slow speed, but if you go fast enough and focus more, you’ll find another valley of comfort at a higher level of speed and focus. With practice this level of speed and attention can get ever higher.

I think The Pomodoro Technique dovetails quite nicely with this approach. Spend 25 minutes working as hard and fast as you can, then rest for 5. After you do that 4 times, the 4th break is 20.

Doooo eeeet

Auto-generate html tags in vim

This post assumes you’ve been using vim for a bit but doesn’t assume you’re some kind of expert.

So, I’ve been writing a lot a posts. I usually write them in vim and I really don’t want to have to write out html markup every time I want to put a link in my post. Turns out, there’s a simple script for that.

Go to your terminal and type the following:

vim ~/.vimrc

Make a new line in the .vimrc file and paste this in there

" Convert two lines (URL then TITLE) to one line: <a href=URL>TITLE</a>
map <F7> <Esc>I<a href="<Esc>A"><Esc>gJA</a><Esc>

Do a wq.

Now, any time you want to make a new line, paste or type in the link, then make a new line again and type what you want the link text to be, like so:


http://www.w3schools.com/

W3 schools

(Except delete line 2. I don’t know why WordPress is putting a blank line there.)

Now put your cursor on the first line there, the one with the url, and then hit the f7 key. The result should look like this:

<a href="http://www.w3schools.com/">W3 schools</a>

Cool, right?

Follow

Get every new post delivered to your Inbox.

Join 165 other followers