Beginner’s Introduction to Python

If you are a beginner in programming languages, you’d be pressured to pick your very first programming language to study. If you study in a course associated with information technology or computer science, there is a high possibility that all the programming languages you need to study are already laid out in your curriculum. But if you aren’t, you might want to consider studying Python.

Many programmers that haven’t touched Python will likely ask whether or not Python is still relevant these days. It is still relevant – in fact, it is highly recommended to study the programming language when you want to understand more about the software engineering world of today.

To save you from the boring details of what started out Python, it is best that you get introduced to the basics. Keep in mind that what you’ll learn here is just brush up of the beginning, and it will be your responsibility to learn more about it. While there is no need to know a programming language before this, it is a great advantage if you do.

The Basic Syntax

You must have at least heard other programming languages when you were searching for the best one for beginners. Python has similarities with Java, Perl and C. However, there are some differences as well.

Start invoking the program’s interpreter, but at this stage you are not to pass a script file when the parameter shows the following:

$ pythonPython 2.4.3 (#1, Nov 11 2010, 13:34:43)[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2Type “help”, “copyright”, “credits” or “license” for more information.>>> After that, type in the following and after that press the Enter key:  >>> print “Hello, Python!” If you are using a new version of the program, use the print statement with the parenthesis like this one:

print (“Hello, Python!”); 

But the version 2.4.3 will produce this result:

Hello, Python!


Script Mode

The above code is by invoking the program’s interpreter without running the script. This one you will be using the interpreter with script parameter. It will begin the script’s execution and will continue to do so until the whole script is finished. After it is finished, the interpreter will no longer be active.

Here is an example to try out. Keep in mind that files in Python end in a .py extension. Name the file “test.py”.

print “Hello, Python!”

This is assuming that the interpreter path of Python is in the PATH variable. Try running the following line of code:

$ python test.py

This code will render the result below:

Hello, Python!

There is also another way to execute the script. Try the modified test.py:

#!/usr/bin/python

print “Hello, Python!”

The following code below assumes that there is a Python interpreter available right in the /usr/bin directory. Try the following lines of codes:

$ chmod +x test.py     # This is to make file executable

$./test.py

This will result to:

Hello, Python!


Identifiers

Identifiers in Python refers to the name that is utilized in identifying a function, variable, class, module or any other object. The identifier can start with a capital or small caps letter or an underscore, which is followed by more letters, digits, underscores or a zero.

Identifiers are not defined by using punctuation characters like %, $, and @. Like other programming languages, Python is case sensitive. So when you compare manpower from Manpower, they are recognized as 2 different identifiers.

The following is a guide for recommended naming conventions of identifiers in Python.

  • An identifier that starts with 2 leading underscores – this means that you have defined a very strong private identifier
  • An identifier that has one leading underscore means that the identifier is set to private
  • Class names begin with a uppercase Other identifiers start with lowercase.
  • If the identifier ends with 2 trailing underscores, this means that it is a special name defined by language.

Indentation and Lines

There are braces in Python, unlike other programming languages, which will help indicate users where the blocks of code for function definitions and class are, including flow control. The blocks of code are identified according to the indentation of lines, which this is rigidly enforced by Python programmers.

The variable is identified according to the number of indentation there is, however, all statements found within the block should be indented on the same amount, like the example below:

if True:

       print “True”

else:

       print “False”

The following code will generate an error:

if True:   

      print “Answer”

      print “True”

else:    print “Answer” 

     print “False”

See the difference? Python with all its continuous lines that are indented on the same amount of spaces defines a block. To get a good idea as you progress your way to more advanced levels in Python, here’s another example of how a good block of code Python loves to read:

#!/usr/bin/python

import sys

try:
# open file stream
file = open(file_name, “w”)
except IOError:
print “There was an error writing to”, file_name
sys.exit()
print “Enter ‘”, file_finish,
print “‘ When finished”
while file_text != file_finish:
file_text = raw_input(“Enter text: “)
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write(“\n”)
file.close()
file_name = raw_input(“Enter filename: “)
if len(file_name) == 0:
print “Next time please enter something”
sys.exit()
try:
file = open(file_name, “r”)
except IOError:
print “There was an error reading file”
sys.exit()
file_text = file.read()
file.close()
print file_text

There is no need to understand the logic of the blocks above of code. It is intended that you know how the blocks of code are made and written well. This will also help you avoid errors, too.


Multi-line Statements

Python’s statements mostly end in a new line. However, Python allows the utilization of the backslash character, known in this programming language as the line continuation character. This tells the interpreter that the line must continue. An example would be as follows:

total = item_one + \

item_two + \

item_three

Statements that are contained within (), {}, or [] brackets has no need to use the continuation character, such as the example below.

days = [‘Monday’, ‘Tuesday’, ‘Wednesday’,       

‘Thursday’, ‘Friday’]

 


Quotation

Python recognizes the single, double and triple quotes that define the string literals. This is so as long as there are the same kinds of the quote that begins and ends with the string.

Here are some examples of how the quotes are used with coding in Python:

word = ‘word’

sentence = “This is a sentence.”

paragraph = “””This is a paragraph. It ismade up of

multiple lines and sentences.”””


Comments

The hash sign, which is (#), that is not placed within the string literal starts a comment. All the characters that follow the hash sign throughout the single line are a part of the comment, and the interpreter skips them. Examples are as follows:

#!/usr/bin/python#

First commentprint “Hello, Python!” # second comment 

You can even declare multiple comments successively. The interpreter will still ignore it.


Blank Lines

A line that only has whitespace, like a comment, is seen as a blank line by the interpreter and will totally ignore it.

Prompt for User

The following lines of codes below shows you how to prompt a user, wherein it waits for the user to do some action:

#!/usr/bin/python 

raw_input(“\n\nPress the enter key to exit.”)

The “\n\n” tells the interpreter to make 2 new lines before showing the actual line. When the user presses a key, the program will then end.

These are just the basics. When you combine everything, including theories and concepts about creating programs in Python, don’t forget the ones that you learned above. They are the foundations that will help you create a robust Python program.

SHARE