Learning Python with Avnish Part 1. (Basic)



Welcome to the wonderful world of Python!
As a professional or student with working knowledge of another high-level programming language, this text was made for you in your efforts to jump straight into Python with as little overhead as possible. The goal of this book is to provide text that flows in a conversational style littered with examples to highlight your path towards Python programming.

What is Python?

So very first question is about Python, 
Python is an uncomplicated and robust programming language that delivers both the power and complexity of traditional compiled languages along with the ease-of-use (and then some) of simpler scripting and interpreted
languages. You'll be amazed at how quickly you'll pick up the language as well as what kind of things you can do with Python, not to mention the things that have already been done. Your imagination will be the only limit.

Why Python?

Because
* Easy to learn.
* Easy to maintain
* Easy to read.
* A board standard library.
* Interactive Mode
* Portable
* Extensible
* Object Oriented
* Database
* GUI Programming 
* Scalable

and much more.....

What we can do with Python?

You can automate simple tasks such as the following:-

• Moving and renaming thousands of files and sorting them into folders
• Filling out online forms, no typing required
• Downloading files or copy text from a website whenever it updates
• Having your computer text you custom notifications
• Updating or formatting Excel spreadsheets
• Checking your email and sending out prewritten responses

These tasks are simple but time-consuming for humans, and they’re often so trivial or specific that there’s no
ready-made software to perform them. Armed with a little bit of programming knowledge, you can have
your computer do these tasks for you.

How to install Python in your system?

Python is available on a wide variety of platforms including Linux, Mac OS X or Windows etc.
Open a terminal window and type "python" to find out if it is already installed and which version is installed.

If not already installed do this:-

The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python: http://www.python.org/.
You can download Python documentation from www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.

Read the instruction for the installation process.

Running Python 

There are three different way to start python.

1. Interactive Interpreter
2. Script from the Command-Line
3. Integrated Development Environment(IDLE).


Hello World! Program for Python

Veterans to software development will no doubt be ready to take a look at the famous "Hello World!" program, typically the first program that a programmer experiences when exposed to a new language. There is no exception here.
                                     
>>> print ('Hello World!')
Hello World!
                              
The print() statement is used to display output to the screen. Those of you who are familiar with C are aware that the printf() function produces screen output. Many shell script languages use the echo command for program output.

NOTE:-
Usually, when you want to see the contents of a variable, you use the print statement in your code. However, from within the interactive interpreter, you can use the print statement to give you the string representation of a variable, or just dump the variable raw—this is accomplished by simply giving the name of the variable.
In the following example, we assign a string variable, then use print to display its contents. Following that, we issue just the variable name.
                                             
>>> myString = 'Hello World!'
>>> print (myString)
Hello World!
>>> myString
'Hello World!'
                                       
Notice how just giving only the name reveals quotation marks around the string. The reason for this is to allow objects other than strings to be displayed in the same manner as this string —being able to display a printable string representation of any object, not just strings. The quotes are there to indicate that the object whose value you just dumped to the display is a string.

One final introductory note: The print() statement, paired with the string format operator ( % ), behaves even more like C's printf() function:
                                 
>>> print ("%s is number %d!" % ("Python", 1))

BASIC SYNTAX


The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

Comments

