Python - Getting Started (Part-1)

Introduction
Python has been a popular language from quite some time now and it is gradually becoming even more popular. It is an interpreted, object oriented, high level programming language. It is a scripting language like Perl, Ruby, JavaScript, etc. There has been a long ongoing debate as to which scripting language (Perl or Python) is better. People on either side have strong reasons to back their claims. So, just to make it clear: through this post, I am NOT going to assert, claim, or comment regarding which language is better. Through this short (yet descriptive) post I intend to talk about Python and help people get started with it. It's pretty difficult to cover various nuances of Python through one blog post and hence I thought of dividing it into two parts. In this first part, I will be talking about basics of Python, discuss some of its features, look at language's structure, briefly introduce modules, share one very basic sample Python program, list some of the most commonly used inbuilt functions, explore strings, lists, tuples, hashes (dictionary), and various file operations.

Getting started with any new programming language is always bit tricky because a new starter doesn't know where to begin from. Hence, I am going to share pointers to few concepts that I grasped when I started exploring Python about 2.5 years back. These helped me understand the language easily. Hopefully, these would help you get started with Python as well.

Prerequisite: While writing this post, I have assumed that a prospective reader will have some basic programming experience in at-least one programming language.

Basics, Structure, and few features
Python is an interpreted, object oriented, high level programming language. It is a scripting language like Perl, Ruby, JavaScript, etc. It is very useful for automating small recurring tasks. It is a light language and is pretty quick. It has a quick turnaround time as there is no compile stage. It can be directly run on an interpreter. Syntax of a line is checked for correctness only when that particular line is executed (i.e. during run time). This makes this language even faster. But this comes with a drawback: if there are buggy lines in a code/program, they will only be detected if they are executed. Let's assume a case where we have an improper syntax or buggy function call inside "else" block of a "if-else". Program will run properly if this buggy "else" block is not executed. There will not be any compile error. Python will only throw error for the cases that will execute the buggy "else" condition in the program.

Unlike C, Perl, and many other programming languages, Python doesn't require semicolons (;) to indicate end of a line in the code. Also, there are no curly braces ({}) to enclose a code. Python uses indentation to group a block of code or functions. Just to mention: Python is case-sensitive language.

Python can directly be run on an interpreter. You can invoke it by typing "python" on a Terminal/Shell (as shown below). In Python, there is no need to declare a data type like int, char, string, float (unlike C). There is no compile-time type associated with a variable. As we see below, a variable "x" can be defined as an integer (15) or as a string (Hello World) without having the need to declare it as an "int" or a "string" before defining.

$ python   [This will invoke interpreter as shown below]
>>> x = 15
>>> x = 'Hello World'
Note that we haven't used a semicolon (;) to indicate end of line.

Getting Started - Writing one basic program
Step-1 (Path to Python Interpreter)
A Python program usually starts with a line of the form "!#/<path>/python<version>" at the top. This line indicates path to a python interpreter. It is a good/recommended practice to add "-tt" flag to this topmost line.
Example: "!#/<path>/python2.4 -tt". If we use this line, we specify that we are using python2.4 and -tt flag halts a program if there is a mixture of tab(s) and space(s) in the program. Recall that Python uses indentation to group a block of code rather than braces! If you inadvertently mix spaces and tabs in your program, -tt will halt the program. Usually, recommended practice is to use a "double space" for each indentation level. Alternatively, we can use "tab" also for indentation, but it's important to be coherent. Either use space(s) or use tab(s).

Step-2 (Modules)
There are many inbuilt modules in Python which we can import depending upon our requirement. One of the most common module is "sys", which is imported to Python program using:
import sys
"sys" module includes basic OS interface types, command line arguments, etc. We can refer to any in-built function inside a module using syntax "<module_name>.<function>". For Example: "sys.argv" refers to function argv.
There are many more useful inbuilt modules which we will discuss in later parts. As of now, we only need to know about "sys".
Note: We can import different modules on an interpreter as well.

Step-3 (Main function)
Define Main function. Functions are defined in Python using "def" keyword and have following syntax (note the presence of ":" at the end of function definition, absence of braces, and indentation)
def main():
  <code>

Step-4 (Boiler Plate Syntax)
Every Python Program consists of something like (usually present at the bottom):
if __name__ == '__main__':
  main()

