Skip to content Skip to sidebar Skip to footer

Python Do Same Function Again and Again

A Quick Start to Python

With the last release of Python two.5 we thought it was about time Builder AU gave our readers an overview of the popular programming linguistic communication. Builder AU'south Nick Gibson has stepped up to the plate to write this introductory article for beginners.

With the last release of Python ii.5 we idea it was about time Builder AU gave our readers an overview of the popular programming language. Builder AU's Nick Gibson has stepped up to the plate to write this introductory commodity for beginners.

Python is a high level, dynamic, object-oriented programming language similiar in some ways to both Java and Perl, which runs on a variety of platforms including Windows, Linux, Unix and mobile devices. Created over 15 years ago as an application specific scripting language, Python is now a serious pick for scripting and dynamic content frameworks. In fact it is being used by some of the world's dynamic programming shops including NASA and Google, among others. Python is likewise the language behind Web development frameworks Zope and Django. With a good for you growth charge per unit at present could be the perfect fourth dimension to add Python to your tool belt. This quickstart guide will give yous an overview of the basics of Python, from variables and control flow statements to exceptions and file input and output. In subsequent articles I'll build upon this foundation and offer more complex and specific code and advice for using Python in real earth development.

Why acquire Python?

  • It'southward versatile: Python can be used as a scripting linguistic communication, the "glue" that sticks other components together in a software system, much in the aforementioned way every bit Perl. It tin be used as an applications development language, just similar Java or C#. It tin can exist used as a Web evolution language, similiarly to how you'd utilize PHP. Whatever you need to do, chances are yous can apply Python.
  • It's gratuitous: Python is fully open up source, significant that its gratuitous to download and completely gratuitous to use, throw in a range of complimentary tools and IDE's and y'all can get started in Python development on a shoestring.
  • It's stable: Python has been around for more than 15 years now, which makes it older than Java, and despite regular development it has just just has reached version 2.5. Any code yous write at present will work with future versions of Python for a long fourth dimension.
  • It plays well with others: Information technology'southward like shooting fish in a barrel to integrate Python code with C or Java code, through SWIG for C and Jython for Java, which allows Python code to telephone call C or Java functions and vice versa. This means that yous tin comprise Python in electric current projects, or embed C into your Python projects whenever you demand a little actress speed.
  • It'southward easy to learn and use: Python'south syntax closely resembles pseudo code, meaning that writing Python code is straightforward. This also makes Python a great choice for rapid application development and prototyping, due to the decrease in development time.
  • It'due south easy to read: Information technology'south a simple concept, a language that is like shooting fish in a barrel to write should besides be easy to read, which makes information technology easier for Python developers to piece of work together.

Okay, enough already, I'm sold. Where do I get information technology?

Easy, in fact if yous're running Mac or Unix, chances you've already got it, but pull up a terminal and type "python" to load up the interpreter. If you don't have it, or you lot're looking to upgrade to the latest version head on over to the download page.

Alternatively you could install ActivePython, a binary python distribution that smooths out many of the hassles. There is a graphical installer under most platforms, all that you need to do is click through the dialogues, setting the install path and components. In Windows, yous tin so start upwards the interpreter by browsing to its entry in the start carte du jour, or on whatever system simply by typing 'python' in a terminal. While ActivePython is generally easier to set upwardly, it tends to lag behind official Python releases, and at the fourth dimension of writing is only bachelor for Python 2.iv.

Interactive Mode

Now it'due south time to load upward the interpreter in interactive mode, this gives you a prompt, similiar to a command line where you lot can run Python expressions. This lets you run simple expressions without having to write a Python programme every time, allow's effort this out:

