Introduction
Python
was created by Guido Van Rossum when he was working at CWI (Centrum Wiskunde
& Informatica) which is a National Research Institute for Mathematics and Computer
Science in Netherlands. The language was released in I991. Python got its name
from a BBC comedy series from seventies- “Monty Python‟s Flying Circus”. Python
can be used to follow both Procedural approach and Object Oriented approach of programming. It
is free to use.
Some of the features which make Python so popular are as follows:
v It is a general purpose programming language which
can be used for both scientific and non-scientific programming.
v It is a platform independent
programming language.
v It is a very simple high level
language with vast library of add-on modules.
v It is excellent for beginners as the language is
interpreted, hence gives immediate results.
v The programs written in Python are easily readable
and understandable.
v It is suitable as an extension language for
customizable applications.
v
It is easy to learn and use.
The
language is used by companies in real revenue generating products, such as:
v In operations of Google search engine, youtube,
etc.
v Bit Torrent peer to peer file sharing is written
using Python
v Intel, Cisco, HP, IBM, etc use Python for hardware
testing.
v Maya provides a Python scripting API
v i–Robot uses Python to develop commercial Robot.
v
NASA and others use Python for their scientific programming task.
First Step with Python
To
write and run Python program, we need to have Python interpreter installed in
our computer.
IDLE (GUI integrated) is the standard, most popular Python development environment.
IDLE is an acronym of Integrated Development Environment. It lets edit, run,
browse and debug Python Programs from a single interface. This environment makes it easy to
write programs.
We will be using version 3.x of Python IDLE to develop and run
Python code, in this course.
It can be downloaded from www.python.org
Python
shell can be used in two ways, viz., interactive mode and script mode. Where
Interactive Mode, as the name suggests, allows us to interact with OS; script
mode let us create and edit python source file. Now, we will first start with
interactive mode. Here, we type a Python statement and the interpreter displays
the result(s) immediately.
Keywords
Keywords are the reserved words in Python. We cannot use a keyword
as variable name, function name or any other identifier. They are used to define
the syntax and structure of the Python language. In Python, keywords are case
sensitive.
There are 33 keywords in Python 3.x. This number can vary slightly
in course of time. All the keywords except True, False and None are in
lowercase and they must be written as it is. The list of all the keywords are
given below.
Identifier is the name given to entities like class, functions,
variables etc. in Python. It helps differentiating one entity from another.
Rules for writing identifiers in Python
1. Identifiers can be a combination of letters in lowercase (a to
z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names like
myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid,
but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
5. Identifier can be of any length.
Things to care about
Python is a case-sensitive language. This means, Variable and
variable are not the same. Always name identifiers that make sense. While, c =
10 is valid. Writing count = 10 would make more sense and it would be easier to
figure out what it does even when you look at your code after a long gap.
Multiple words can be separated using an underscore, this_is_a_long_variable.
We can also use camel-case style of writing, i.e., capitalize every first
letter of the word except the initial word without any spaces. For example:
camelCaseExample
Python Statement, Indentation and Comments
Python Statement
Instructions that a Python interpreter can execute are called
statements. For example, a = 1 is an assignment statement. if statement, for
statement, while statement etc. are other kinds of statements which will be
discussed later.
Multi-line statement
In Python, end of a statement is marked by a newline character.
But we can make a statement extend over multiple lines with the line
continuation character (\).
For example:
For example:
a = 1 + 2 + 3 + \ 4 + 5
+ 6 + \ 7 + 8 + 9
This is explicit line continuation. In Python, line continuation
is implied inside parentheses ( ), brackets [ ] and braces { }. For instance,
we can implement the above multi-line statement as a = (1 + 2 + 3 + 4 + 5 +
6 + 7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation
implicitly. Same is the case with [ ] and { }. For example: colors = ['red',
'blue', 'green']
We could also put multiple statements in a single line using
semicolons, as follows
a = 1; b = 2; c = 3
Most of the programming languages like C, C++, Java use braces { }
to define a block of code. Python uses indentation. A code block (body of a
function, loop etc.) starts with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it must be consistent
throughout that block. Generally four whitespaces are used for indentation and
is preferred over tabs. Here is an example.
for i in range(1,11): print(i) if i == 5: break
The enforcement of indentation in Python makes the code look neat and clean. This results into Python programs that look similar and consistent. Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code more readable. For example:
if True:
print('Hello') a = 5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is
clearer. Incorrect indentation will result into IndentationError.
Python Comments
Comments are very important while writing a program. It describes
what's going on inside a program so that a person looking at the source code
does not have a hard time figuring it out. You might forget the key details of
the program you just wrote in a month's time. So taking time to explain these
concepts in form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
#This is a comment #print out Hello print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing
it is to use hash (#) in the beginning of each line. For example:
#This is a long comment #and it extends #to multiple lines
Another way of doing this is to use triple quotes, either ''' or
""". These triple quotes are generally used for multi-line
strings. But they can be used as multi-line comment as well. Unless they are
not docstrings, they do not generate any extra code.
"""This is also a perfect example of multi-line
comments"""
Docstring
Docstring is short for documentation string. It is a string that
occurs as the first statement in a module, function, class, or method
definition. We must write what a function/class does in the docstring. Triple
quotes are used while writing docstrings.
For example:
For example:
def double(num):
"""Function to double the value""" return 2*num
Docstring is available to us as the attribute __doc__ of the
function.
>>> print(double.__doc__) Function to double the value
Python Variables
Python Variables
A variable is a location in memory used to store some data
(value). They are given unique names to differentiate between different memory
locations. The rules for writing a variable name is same as the rules for
writing identifiers in Python.
We don't need to declare a variable before using it. In Python, we
simply assign a value to a variable and it will exist. We don't even have to
declare the type of the variable. This is handled internally according to the
type of value we assign to the variable.
Variable assignment
We use the assignment operator (=) to assign values to a variable.
Any type of value can be assigned to any valid variable.
a = 5 b = 3.2 c = "Hello"
Here, we have three assignment statements. 5 is an integer
assigned to the variable a. Similarly, 3.2 is a floating point number and
"Hello" is a string (sequence of characters) assigned to the
variables b and c respectively.
Multiple assignments
In Python, multiple assignments can be made in a single statement
as follows:
a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once,
we can do this as x = y = z = "same"
This assigns the "same" string to all the three
variables.
When we create a program, we often like to store values so that it can be used later. We use objects to capture data, which then can be manipulated by computer to provide information. By now we know that object/ variable is a name which refers to a value.
Every object has:
A. An Identity, - can be known using id (object
B. A type – can be checked using type (object) and
C. A value
A. Identity of the object: It is the object's address in memory and does not change once it has been created
B. Type (i.e data type): It is a set of values, and the allowable operations on those values. It can be one of the following:
1. Number
Number data type stores Numerical Values. This data type is immutable i.e. value of its object cannot be changed. These are of three different types:
a) Integer
b) Float/floating point
c) Complex
a) Integer
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17. While writing a large integer value, don‟t use commas to separate digits. Also integers should not have leading zeros.When we are working with integers, we need not to worry about the size of integer as a very big integer value is automatically handled by Python.
Example
>>> a = 10
>>> c= 4298114
>>> type(c)
<type 'int'>
Integers contain Boolean Type which is a unique data type, consisting of two constants, True & False. A Boolean True value is Non-Zero, Non-Null and Non-empty.
Example
>>> flag = True
>>> type(flag)
<type 'bool'>
b) Floating Point: Numbers with fractions or decimal point are called floating point numbers.
A floating point number will consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be used to represent a number in engineering/ scientific notation.
Example
-2.0X 10 power 5 will be represented as -2.0e5 , 2.0X10 power -5 will be 2.0E-5
Example
y= 12.36
c) Complex: Complex number in python is made up of two floating point values, one each for real and imaginary part. For accessing different parts of variable (object) x; we will use x.real and x.image. Imaginary part of the number is represented by „j‟ instead of „i‟, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
This is special data type with single value. It is used to signify the absence of value/false in a situation. It is represented by None.
String: is an ordered sequence of letters/characters. They are enclosed in single quotes (' ') or double (" ").These are immutable data types.
Example
>>> a = 'Ram'
>>> type ("Good Morning")
<type "str">
>>> type ("3.2")
<type "str">
Conversion from string type to another data type
It is possible to change one type of value/ variable to another type. It is known as type conversion or type casting. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type). For explicit type casting, we use functions (constructors):
int ()
float ()
str ()
bool ()
Lists: List is also a sequence of values of any type. Values in the list are called elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets.
Example
list = ["spam‟, 20.5,5]
Examples of List
>>> list=['aman',678,20.4,'saurav']
>>> list1=[456,'rahul']
>>> list
['aman', 678, 20.4, 'saurav']
>>> list[1:3]
[678, 20.4]
>>> list+list1
['aman', 678, 20.4, 'saurav', 456, 'rahul']
>>> list1*2
[456, 'rahul', 456, 'rahul']
>>>
Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are enclosed in ().
c) Value of Object (variable) – to bind value to a variable, we use assignment operator (=). This is also known as building of a variable.
Example
>>> pi = 31415
Here, value on RHS of "= " is assigned to newly created " pi " variable.
Example
>>>x=5
Will create a value 5 referenced by x
x ---> 5
>>>y=x
This statement will make y refer to 5 of x
>>> x=x+y
As x being integer (immutable type) has been rebuild.
In the statement, expression on RHS will result into value 10 and when this is assigned
to LHS (x), x will rebuild to 10. So now
x--------> 10
y--------> 5
When we create a program, we often like to store values so that it can be used later. We use objects to capture data, which then can be manipulated by computer to provide information. By now we know that object/ variable is a name which refers to a value.
Every object has:
A. An Identity, - can be known using id (object
B. A type – can be checked using type (object) and
C. A value
A. Identity of the object: It is the object's address in memory and does not change once it has been created
B. Type (i.e data type): It is a set of values, and the allowable operations on those values. It can be one of the following:
1. Number
Number data type stores Numerical Values. This data type is immutable i.e. value of its object cannot be changed. These are of three different types:
a) Integer
b) Float/floating point
c) Complex
a) Integer
Example
>>> a = 10
>>> c= 4298114
>>> type(c)
<type 'int'>
Integers contain Boolean Type which is a unique data type, consisting of two constants, True & False. A Boolean True value is Non-Zero, Non-Null and Non-empty.
Example
>>> flag = True
>>> type(flag)
<type 'bool'>
b) Floating Point: Numbers with fractions or decimal point are called floating point numbers.
A floating point number will consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be used to represent a number in engineering/ scientific notation.
Example
-2.0X 10 power 5 will be represented as -2.0e5 , 2.0X10 power -5 will be 2.0E-5
Example
y= 12.36
c) Complex: Complex number in python is made up of two floating point values, one each for real and imaginary part. For accessing different parts of variable (object) x; we will use x.real and x.image. Imaginary part of the number is represented by „j‟ instead of „i‟, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
2. None
This is special data type with single value. It is used to signify the absence of value/false in a situation. It is represented by None.
3. Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and non mutable data types. Three types of sequence data type available in Python are Strings, Lists & Tuples.String: is an ordered sequence of letters/characters. They are enclosed in single quotes (' ') or double (" ").These are immutable data types.
Example
>>> a = 'Ram'
>>> type ("Good Morning")
<type "str">
>>> type ("3.2")
<type "str">
Conversion from string type to another data type
It is possible to change one type of value/ variable to another type. It is known as type conversion or type casting. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type). For explicit type casting, we use functions (constructors):
int ()
float ()
str ()
bool ()
Example
>>> a= 12.34
>>> b= int(a)
>>> print b
12
Example
>>>a=25
>>>y=float(a)
>>>print y
25.0
Lists: List is also a sequence of values of any type. Values in the list are called elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets.
Example
list = ["spam‟, 20.5,5]
Examples of List
>>> list=['aman',678,20.4,'saurav']
>>> list1=[456,'rahul']
>>> list
['aman', 678, 20.4, 'saurav']
>>> list[1:3]
[678, 20.4]
>>> list+list1
['aman', 678, 20.4, 'saurav', 456, 'rahul']
>>> list1*2
[456, 'rahul', 456, 'rahul']
>>>
Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are enclosed in ().
c) Value of Object (variable) – to bind value to a variable, we use assignment operator (=). This is also known as building of a variable.
Example
>>> pi = 31415
Here, value on RHS of "= " is assigned to newly created " pi " variable.
Mutable and Immutable Variables
A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.Example
>>>x=5
Will create a value 5 referenced by x
x ---> 5
>>>y=x
This statement will make y refer to 5 of x
>>> x=x+y
As x being integer (immutable type) has been rebuild.
In the statement, expression on RHS will result into value 10 and when this is assigned
to LHS (x), x will rebuild to 10. So now
x--------> 10
y--------> 5
It is a good practice to follow these identifier naming conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lower case letters
Operators and Operands
Operators are particular symbols that are used to perform operations on operands. It returns result that can be used in application form an expression
Types of Operators
Python supports the following operators
- Arithmetic Operators.
- Relational Operators.
- Assignment Operators.
- Logical Operators.
- Membership Operators.
- Identity Operators.
- Bitwise Operators.
Arithmetic Operators
The following table contains the arithmetic operators that are used to perform arithmetic operations.
Symbol
|
Description
|
Example 1
|
Example 2
|
+
|
Addition
|
>>>55+45
100
|
>>>”Good‟
+ “Morning‟
GoodMorning
|
_
|
Subtraction
|
>>>55-45
10
|
>>>30-80
-50
|
*
|
Multiplication
|
>>>55*45
2475
|
>>>
„Good‟* 3
GoodGoodGood
|
/
|
Division
|
>>>10/3
3.33333335
|
>>>15/6
2.5
|
//
|
Perform Floor
division
|
>>>10
// 3
3
|
>>>15
// 6
2
|
%
|
Remainder /
Modulo
|
>>>17%5
2
|
>>>
23%2
1
|
**
|
Exponentiation
|
>>>2**3
8
|
>>>16**.5
4.0
>>>2**8
256
|
Relational Operators
The following table contains the relational operators that are used to check relations.
Symbol
|
Description
|
Example 1
|
Example 2
|
<
|
Less than
|
>>>7<10
True
>>>
7<5
False
>>>
7<10<15
True
>>>7<10
and 10<15
True
|
>>>„Hello‟<
‟Goodbye‟
False
>>>'Goodbye'<
'Hello'
True
|
>
|
Greater than
|
>>>7>5
True
>>>10<10
False
|
>>>„Hello‟>
„Goodbye‟
True
>>>'Goodbye'>
'Hello'
False
|
<=
|
less than
equal to
|
>>>
2<=5
True
>>>
7<=4
False
|
>>>„Hello‟<=
„Goodbye‟
False
>>>'Goodbye'
<= 'Hello'
True
|
>=
|
greater than
equal
to
|
>>>10>=10
True
>>>10>=12
False
|
>>>‟Hello‟>=
„Goodbye‟
True
>>>'Goodbye'
>= 'Hello'
False
|
!
=, <>
|
not equal to
|
>>>10!=11
True
>>>10!=10
False
|
>>>‟Hello‟!=
„HELLO‟
True
>>>
„Hello‟ != „Hello‟
False
|
==
|
equal to
|
>>>10==10
True
>>>10==11
False
|
>>>„Hello‟
== „Hello‟
True
>>>‟Hello‟
== „Good Bye‟
False
|
Assignment Operators
The following table contains the assignment operators that are used to assign values to the variables.
Symbol
|
Description
|
Example 1
|
Example 2
|
=
|
Assignment
|
>>> c=10
>>> c 10 |
>>>y=‟greetings‟
|
/=
|
Divide and Assign
|
||
+=
|
Add and assign
|
>>> c+=5
>>> c
15
|
|
-=
|
Subtract and Assign
|
>>> c-=5
>>> c
10
|
|
*=
|
Multiply and assign
|
>>> c*=2
>>> c
20
|
|
%=
|
Modulus and assign
|
>>> c%=3
>>> c
1
|
|
**=
|
Exponent and assign
|
>>> c=5
>>> c**=2
>>> c
25
|
|
//=
|
Floor division and assign
|
>>> c//=2
>>> c
12
>>>
|
Logical
Operators
The following table contains the arithmetic operators that are
used to perform arithmetic operations.
Symbol
|
Description
|
Example 1
|
Example 2
|
and
|
Logical
AND(When both conditions are true output will be true)
|
a=5>4 and 3>2
print a
TRUE
|
|
or
|
Logical
OR (If any one condition is true output will be true)
|
b=5>4 or 3<2
print b
TRUE
|
|
not
|
Logical
NOT(Compliment the condition i.e., reverse)
|
c=not(5>4)
print c
FALSE
|
Membership Operators
The following table contains the membership
operators.
Symbol
|
Description
|
Example 1
|
in
|
Returns
true if a variable is in sequence of another variable, else false.
|
a=10
b=20
list=[10,20,30,40,50];
if (a in list):
print "a is in given list"
else:
print "a is not in given list"
if(b not in list):
print "b is not given in list"
else:
print "b is given in list"
OUTPUT
a is in given list b is given in list >>> |
not in
|
Returns
true if a variable is not in sequence of another variable, else false.
|
Identity
Operators
The following table contains the identity operators.
Symbol
|
Description
|
Example 1
|
is
|
Returns
true if identity of two operands are same, else false
|
a=20
b=20 if( a is b): print a,b have same identity
else:
print a, b are different
b=10
if( a is not b): print a,b have different identity
else: print a,b have same identity
OUTPUT >>> a,b have same identity a,b have different identity >>> |
is
not
|
Returns
true if identity of two operands are not same, else false.
|
Expression and Statements
An expression is
a combination of value(s) (i.e. constant), variable and operators. It generates
a single value, which by itself is an expression.
10+5 and 9+4+2 are
two expressions which will result into value 15. Taking another example, 5.0/4+
(6- 3.0) is an expression in which values of different data types are used.
These type of expressions are also known as mixed type expressions. When mixed
type expressions are evaluated, Python promote
A Python
statement is a unit of code that the Python interpreter can execute. Example of statement are:
>>> x=5
>>>
area=x**2 #assignment statement
>>>print
x #print statement
5
>>>print
area
25
>>>
print x, area
5 25
While writing
Python statements, keep the following points in mind:
- Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
- Comment starts with „#‟ outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by interpreter.
- For a long statement, spanning multiple physical lines, we can use „/‟ at the end of physical line to logically join it with next physical line. Use of the „/‟ for joining lines is not required with expression consists of ( ), [ ], { }
- When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
- Indentation is used to represent the embedded statement(s) in a compound/Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
- White space in the beginning of line is part of indentation, elsewhere it is not significant.
The following table lists all operators from
highest precedence to lowest.
|
Operator
|
Description
|
|
**
|
Exponentiation (raise to the power)
|
|
~ + -
|
Complement, unary plus and minus (method names for the
last two are +@ and -@)
|
|
* / % //
|
Multiply, divide, modulo and floor division
|
|
+ -
|
Addition and subtraction
|
|
>> <<
|
Right and left bitwise shift
|
|
&
|
Bitwise 'AND'td>
|
|
^ |
|
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
|
Operator
precedence affects how an expression is evaluated.
For
example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first multiplies 3*2 and then adds into 7.
Here,
operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom.
Example
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #(
30 * 15 ) / 5
print "Value of (a + b)
* c / d is ", e
e = ((a + b) * c) / d #
(30 * 15 ) / 5
print "Value of ((a +
b) * c) / d is ", e
e = (a + b) * (c / d); #
(30) * (15/5)
print "Value of (a + b)
* (c / d) is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b
* c) / d is ", e
When you
execute the above program, it produces the following result −
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
sir,please upload DATA HANDLING
ReplyDelete
ReplyDeleteThanks so much for a great post. I'd like to know more about these topics and hope that I can receive more insight into this topic.
Click Here : used-bakhoe 420f 0skr02123 for sale