Introduction to Python
Introduction to Python
Python was developed by Guido Van Rossum
at the National Research Institute for Mathematics and Computer Science in
Netherlands during 1985-1990. Python is derived from many other languages,
including ABC, Modula-3,C,C++,Algol-68,SmallTalk,Unix shell and other scripting
languages. Rossum was inspired by Monty Python's Flying Circus, a BBC comedy
series and he wanted the name of his new language to be short, unique and
mysterious. Hence he named it python. It is general-purpose interpreted,
interactive, object-oriented, and high-level programming language. Python
source code is available under the GNU General Public License(GPL) and is now
maintained by a core development team at the National Research Institute.
Features
of Python
5. Scalable
6. Extendable
7. Dynamic
8. GUI Programming and Database
9. Broad Standard Library
1.
Simple
and easy-to-learn
2.
Interpreted
and interactive
3.
Object-oriented
4.
Portable
How
to Run Python
There are three different ways to start
python
a)
Using Interactive Interpreter
You can start python from Unix, DOS, or any other
system that provides you a command-line interpreter or shell window. Get into
command line of python. For Unix/Linux, you can get into interactive mode by
typing $python or python%. For windows/DOS it is c:>python.
Invoking
the interpreter without passing a script file as a parameter brings up the
following prompt-
$ python
python
2.7.10 (default, sep 27 2015, 18:11:38)
[GCI 5.1.1
20150422 (Red Hat 5.1.1-1)] on linux2
Type
"help", "copyright", "credits" or
"license" for more
information
>>>
Type the following text at python prompt
and press enter:
>>>print("programming in python")
The result will be as given below
programming in python
>>>
b)
Scripts From Command Line
This method invokes the interpreter with
a script parameter which begins the execution of the script and continues until
the script is finished. When the script is finished, the interpreter is no
longer active. a python script can be executed at command line by invoking the
interpreter on your application, as follows.
for
Unix/Linux $python script.py or python%
script.py
for windows/DOS c:>python script.py
c) Integrated Development Environment
You can run
python from Graphical User Interface(GUI) environment as well, if you have a
GUI application on your system that supports python. IDLE is the integrated
Development Environment(IDE) for UNIX and pythonWin is the first window
interface for python.
Identifiers
A python
identifier is a name used to identify a variable, function, class, module or
any other object. Python is case sensitive and hence uppercase and lowercase
letters are considered distinct. The following are rules for naming an
identifier in python.
1.
Identifier
can be combination of letters in lowercase(a to z) or uppercase(A to Z) or
digit(0-9) or an underscore(_). For example total and Total is different.
2.
Reserved
keywords cannot be used as an identifier.
3.
Identifiers
cannot begin with a digit.
4.
Special
symbols like !,@,#, etc cannot be used in an identifier. For example sum@ is an
invalid identifier.
5.
Identifier
can be of any length.
Reserved Keywords
These are
keywords reserved by the programming language and prevent the user or the
programmer from using it as it as an identifier in a program. There are 33
keywords in python 3.3. This number may vary with different versions. To
retrieve the keywords in python the following code can be given at the prompt.
>>> import keyword
>>> print(keyword.kwlist)
The following list in table shows the python
keywords.
False
|
class
|
finally
|
is
|
return
|
None
|
continue
|
for
|
lambda
|
try
|
True
|
def
|
from
|
nonlocal
|
while
|
and
|
del
|
global
|
not
|
with
|
as
|
elif
|
if
|
or
|
yield
|
assert
|
else
|
import
|
pass
|
break
|
except
|
in
|
raise
|
Variables
Variables are
reserved memory locations to store values. Based on the data type of a
variable, the interpreter allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
Python variables do not need
explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign(=) is used
to assign values to variables. The operand to the left of the = operator is the
name of the variable and the operand to the right of the = operator is the
value stored in that variable.
Example program
a = 100
b = 1000
print(a)
print(b)
output
100
1000
Comments in Python
Comments are
very important while writing a program. It describes what the source code has
done. Comments are for programmers for better understanding of a program. In
python , we use the hash(#) symbol to start writing a comment. All the
character after the #and up to the end of the physical line are part of the
comment.
Example program
>>>#this is demo of comment
>>>print("hello")
For multiline
comments use triple quotes, either ''' or """. the statements
within the start and end of triple quotes are considered as comment.
Indentation in Python
Most of the programming languages like
c, c++ use braces{} to define a block of code. Python uses indentation. A code
block starts with indentation and ends with the first unindented line. The
amount of indentation can be decided by the programmer, but it ,must be
consistent throughout the block. Generally four whitespaces are used for
indentation.
Example
program
if True:
print("correct")
else:
print("Wrong")
Multi-line
statement
Instructions that a python interpreter
can execute are called statements. In python, end of a statement is marked by a
newline character, but we can make statement extend over multiple lines with
the line continuation character(\).
grand_total = first_item +\
second_item+\
third_item
Input,
Output and Import Functions
Displaying
the Output
The function used to print output on a
screen is print statement where you can pass zero or more expression separated
by commas. The print function converts the expression you pass into a string
and writes the result to standard output.
Example
program
>>>a=2
>>>print("the
value of a is:",a)
the value
of a is 2
>>>
By default a space is added after the
text and before the value of variable a. The syntax of print function is given
below
print *objects, sep=' ', end='\n',
file=sys.stdout,flush=False
Here
objects are the value to be printed . sep is the separator used between the
values. spaces character is the default separator. end is printed after printing all the values. The default value of
end is a newline. file is the object where the values are printed and its
default value is sys.stdout(screen). Flush determines whether the output stream
needs to be flushed for any waiting output.
Reading
the Input
Python provides two built-in functions
to read from standard input(keyboard). These functions are raw_input and input.
Example
program
str = input("enter your name:")
print("your
name is: ",str)
output
enter your name: abc
your name
is: abc
Import
function
When the program grows bigger or when
there are segments of code that is frequently used, it can be stored in
different modules. A module is a file containing python definition and
statements. Python modules have a file name and end with expression .py.
Definition inside a module can be imported to another module or the interactive
interpreter in python. We use the import keyword to do this .
Example
program
>>>import math
>>>math.pi
3.141592653589793
Operators
Operators are the constructs which can
manipulate the value of operands. Consider the expression a = b+c, here a, b
and c are operands and +, = are operators. There are different types of
operators.
1.
Arithmetic
operators
2.
Comparison
operators
3.
Assignment
operators
4.
Logical
operators
5.
Bitwise
operators
6.
Membership
operators
7.
Identity
operators
Arithmetic
Operators
Arithmetic operators are used for
performing basic arithmetic operations. The following table shows the
arithmetic operators supported by python
Operator
|
Operation
|
Description
|
+
|
Addition
|
Adds
values on either side of operator
|
-
|
Subtraction
|
Subtracts
right hand operand from left hand operand
|
*
|
Multiplication
|
Multiplies
values on either side of the operator
|
/
|
Division
|
Divides
left hand operand by the right hand operand
|
%
|
Modulus
|
Divides
left hand operand by right hand operand and returns remainder
|
**
|
Exponent
|
Performs
exponential calculation on operands
|
//
|
Floor
division
|
The
division of Operands where the result is the quotient in which the digits
after the decimal point are removed
|
Comparison
Operator
These operators compare the values on
either sides of them and decide the relation among them. They are also called
as relational operators. The following table shows the comparison operators
supported by python
Operator
|
Description
|
==
|
If
the values of two operands are equal, then the condition becomes true.
|
!=
|
If
the values of two operands are not equal, then the condition becomes true.
|
>
|
If
the values of left operands is greater than the value of right operand, then
the condition becomes true.
|
<
|
If
the values of left operands is lesser than the value of right operand, then
the condition becomes true.
|
>=
|
If
the values of left operands is greater than or equal to the value of right
operand, then the condition becomes true.
|
<=
|
If
the values of left operands is lesser than or equal to the value of right
operand, then the condition becomes true.
|
Assignment
Operators
Python provides various assignment
operators. Various shorthand operators for addition, subtraction,
multiplication, division, modulus, exponent and floor division are also
supported by python. The following table shows the assignment operators
supported by python
Operator
|
Description
|
=
|
Assigns
values from right side operand to left side operand
|
+=
|
It
adds right operand to the left operand and assign the result to left operand
|
-+
|
It
subtracts right operand from the left operand and assign the result to left
operand
|
*=
|
It
multiplies right operand with the left operand and assign the result to left
operand
|
/=
|
It
divides right operand by the left operand and assign the result to left
operand
|
%=
|
It
takes modulus using two operands and assign the result to left operand
|
**=
|
Performs
exponential calculation on operands and assign values to the left
|
//=
|
It
performs floor division on operators and assign value to the left operand
|
Bitwise
Operators
Bitwise operator works on bits and
perform bit by bit operation. The following table shows the bitwise operators
supported by python.
Operator
|
Operation
|
Description
|
&
|
Binary
AND
|
Operator
copies a bit to the result if it exists in both operands
|
|
|
Binary
OR
|
It
copies a bit if it exists in either operand.
|
^
|
Binary
XOR
|
It
copies the bit if it is set in one operand but not both
|
~
|
Binary
ones complement
|
It
is unary and ahs the effect of 'flipping' bits.
|
<<
|
Binary
Left Shift
|
The
left operands value is moved left by the number of bits specified by the
right operand.
|
>>
|
Binary
Right Shift
|
The
left operands value is moved right by the number of bits specified by the
right operand.
|
Logical
Operators
Table shows the various logical
operators supported by python language.
Operator
|
Operation
|
Description
|
and
|
Logical
And
|
If
both the operands are true then condition becomes true
|
or
|
Logical
OR
|
If
any of the operand is true then condition becomes true
|
not
|
Logical
NOT
|
Used
to reverse the logical state of its operand
|
Membership
Operators
Python's membership operators test for
membership in a sequence, such as strings, lists, and tuples. There are two
membership operators supported by python which are described in the following
table.
Operator
|
Description
|
in
|
Evaluates
to true if the variable on either side of the operator point to the same
object and false otherwise
|
not
in
|
Evaluates
to true if it does not finds a variable in the specifies sequence and false
otherwise.
|
Identity
Operator
Identity operators compare the memory
locations of two objects. There are two identity operators as shown in the
following table
Operator
|
Description
|
is
|
Evaluates
to true if the variables on either side of the operator point to the same
objects and false otherwise
|
is
not
|
Evaluates
to false if the variables on either side of the operator point to the same
objects and true otherwise
|
Operator
Precedence
The following table lists all operators
from highest precedence to lowest.
Operator
|
Description
|
**
|
Exponentiation
|
~,+,-
|
Complement,
unary plus and minus
|
*,/,%,//
|
Multiply,
divide, modulo and floor division
|
+,-
|
Addition
and subtraction
|
>>,<<
|
Right
and left bitwise shift
|
&
|
Bitwise
AND
|
^,|
|
Bitwise
exclusive 'OR' and regular 'OR'
|
<=,<
>,>=
|
Comparison
operators
|
<
>, ==,!=
|
Equality
operators
|
=,%=,/=,//=,-=,+=,*=,**=
|
Assignment
operators
|
is,
is not
|
Identity
operators
|
in,
not in
|
Membership
operators
|
not,
or, and
|
Logical
operators
|
0 comments:
Post a Comment