Python two.5 (r25:51908, October 6 2006, xv:24:43) [GCC iv.one.2 20060928 (prerelease) (Ubuntu iv.1.1-13ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello Earth" Hello World >>>            

The first two lines are the Python environs information, and are specific to my install, and then your mileage may vary. Interactive mode is useful for more than just friendly greetings however, information technology also makes a handy calculator in a pinch, and existence part of a programming language allows you to apply intermediate variables for more than complicated calculations.

>>> two+ii 4 >>> 2.223213 * 653.9232 1453.8105592415998 >>> x,y = 5,20 >>> x + y 25 >>> tax = 52000 * (8.v/100) >>> print tax 4420.0 >>> "hi" + "globe" 'helloworld' >>> "ring " * seven 'ring ring ring ring ring ring ring '            

Another Python type that is useful to know is the list; a sequence of other types in gild. Lists can be added and multiplied like strings, and can also be indexed and cut into sublists, called slices:

>>> x = [ane,2,iii,four,5,six,vii,8,9,10] >>> x [1, 2, 3, iv, 5, half-dozen, vii, 8, nine, ten] >>> x + [11] [one, 2, 3, 4, 5, 6, 7, 8, 9, ten, 11] >>> ten + [12] * two [i, ii, 3, 4, five, 6, seven, 8, ix, x, 12, 12] >>> x[0], x[1], 10[nine] (1, 2, 10) >>> x[1:3], x[4:], x[2:-2] ([ii, iii], [five, six, vii, 8, 9, ten], [3, iv, 5, 6, vii, 8]) >>> x[:] [1, 2, three, 4, v, 6, seven, viii, 9, 10]            

The interactive mode is practiced for quick and dingy calculations, only once you outset writing anything longer than a couple lines, or you would like to salve your programs to use over again later, it's fourth dimension to let it go and start writing python programs. Thankfully this is easy, just blazon your commands into a .py file and run it with the same command.

Command Catamenia

Just like your favourite programming language, Python has all the usual ways of decision-making the execution of programs through if, while and for statements. In Python, an if statement looks like this:

if a > b:  impress a else:  print b            

You lot'll run into that unlike languages such as C or Coffee, Python does not use braces to group statements together. Instead statements are grouped together by how far they are indented from the margin, the body of a statement extends for as long as there are lines below information technology with the same or greater indentation.

x = 3 y = 4 if x > y:  x = ten + ane  y = y + 1            

For example, in the in a higher place code x = three and y = four at the stop of the program.

x = 3 y = 4 if x > y:  x = x + i y = y + 1            

In the second example, nonetheless, y finishes equal to five.

Python too has loops, both of the while and for variety. While loops are straightforward:

while a > b:  a = a + 1            

For loops work a little differently from what yous might be used to from programming in other languages, rather than increasing a counter they iterate over sucessive items in a sequence, similiar to a Perl or PHP foreach. If y'all practise need to accept that counter its no problem, you can use the born range function to generate a list of numbers similar and then:

for i in range(10):  print i            

If yous need it, you lot tin have finer control over your loops in Python past using either break or go on statements. A continue statement jumps execution to the top of the loop, whilst a break argument finishes the loop prematurely.

for ten in range(x):  if ten % 2 == 0:  proceed  if x > half-dozen:  break;  print x            

This code will produce the following output:

1 three 5            

A real plan: cat

Now nosotros virtually have the tools at our disposal to write a consummate, admitting small, program, such every bit the common unix filter cat (or blazon in Windows). cat takes the names of text files equally arguments and prints their contents, or if no filenames are given, repeats user input back into the terminal. Before nosotros can write this program all the same, nosotros need to introduce a few new things:

Opening and reading files.

In Python files are objects like whatever other blazon, and have methods for reading and writing. Say for example nosotros accept a file chosen lines.txt which contains the following:

line1 line2 line3            

There are 2 primary ways we tin view the contents of this file, by graphic symbol or past line. The following lawmaking demonstrates the difference:

>>> lines1 = file("lines.txt") >>> lines1.read() 'line1\nline2\nline3\n' >>> lines2 = file("lines.txt") >>> lines2.readlines() ['line1\northward', 'line2\n', 'line3\northward']            

The read() method of a file object reads the file into a string, whilst the readlines() method returns a listing of strings, ane per line. It is possible to take effectively control over file objects, for example reading less than the entire file into memory at once, for more information see the python library documentation (http://docs.python.org/lib/bltin-file-objects.html).

Importing modules and querying command line arguments.

Python comes with a wide diversity of library modules containing functions for commonly used tasks, such as string and text processing, support for mutual internet protocols, operating system operations and file compression – a complete list of standard library modules can be found here http://docs.python.org/lib/lib.html. In order to employ these functions you must import their module into your programs namespace,
like so:

>>> import math >>> math.sin(math.radians(60)) 0.8660254037844386            

In this example you can see that nosotros refer to the imported functions by their module name (ie. math.sin). If yous are planning to use a module a lot and don't want to go to the problem of typing it'south module name every time you use it and then you can import the module like this:

>>> from math import * >>> sin(radians(60)) 0.8660254037844386            

Access to command line arguments is in another module: sys, which provides access to the python interpreter. Control line arguments are kept in a listing in this module called argv, the following example demonstrates a plan that simply prints out all the control line arguments ane per line.

import sys for statement in sys.argv:  print argument            

This produces the following output when run with multiple arguments, the showtime argument is e'er the name of the script.

% python args.py many command line arguments args.py many control line arguments            

Input from the console

It seems perchance a little primitive in the era of GUIs and Web delivered content, but console input is a necessity for whatsoever program that is intended to be used with pipes. Python has a number of methods for dealing with input depending on the amount of control you lot demand over the standard input buffer, however for most purposes a simple phone call to raw_input() will exercise. raw_input() works just like a readline in C or Java, capturing each character until a newline and returning a string containing them, like so:

name = raw_input() impress "How-do-you-do ", name            

Error treatment with exceptions

When you're a developer, runtime errors are a fact of life; fifty-fifty the best and well-nigh robust lawmaking can be susceptible to user fault, hardware failures or simply conditions y'all haven't thought of. For this reason, Python, similar most modern languages, provides runtime error handling via exceptions. Exceptions have the advantage that they can be raised at ane level of the program and then defenseless further up the stack, meaning that errors that may be irretrievable at a deep level merely can be dealt with elsewhere need non crash the programme. Using exceptions in Python is simple:

try:  filename = raw_input()  filehandle = file(filename)  impress len(filehandle.readlines()) except EOFErrror:  impress "No filename specified" except IOError:  impress filename, ": cannot exist opened"            

In this example, a block of lawmaking is placed within a try statement, indicating that exceptions may be raised during the execution of the cake. And so ii types of exceptions are caught, the first EOFError, is raised when the raw_input() call reaches an stop of line character earlier a newline, the 2nd, IOError is raised when there is a trouble opening the file. In either case if an exception is raised then the line that prints the number of lines in the file volition not be reached. If any other exceptions are raised other than the two named, then they will exist passed up to a higher level of the stack. Exceptions are such a clean way to deal with runtime errors that soon enough you lot'll be wanting to raise them in your ain functions, and yous'll be pleased to know that this is easy plenty in Python.

endeavour:  raise ValueError, "Invalid type" except ValueError:  impress "Exception Defenseless"            

The Last Product

At present that you've got all the tools at your disposal to write our filter. Permit's take a look at the programme in total outset, earlier reading on, put your new knowledge to use by working out what each line does:

import sys  if len(sys.argv) < two:  while i:  try:  line = raw_input()  except:  pause  print line else:  for filename in sys.argv[ane:]:  try:  file_contents = open(filename).read()  print file_contents,  except IOError:  print "Fault: Cannot open", filename            

The program is unproblematic, if there are no command line arguments (except for the script proper noun, of class), and so the program starts reading lines from the console until an interrupt is given. If at that place are control line arguments, then they are opened and printed in order.

So there you have it, Python in a nutshell. For my side by side commodity I'll be walking you lot through the development of a Python plan for finding all of the images used on a web page. If you'd similar to suggest a topic for me to cover on Python drop me a line at nick.gibson@builderau.com.au.

osbornclar1961.blogspot.com

Source: https://www.techrepublic.com/article/a-quick-start-to-python/

Post a Comment for "Python Do Same Function Again and Again"