Difference between revisions of "Python"

From CSE330 Wiki
Jump to: navigation, search
Line 1: Line 1:
Python is an interpreted language with familiar syntax. It's a great language to use for parsing text files and rapid application development. Rather than the time-consuming write-compile-test-rewrite-recompile-retest-etc. cycle of languages like C and C++, Python scripts run through an interpreter. This eliminates the compile step and speeds up the development process.
+
Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on.  Although these restrictions help make the compiled program run quickly, they are cumbersome when you are trying to write short, quick scripts to perform tasks.  This is where a ''scripting language'' comes into play.
 +
 
 +
'''Python''' is a language well-suited to rapid prototype development. It is an ''interpreted language'', which means that you do '''''not''''' need to compile the code when you run it. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.
  
 
{{XKCD
 
{{XKCD
Line 6: Line 8:
 
}}
 
}}
  
=Getting Started=
+
== Installation ==
==Installing Python==
+
 
 +
Python may already be installed on your system.  To see whether or not it is, enter the command
 +
 
 +
<source lang="bash">$ python --version</source>
 +
 
 +
If it tells you a version of Python (like "2.7.1"), then you're good to go.  If not, you need to do a quick package install to get it up and running.  Apt and Yum both call a functional Python package '''python'''.
 +
 
 +
== Pip ==
 +
 
 +
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''.  PHP has a package manager named ''PEAR''.  It's now time to introduce Python's leading package manager: '''pip'''.
 +
 
 +
You need to install Pip from Apt or Yum before you can use it.  Both call the package '''python-pip'''.
 +
 
 +
Once you have pip installed, you can use it to install Python packages.  Use the '''pip-python''' (RHEL) or '''pip''' (Debian) command:
 +
 
 +
<source lang="bash">
 +
$ pip-python install package_name # RHEL
 +
$ pip install package_name # Debian
 +
</source>
 +
 
 +
== Running Python ==
 +
 
 +
There are two common ways to run Python code: via the console, and via a Python script file.
 +
 
 +
=== The Python Console ===
 +
 
 +
The Python console enables you to experiment with code without opening a text editor.  To enter the Python console, simply type the ''python'' command at the terminal:
 +
 
 +
<source lang="bash">$ python</source>
 +
 
 +
To leave the interactive console, either type "quit()" or press Ctrl-D (on both Mac and Windows).
 +
 
 +
=== Python Script Files ===
 +
 
 +
You can also save Python script files for later use.  The extension for Python scripts is '''*.py'''.  To run a script file, simply feed its path as an argument to the ''python'' command in Terminal:
 +
 
 +
<source lang="bash">$ python my_script.py</source>
 +
 
 +
== Syntax ==
  
  yum install python
+
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].
  
should do the trick. Make sure that python is in your path with
+
=== An Example Python Script ===
  
which python
+
In my mind, there's no better way to learn Python than to be immersed in a simple example script.
  
and modify your path if necessary.
+
<source lang="python">
 +
print "Hello World"
  
===Installing Pydev (Optional)===
+
fruits = ["apple", "banana", "cherry", "date"]
If, like me you're an IDE junkie then you may wish to install the eclipse pydev plugin (though it can be a little annoying when [[#Installing Python Modules | Installing Python Modules]].
+
for i, fruit in enumerate(fruits):
 +
print "I always love to eat a fresh %s." % fruit
  
The Pydev installation guide is available [http://pydev.org/manual_101_install.html here].
+
# Map the fruits list over to a new list containing the length of the fruit strings:
 +
fruit_size = [len(fruit) for fruit in fruits]
  
==Using Python==
+
avg_fruit_size = sum(fruit_size) / float(len(fruit_size))
 +
print "The average fruit string length is %4.2f." % avg_fruit_size
 +
</source>
  
Python programs can be run in several ways. Two of the most common ways are through the python shell and in .py files.
+
Some things to notice:
To enter the python shell, simply type
+
* Printing is achieved using the '''print''' command
 +
* A colon starts a block, similar to a curly brace '''{''' in many other languages.  The corresponding code block '''''must''''' be indented. The end of the code block is signified by when the indentation ends.
 +
* Strings can be printf-style formatted using the '''%''' operator
 +
* Inline comments start with a pound symbol '''#'''
 +
* We can map a list to a new list in just one line. (Beat that, Java!)
 +
* When we compute the average fruit size, we need to cast ''len(fruit_size)'', which returns an int, to a float in order to prevent integer truncation.  Note that ''sum(fruit_size)'' returns a float, even though the list contains only ints.
  
python
+
=== A Handfull of Other Useful Tips ===
  
into your shell. Interactive mode should start up, and you can type commands to be directly executed. You can exit interactive mode with ctrl+d or with
+
Define functions using the '''def''' keyword:
  
quit()
+
<source lang="python">
 +
def my_function(name):
 +
print "Hello, %s!" % name
  
To run a .py file, simply use:
+
my_function("Batman")
 +
my_function("Superman")
 +
</source>
  
python <filename> <args>
+
Python has a special datatype called '''tuples''', which are essentially short arrays useful for storing data that is associated with each other:
  
==Syntax==
+
<source lang="python">
  
Since the online documentation for Python is quite extensive and helpful, [http://docs.python.org/tutorial/index.html the online Python tutorial] is definitely the place for any and all of your Python-related needs. Be sure to read the [http://docs.python.org/tutorial/datastructures.html data structures] page to understand how they work in Python.
+
</source>
=Installing Python Modules=
 
Most likely the module will be distributed according to the python standard described [http://docs.python.org/install/#the-new-standard-distutils here], so you can simply unpack the archive, cd into the resulting directory, and execute the following commands:
 
python setup.py build
 
python setup.py install
 
Note: you may have to execute the command using sudo depending on the permissions of the directories involved.
 
  
Though there are yum packages available for installing many python modules, it is recommended that you use the above method if you are using eclipse with pydev, otherwise eclipse does not recognize that the module is installed, and you will simply have to ignore the unresolved import error and make due without autocomplete for that module. It's not ideal, but sometimes that's how it goes.
+
Python has another datatype called '''dictionaries''', which are like ''maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6).  Essentially, they enable you to use strings as the keys in your data structure.
  
 +
=== Object-Oriented Programming in Python ===
  
 
[[Category:Module 4]]
 
[[Category:Module 4]]

Revision as of 01:44, 23 March 2013

Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. Although these restrictions help make the compiled program run quickly, they are cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a scripting language comes into play.

Python is a language well-suited to rapid prototype development. It is an interpreted language, which means that you do not need to compile the code when you run it. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.

XKCD Comic: python

Installation

Python may already be installed on your system. To see whether or not it is, enter the command

$ python --version

If it tells you a version of Python (like "2.7.1"), then you're good to go. If not, you need to do a quick package install to get it up and running. Apt and Yum both call a functional Python package python.

Pip

Linux distributions have package managers like Apt, Yum, and YaST. PHP has a package manager named PEAR. It's now time to introduce Python's leading package manager: pip.

You need to install Pip from Apt or Yum before you can use it. Both call the package python-pip.

Once you have pip installed, you can use it to install Python packages. Use the pip-python (RHEL) or pip (Debian) command:

$ pip-python install package_name # RHEL
$ pip install package_name # Debian

Running Python

There are two common ways to run Python code: via the console, and via a Python script file.

The Python Console

The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the python command at the terminal:

$ python

To leave the interactive console, either type "quit()" or press Ctrl-D (on both Mac and Windows).

Python Script Files

You can also save Python script files for later use. The extension for Python scripts is *.py. To run a script file, simply feed its path as an argument to the python command in Terminal:

$ python my_script.py

Syntax

This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see the Python docs.

An Example Python Script

In my mind, there's no better way to learn Python than to be immersed in a simple example script.

print "Hello World"

fruits = ["apple", "banana", "cherry", "date"]
for i, fruit in enumerate(fruits):
	print "I always love to eat a fresh %s." % fruit

# Map the fruits list over to a new list containing the length of the fruit strings:
fruit_size = [len(fruit) for fruit in fruits]

avg_fruit_size = sum(fruit_size) / float(len(fruit_size))
print "The average fruit string length is %4.2f." % avg_fruit_size

Some things to notice:

  • Printing is achieved using the print command
  • A colon starts a block, similar to a curly brace { in many other languages. The corresponding code block must be indented. The end of the code block is signified by when the indentation ends.
  • Strings can be printf-style formatted using the % operator
  • Inline comments start with a pound symbol #
  • We can map a list to a new list in just one line. (Beat that, Java!)
  • When we compute the average fruit size, we need to cast len(fruit_size), which returns an int, to a float in order to prevent integer truncation. Note that sum(fruit_size) returns a float, even though the list contains only ints.

A Handfull of Other Useful Tips

Define functions using the def keyword:

def my_function(name):
	print "Hello, %s!" % name

my_function("Batman")
my_function("Superman")

Python has a special datatype called tuples, which are essentially short arrays useful for storing data that is associated with each other:

Python has another datatype called dictionaries, which are like maps in Java, associative arrays in PHP, and object literals in JavaScript (coming up soon in Module 6). Essentially, they enable you to use strings as the keys in your data structure.

Object-Oriented Programming in Python