Python Functions and If Statements

Now that we've written hello world in python, let's press on.

Hello World Revisited

Let's break down this program into its components. This should make it easier to learn.

Don't worry about memorising this stuff. You are going to see these components again and again, so after a while it will become second nature to you.

It's worth noting here that Python cares about indentation. If I use 4 spaces at the start of a line, so should you!

Python Functions

The highlighted code below is a function. A function does something.

def main():
  print 'hello, world'

if __name__ == '__main__':

This particular function prints, or outputs to the screen, the text, or string, 'hello, world'

We've decided to call it main. The name main is just a convention. We could have called it anything.

So, to recap, we've defined a function called main, that prints the string 'hello, world'.

That was pretty easy, wasn't it?

Python If Statements

The highlighted code below is a conditional statement. It does something if a condition is met.

def main():
  print 'hello, world'

if __name__ == '__main__':

This particular conditional statement kicks off the main function if somebody's __name__ is __main__.

Who's __name__ are we talking about? The current python source-code file or module, that's who.

Whenever we run a Python module from the cmd prompt, its __name__ is set to __main__.

All Together Now

So, lets see how this fits together.

  1. The Python Interpreter begins at the top of the module and reads downward.

    The Python Interpreter finds a conditional statement, and says 'if the module's __name__ is __main__, then execute the code inside of the statement.
  2. The code inside the statement says 'Call the main function and ask it what to do'. main tells the interpreter to print 'hello, world'.

Python reads a lot like English!

Go Do Something

You won't learn Python, or programming in general, by just reading tutorials. You actually need to get your hands dirty.

So...using your current vocabulary and skillset, "Write a Python script that prints the days of the week"

Have a coffee first though. What's the rush?

Python Lists and For Loops

Please Share

If you found this useful, please share with friends.

comments powered by Disqus