As with most scripting and Unix-shell languages, the hash/pound ( # ) sign signals that a comment begins right from the # and continues until the end of the line.
                                   
>>> # one comment
>>> print ('Hello World!')   # another comment

Hello World!

Operators

The standard mathematical operators that you are familiar with work the same way in Python as in most other languages.
                                       
+          -          *         /         %         **

                                
Addition, subtraction, multiplication, division, and modulus/remainder are all part of the standard set of operators. In addition, Python provides an exponentiation operator, the double star/asterisk ( ** ). Although we are emphasizing the mathematical nature of these operators, please note that some of these operators are overloaded for use with other data types as well, for example, strings and lists.
                                     
>>> print (-2 * 4 + 3 ** 2)
1

                               
As you can see from above, all operator priorities are what you expect: + and - at the bottom, followed by *, /, and %, then comes the unary + and -, and finally, ** at the top. (3 ** 2 is calculated first, followed by -2 * 4, then both results are summed together.)
NOTE
Although the example in the print() statement is a valid mathematical statement, with Python's hierarchical rules dictating the order in which operations are applied, adhering to good programming style means properly placing parentheses to indicate visually the grouping you have intended (see exercises). Anyone maintaining your code will thank you, and you will thank you.

Python also provides the standard comparison operators:
                                     
<          <=       >         >=        ==       !=   <>

                                
Trying out some of the comparison operators we get:
                                 
>>> 2 < 4
True
>>> 2 == 4

False
>>> 2 > 4
False
>>> 6.2 <= 6
True
>>> 6.2 <= 6.2
True
>>> 6.2 <= 6.20001
True


                               
Python currently supports two "not equals" comparison operators, != and <>. These are the C-style and ABC/Pascal-style notations. The latter is slowly being phased out, so we recommend against its use.
Python also provides the expression conjunction operators:
                                     
 and                  or               not

                               
Using these operators along with grouping parentheses, we can "chain" some of our comparisons together:
                                       
>>> (2 < 4) and (2 == 4)
False
>>> (2 > 4) or (2 < 4)
True
>>> not (6.2 <= 6)
True
>>> 3 < 4 < 5

                                
The last example is an expression that may be invalid in other languages, but in Python, it is really a short way of saying:
                                   
>>> (3 < 4) and (4 < 5)


Variables and Assignment


Rules for variables in Python are the same as they are in most other high-level languages: 
  1. It can be only one word.
  2. It can use letter, number and underscore ( _ ) character.
  3. It can't begin with a number.

Python is case-sensitive, meaning that the identifier "cAsE" is different from "CaSe."

Python is dynamically typed, meaning that no pre-declaration of a variable or its type is necessary. The type (and value) are initialized on assignment. Assignments are performed using the equals sign.
                                     
>>> counter = 0
>>> miles = 1000.0
>>> name = 'Bob'
>>> counter = counter + 1
>>> kilometers = 1.609 * miles
>>> print ('%f miles is the same as %f km' % (miles, kilometers))

1000.000000 miles is the same as 1609.000000 km

Common Data Types in Python:-
  • Integers
  • Floating Point Number
  • Strings

Numbers

Python supports four different numerical types:
  • int (signed integers)
  • long (long integers [can also be represented in octal and hexadecimal])
  • float (floating point real values)
  • complex (complex numbers)
Here are some examples:
int010184-2370x80017-680-0X92
long29979062458L-84140l0xDECADEDEADBEEFBADFEEDDEAL
float3.141594.2E-10-90.6.022e23-1.609E-19
complex6.23+1.5j-1.23-875J0+1j9.80665-8.31441J-.0224+0j
Numeric types of interest are the Python long and complex types. Python long integers should not be confused with C long. Python long has a capacity that surpasses any C long. You are limited only by the amount of (virtual) memory in your system as far as range is concerned. If you are familiar with Java, a Python long is similar to numbers of the BigInteger class type.

Complex numbers (numbers which involve the square root of -1, so-called "imaginary" numbers) are not supported in many languages and perhaps are implemented only as classes in others.

Strings

Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. Here are some examples of strings and string usage:
                                 
>>> pystr = 'Python'
>>> iscool = 'is cool!'
>>> pystr[0]
'P'
>>> pystr[2:5]
'tho'
>>> iscool[:2]
'is'
>>> iscool[3:]
'cool!'
>>> iscool[-1]
'!'
>>> pystr + iscool
'Pythonis cool!'
>>> pystr + ' ' + iscool
'Python is cool!'
>>> pystr * 2
'PythonPython'
>>> '-' * 20

'--------------------'

Note: - We will learn more about Number and String in later Chapters.

Lists and Tuples

Lists and tuples can be thought of as generic "buckets" with which to hold an arbitrary number of arbitrary Python objects. The items are ordered and accessed via index offsets, similar to arrays, except that lists and tuples can store different types of objects.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ), and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of for now as "read-only" lists. Subsets can be taken with the slice operator ( [] and [: ] ) in the same manner as strings.
                                  
>>> aList = [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aLlist
[1, 5, 3, 4]

                                
Slice access to a tuple is similar, except for being able to set a value (as in aList[1] = 5 above).
                               
>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[0]
'robots'
>>> aTuple[2:]
(93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>> aTuple[1] = 5
Traceback (innermost last):
  File "", line 1, in ?

TypeError: object doesn\qt support item assignment

Dictionaries

Dictionaries are Python's hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. Keys can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ( { } ).
                                 
>>> aDict = {}
>>> aDict['host'] = 'earth'
>>> aDict['port'] = 80
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'


Thanks.

Next Post Previous Post
No Comment
Add Comment
comment url