TUTORIAL: Introduction to Python

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

Introduction


This tutorial will introduce you to some of the basic concepts of Python, including syntax, data types, and language constructs. No previous experience with Python is assumed.

Obtaining and Installing Python


Python is a free and open-source language and can be downloaded for your specific platform at the following URL:
http://python.org/download/

For detailed instructions on installing Python on your particular platform, consult the Python documentation.

Once you have Python installed, you should be able to bring up a command prompt (Windows) or a terminal (UNIX/Linux) and type `python` to start the Python interpreter:

Attachments:
python_prompt.png

The Python interpreter



The interpreter will evaluate any expression you type in. Alternatively, you may specify a Python script (.py) to be executed:

Attachments:
python_script.png

Executing a Python script file



Writing Python Scripts


Any basic text editor will work fine for writing Python code, although you may want to use an editor with syntax highlighting support for the language, as well as one with the option to indent using spaces rather than tabs.

Attachments:
python_editor.png

Editing Python code with Notepad2



Python's Syntax: Indentation is King


In Python, blocks of code are distinguished by indentation. This is quite different than C-like languages such as PHP and Javascript, which use curly braces ("{" and "}") to signify the beginning and end of a block of code, respectively. This may feel strange at first, but you'll get used to it, and it can make Python code significantly easier to read.

Here's an example of Python code containing nested code blocks. Notice how the indentation of each line determines which block it belongs to:
PYTHON Code: [ Select ]
def foo():
    print "Hello, world!"
    num = 5
    if( num <= 5 ):
        temp = num
        while( temp > 0 ):
            print "The number is", temp
            temp -= 1
    else:
        print "The number is greater than five."
  1. def foo():
  2.     print "Hello, world!"
  3.     num = 5
  4.     if( num <= 5 ):
  5.         temp = num
  6.         while( temp > 0 ):
  7.             print "The number is", temp
  8.             temp -= 1
  9.     else:
  10.         print "The number is greater than five."


Basic Keywords and Constructs



Comments
Python has two different comment styles that can be used.

The pound symbol style (#) is used to signify a comment that extends through to the end of the line.

PYTHON Code: [ Select ]
foo = 5   #this is a comment
bar = 24
#this is also a comment
baz = "hello"
  1. foo = 5   #this is a comment
  2. bar = 24
  3. #this is also a comment
  4. baz = "hello"


The slash-star style (/* ... */) specifies a comment that begins with a slash-star (/*) and ends at the first star-slash (*/). Comments of this style can span multiple lines.

PYTHON Code: [ Select ]
foo = 5    /*this is a comment*/
bar = 24
/*this comment
  spans multiple
  lines */
baz = "hello"
  1. foo = 5    /*this is a comment*/
  2. bar = 24
  3. /*this comment
  4.   spans multiple
  5.   lines */
  6. baz = "hello"


Line Endings
No semicolon is needed at the end of a statement in Python; the end of a line implies the end of the statement

PYTHON Code: [ Select ]
foo = 5<span style="font-weight: bold">;</span>   #wrong!
bar = 42    #correct
  1. foo = 5<span style="font-weight: bold">;</span>   #wrong!
  2. bar = 42    #correct


Conditionals and Loops
Conditional blocks (if-statements) and loops begin with their respective keywords, an open-parenthesis, the conditions, a closing-parenthesis, and a colon:

PYTHON Code: [ Select ]
if( foo > 5 ):     #note the colon!
    #these indented lines are part of the conditional
    bar = 42
    print "hello"
elif( foo < 5 ):               #note that it's "elif", not "else if"
    bar = 10
    print "hola"
else:
    print "bonjour"
  1. if( foo > 5 ):     #note the colon!
  2.     #these indented lines are part of the conditional
  3.     bar = 42
  4.     print "hello"
  5. elif( foo < 5 ):               #note that it's "elif", not "else if"
  6.     bar = 10
  7.     print "hola"
  8. else:
  9.     print "bonjour"


PYTHON Code: [ Select ]
while( foo > 5 ):     #again, note the colon!
    #once again, indentation determines
    #the statements within the loop
    print "foo is", foo
    foo -= 1
  1. while( foo > 5 ):     #again, note the colon!
  2.     #once again, indentation determines
  3.     #the statements within the loop
  4.     print "foo is", foo
  5.     foo -= 1


Variables and Basic Data Types


You've already seen some variables used in this tutorial. To define a variable, simple write the name of the variable and set it equal to some value:

PYTHON Code: [ Select ]
my_variable = "this is some text"


Python's basic data types include those found in most other languages: integers, floating point numbers, booleans, and strings.

PYTHON Code: [ Select ]
my_int_var = 5
my_float_var = 2.467
my_bool_var = True
my_string_var = "a string of text"
  1. my_int_var = 5
  2. my_float_var = 2.467
  3. my_bool_var = True
  4. my_string_var = "a string of text"


Functions and Classes



Functions
To define a function in Python, we use the def keyword, followed by the name of the function, an open-parenthesis, any parameters for the function, a closing-parenthesis, and a colon:

PYTHON Code: [ Select ]
def doSomething(num):
    print "The number is", num
  1. def doSomething(num):
  2.     print "The number is", num


Classes
Python is an object-oriented language and thus allows the creation of new types (classes). A class is defined with the class keyword, followed by the name of the class and a colon:

PYTHON Code: [ Select ]
class Foo:
    some_variable = 5
    some_other_variable = "some text"
   
    def doSomething(self, num):
        print "The number is", num
  1. class Foo:
  2.     some_variable = 5
  3.     some_other_variable = "some text"
  4.    
  5.     def doSomething(self, num):
  6.         print "The number is", num


We'll explore Python classes further in future tutorials.

Conclusion


At this point you should have a basic enough understanding of Python to begin writing a few simple scripts. Here are a few sample problems to solve using Python:

- Create a function that prints out all even numbers between 1 and 100
- Modify this function to take an argument specifying the upper end of the range rather than setting it to 100

- Create a function that concatenates two strings together and returns the result

- Create a function that prints out all Fibonacci numbers up to a specified number

Post Information

  • Total Posts in this topic: 1 post
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 1 guest
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.