Welcome to the third installment of my Python Basics tutorials. Please read the other two tutorials before starting this one…or you won’t understand a thing. On the other hand, if you have programmed before and are interested in seeing what this is all about, please continue. Anyhoo, let’s get right to it, shall we?

User Input

Up until now, we have looked at creating simple programs in Python. In fact, we have even learned how to make those programs make decisions. Not the greatest feat, but at least our programs are semi-intelligent now. The next thing we will be covering is loops and how to get user input. To get user input you must use the statement:

1
var = raw_input("User: ")

I’ve always said the best way to learn is by example, so let’s make something that’ll toss whatever the user types back to the user. Haha, stupid user.

1
2
3
whatUserTyped = raw_input("Say something: ")
 
print whatUserTyped

The variable whatUserTyped is being directly fed by whatever the built-in function raw_input() can get for us. I’ll talk more about functions and modularity in the next tutorial. You’ll notice that in the parenthesis of raw_input() we have “Say something:”. We could put anything there, but what I want you to really notice is the space after the “:” in the function’s parenthesis. We should always be picturing what our programs will be doing when actual users run them. The space after the colon simple prints an extra space to the screen, but also makes the program neater when the user actually begins typing. This way what the user is typing isn’t stuck to what we printed using raw_input().

That’s all we will be looking at when it comes to user input. We will revisit this in greater detail in the next tutorial.

Loops

Finally! The meat of the tutorial. The stirloin steak. The sausage. The meat ball…? Everything before this was just an appetizer. Loops are everywhere, and like the conditional, are a fundamental programming concept. There are two loops we will be looking at. The for loop and the while loop. But first of all, what are loops? Well, since I’m lazy, I won’t actually tell you. In fact, like a politician, I’m going to dodge this question. But unlike the politician, I will make sure you understand. What the hell am I blabbing on about? Well, let’s see.

Say we want to print 100 lines, and on each line we want the corresponding number from 1 to 100. We could do this…

1
2
3
4
print "1"
print "2"
print "3"
print ...

all the way to 100. But that seems rather cumbersome. There must be an easier way. And that way is with loops. Now, do you have a basic idea of what loops are used for? I told you you would know what loops are without me actually telling you.

The while Loop

Let’s take a look at the structure of a while loop.

1
2
3
while CONDITION:
 
    STATEMENTS

What the while loop basically does is it keeps looping through STATEMENTS while the CONDITION is true. Like a broken record player, it will keep playing until someone stops it. Or in our case, something will loop, until we stop it. So let’s rewrite the above code with the knowledge we have acquired about Python until now.

1
2
3
4
5
6
7
8
count = True
k = 1
 
while count:
    print k
    k += 1
    if k > 100:
        count = False

And in 8 lines we printed all the numbers from 1 to 100. Let’s analyse this line by line.

  • Line 1 creates a boolean variable called count and stores the value True in it. Remember that boolean variables can only be True or False. Also note the capitalization on True, Python is case-sensitive!
  • Line 2 creates a variable k and sets a value of 1 to it. Nothing interesting there. Now comes the loop.
  • What line 4 is saying is “while the variable count is true, loop!” Writing while count is just a shorthand of saying while count == True.
  • In line 5 we print k, and
  • in line 6 we use another shorthand, k += 1, which could be re-written as k = k + 1. This prepares the variable k for the next loop by adding a 1 to it.
  • In line 7 and 8, we set the variable count to False so the loop won’t run anymore.

So, if we wanted to count to 200, all we would have to do is change line 7 to read if k > 200:. Simple, eh?

The for Loop

Like the while loop, the for loop loops too! The difference is that now we’re saying exactly what and how many times we want to loop through something. Before we look at an example, I’m going to tell you something really obvious. A word is made out of letters. But you knew that, right? Well, I sure hope so. In Python, we can loop through words (strings) by going through every individual letter. Let’s bring back the “Hello World!” example, but only this time let’s print the first letter of the word every line.

1
2
3
4
myVar = "Hello World!"
 
for letter in myVar:
       print letter

This does not need a line by line analysis. It’s really elegant in it’s simplicity. All we did was create a variable myVar and stored the string “Hello World!” in it. Then in line 3, we tell Python for every letter in the variable myVar print the variable letter. Note that we never initialized the variable letter. You don’t have to initialize variables that you put in a for statement. And it’s just that, a variable. We could have called it anything.

That’s pretty much it! So let’s put everything that we’ve learned together now. If you can tell what the code below does, then you’ve mastered everything we’ve covered so far. If you can’t. I’ll describe it in the conclusion.

1
2
3
4
5
6
7
8
9
control = True
 
while control:
    userInput = raw_input("Enter your name: "):
    if userInput == "q" or "Q" or "Quit" or "quit":
        control = False
    else:
        for letter in userInput:
            print letter

Conclusion

Congratulations on getting this far. By now you should have a feel for the Python language. There is only one more basic concept that we need to cover. In the next tutorial we will be talking about functions and modularity. But before we call it a day, I promised to tell you what the code above does. Well, basically it keeps asking the user for a name, and whatever the user types is broken down into characters and outputted line by line. However, if the user types “quit” or any other variation of it, the loop will cease to function, ending our program. Oh, and another thing before I forget! Be careful of infinite loops! If you write something like while 1 == 1, it will go on forever. Stuff like this could potentially crash programs, and in severe cases, your system. So be wary!