An Overview of Python: Tutorial 3 - Control-Flow (branching)
Author |
Message |
apython1992
|
Posted: Wed Mar 23, 2011 12:56 pm Post subject: An Overview of Python: Tutorial 3 - Control-Flow (branching) |
|
|
Hello again! This is a continuation from my last tutorial, which covered basic console input and output in python. Up until now, we have dealt entirely with Python's interactive interpreter, which is really nice for writing small pieces of test code to immediately see what works and what doesn't. But now, it's time to learn how to write real programs and run them. Let's start with the obligatory "Hello, world" program.
First, a quick note
It is my personal opinion that IDEs should really only be used to manage large projects, which I'm quite certain "Hello world" is not. Besides, if this happens to be your first time programming, learning how to do so with a text editor and command-line environment will teach you some valuable skills and prevent you from establishing some bad habits. So we're going to go with the text editor/command-line combo.
If you're a Linux user, gEdit should already be installed, and you can use vim as well. Both of these offer options for syntax highlighting. If you're a Windows user, it's questionable whether or not you have a decent text editor. If you already have one that you know and love, great. If not, I know quite a number of people who like using Notepad++, so you can try that if you want, but I'll point you to a Windows binary of gEdit: http://projects.gnome.org/gedit/ (you can find the link to the Windows binary on the right).
If you're a new programmer, please note: computer code is just plain ol' text, and sadly a lot of new programmers think that they must use an IDE for the computer to recognize the code or something. You can type your code in Notepad and it will accomplish the exact same thing. So if you really don't feel like downloading anything, go ahead and use Notepad! Alright, so now that we're all sorted out with a text editor, let's get to writing our first Python program.
Hello world!
The first obvious step is to open up your text editor, so get it up and running. Now, type in the following line:
Python: | print "Hello, world!" |
Doesn't look like much, but this is a complete program! Now, we have to save it as a Python file (*.py) for the system to be able to know what to run it with, so go ahead and save it as "hello.py". Of course if you're a Linux user, you know that file extensions mean nothing, so you can add a shebang at the very top of the program:
Python: | #!usr/bin/python
print "Hello, world!"
|
Alright! Time to run it. Open up a command/terminal window, and get into the directory where you saved the program. I'm assuming that if you're a UNIX user you know how to do this, but for Windows users who have no idea what I'm talking about, here is a quick tutorial on how to use some basic features of the command prompt: http://www.cs.princeton.edu/courses/archive/spr05/cos126/cmd-prompt.html.
Now, type in the following command:
And there you go! Your program executed and returned control to the console. Now we can start learning more about Python.
Variables and Control Flow
For you new programmers, variables are much like those you are already familiar with in math class: they hold information and can change throughout the course of the program (hence 'variable'). In Python, you don't need to declare variables - you can just assign them on the fly. Making use of the interactive prompt:
code: |
>>> print x = 3
>>> print x
3
>>> x = True
>>> print x
True
>>> x = "string"
>>> print x
string
>>> x = [1, 2, 3, 4, 5]
>>> print x
[1, 2, 3, 4, 5]
>>>
|
But actually, this isn't anything new if you read the last tutorial - we stored user input into variables without ever having to declare them. Variables can hold a large number of types of data, some of the more basic ones in Python being integers, floats, strings (characters are treated as strings in Python), and lists. We'll go more into detail with some of these data types in the next tutorial.
Control Flow: if, elif and else
Using control-flow statements like Python's if-elif-else blocks allow portions of programs to execute differently depending on certain conditions. It reads very much like English, making it very easy to understand. In Python if/else clauses are structured as follows:
Python: |
if {condition}: # Minus the braces
{execute block}
elif {some other specified condition}:
{execute other block}
"""
any number of elif clauses
"""
else: # Any condition other than those specified falls into the 'else' block
{execute another block}
|
Control-flow clauses are arranged into blocks, just like in C and C++. However, instead of delimiting blocks with curly braces, Python uses whitespace indentation. The beginning of the next block implies the end of the previous block. In the above piece of code, I also made use of Python's two methods of commenting code. New programmers: in-code commenting is used to explain what pieces of code accomplish in a program, among other things, and are ignored by the interpreter - they just help to make code more understandable to someone who may need to come back to it. In Python, single line comments are prefixed with a '#' symbol, and multi-line comments can be surrounded with triple quotation marks (also called docstrings).
If you're learning Python after coming from another language, chances are you're already comfortable with using if/else clauses. Here's an exercise to get comfortable with this if you're a new programmer (or want to practice anyway):
Exercise: Write a program that asks the user for his/her age, and produces the following output depending on the entered age:
Age 0-9: "You're just a kid!"
Age 10-14: "I hope you don't like Justin Beiber."
Age 15-19: "They say these are the best years of your life."
Age 20-34: "These ARE the best years of your life."
Age 35-49: "Have you had your mid-life crisis yet?"
Age 50+: "You're old!"
If you're a new programmer and you find this a little difficult at first, try to work with simpler examples of using if-elif-else. For a bit of a hint, it's nice to understand that the condition always evaluates to either True or False, so you can combine conditions with operators like and and or into one condition,
e.g. age >= 10 and age <= 14
And finally the challenge for this tutorial (10 bits, open to new/inexperienced programmers): Is "elif" ever truly necessary? If not, show an example that illustrates an alternative in Python code. If so, explain why. First person to answer correctly receives 10 bits. Sorry to you relatively experienced programmers; next tutorial's challenge will be open to everyone so you'll have an advantage
That's it for now. Next up: more control-flow (looping) and lists. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
SNIPERDUDE
|
Posted: Wed Mar 23, 2011 4:19 pm Post subject: RE:An Overview of Python: Tutorial 3 - Control-Flow (branching) |
|
|
Great series so far. |
|
|
|
|
|
apython1992
|
Posted: Sun Mar 27, 2011 12:31 pm Post subject: RE:An Overview of Python: Tutorial 3 - Control-Flow (branching) |
|
|
Thanks! |
|
|
|
|
|
|
|