This is called Boiler Plate Syntax.  To begin with, we can assume that this piece of code is required to run main() in the program. To start with, we can take it as a rule of thumb to add this syntax in a Python Program. Usage of this syntax is bit involved and for the sake of mentioning it here: Boiler Plate Syntax is used to "Load a module, use definitions present in the module as a library, without actually running the module".

Sample Program
Hence, combining all these four steps - our first basic program will look like (say program.py):
!#/<path>/python2.4 -tt
import sys
def main():
  print 'Hello World! First Python Program. Easy!'
if __name__ == '__main__':
  main()

Running a python program:
$ python program.py, OR
$ ./program.py

Few more basic commands
1) To figure out what all functions a module support? - dir(). Example: dir(sys)
2) To know more about a function? - help(). Example: help(sys.argv)

Note:
1) Comments in Python start with "#"
2) If you use a pre-defined function from a module without importing the module, interpreter will throw an Error saying 'module' not defined.
3) Observe the syntax of the print statement in our first program above. We used single quotes (''). We could instead use double quotes ("") as well. If we use single quotes ('') and if we want to use single quote (') as part of the print message as well, use escape character "\".

Few more basic functions/syntax
1) if
if <condition>:
  <code>
Example:
if value==10:
  print 'Value is 10'

2) for
for <variable> in <list>:
  <code>
Example:
for number in list:
  print number
We will see lists below. For now, assume this to be the syntax.

Strings (and few basic functions)
Strings in python are immutable i.e. once created, they never change.
For understanding few basic functions, lets assume a string:  st = 'Hello World'

1. For string concatenation, we can use "+" operator
2. st.lower() :: This converts all characters in the string "st" to lower case.
3. st.upper() :: This converts all characters in the string "st" to upper case.
4. len(st) :: This outputs the length of a string "st"
5. st[index] :: To refer to a character present at index in a string. Example: st[0] to refer to first character (H in this case)
6. In Python, we can refer characters in a string from right hand side as well [using negative number scheme]. Example: st[-1] will give "d" (last character)
7. "Slice" of a string (i.e. sub-part of a string) :: Example: st[3:7]

Lists (and few basic functions)
Lists have square brackets around them and they consist of elements. Lists are mutable and can be changed. Lists can be mixture of integers/characters/strings etc. Example: list = [1,2,3], list = [1, 'A','BB']

1. list concatenation also uses "+" operator
2. len(list) :: Returns number of elements in a list
3. list1 = list :: This doesn't make a copy of list.  list1 points to list of elements present at the memory location. It's a reference.
4. To make a copy of list :: list1 = list[:]
5. list.append() :: appends a value to the list and modifies the list. Example: list.append('C') would add fourth element to the list.
6. list.pop(<position>) :: removes element at <position>. Example: list.pop(0) removes first element from the list.
7. ':'.join(list) :: joins elements of a list to make a single string.

Sorting a list
1. sorted(list) :: sort by ascending order. Comparison depends on type of thing being compared. It can be an integer or string or mixture.
2. sorted(list, reverse=True) :: sort by descending order.
3. sorted(list, key=<>) :: custom sorting.

Tuple
Tuple is a data structure. It is kept in parenthesis and has elements separated by commas. Tuple is fixed length and is immutable. Length of a tuple can't be changed unlike list. Example: tuple = (1,'A',3)

Dictionary (and few basic functions)
Dictionary in Python is like a Hash in Perl. It has associated "key-value" pair like a real-dictionary. One of the major advantage of using a Dictionary/Hash is: It makes search super-fast. Time complexity is very less as compared to other search algorithms.

1. Initialization :: dict = {}
2. Assignment :: dict['Key1'] = 'Value1'
3. Retrieving a value :: dict['Key1'] OR dict.get('Key1')
4. Get list of all Keys :: dict.keys()
5. Get list of all Values :: dict.values()
6. Get Key and Value in same step :: dict.items(). Returns a list of all key-value pairs with each key-value as a tuple.

File Operations
1. Open a file: "f = open(filename, '<mode>')". <mode> can be read or write (r or w)
2. Close a file: f.close()
3. Read lines of a file. Using for loop:
for line in f:
  print 'line'
There are few other functions as well through which we can read lines of a file as elements of a list or as a single string. I will let readers explore that :)!

I hope this was useful! Do share your feedback.
Second Part is now available. Click here.

要查看或添加评论,请登录

社区洞察