Python Programming Language Overview
Python Programming Language Overview
Python is easy to learn yet powerful and versatile scripting language, which
makes it attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.
Python Features
Python provides lots of features that are listed below.
2) Expressive Language
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line
at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
Python supports object oriented language and concepts of classes and objects
come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
Python has a large and broad library and prvides rich set of module and
functions for rapid application development.
10) Integrated
Python Applications
Python is known for its general purpose nature that makes it applicable in
almost each domain of software development. Python as a whole can be used
in any sphere of development.
1) Web Applications
3) Software Development
Python is popular and widely used in scientific and numeric computing. Some
useful library and package are SciPy, Pandas, IPython etc. SciPy is group of
packages of engineering, science and mathematics.
5) Business Applications
8) 3D CAD Applications
9) Enterprise Applications
There are several such applications which can be developed using Python
Variable names can be a group of both letters and digits, but they have to
begin with a letter or an underscore.
It is recomended to use lowercase letters for variable name. Rahul and rahul
both are two different variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
Eg:
Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement
which is also known as multiple assignment.
Eg:
1. x=y=z=50
2. print (x)
3. print (y)
4. print (z)
Output:
1. 50
2. 50
3. 50
[Link] multiple values to multiple variables:
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
Basic Fundamentals:
This section contains the basic fundamentals of Python like :
ii) Comments
a)Tokens:
o Keywords.
o Identifiers.
o Literals.
o Operators.
Tuples:
o Tuple is another form of collection where different type of data can be
stored.
o It is similar to list where data is separated by commas. Only the
difference is that list uses square bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.
Eg:
1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>
Dictionary:
o Dictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be
retrieved by square bracket([]).
Eg:
di={'name':'charlie','id':100,'dept':'it'}
a=[Link]()
print(a)
OUTPUT:
dict_keys(['name', 'id', 'dept'])
EG:
di={'name':'charlie','id':100,'dept':'it'}
a=[Link]()
print(a)
OUTPUT:
dict_values(['charlie', 100, 'it'])
Python enables us to check the type of the variable used in the program.
Python provides us the type() function which returns the type of the variable
passed.
Consider the following example to define the values of different data types and
checking its type.
1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Python provides various standard data types that define the storage method on
each of them. The data types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data
types. We will discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. Python creates Number objects when a number
is assigned to a variable. For example;
String
The string can be defined as the sequence of characters represented in the
quotation marks. In python, we can use single, double, or triple quotes to
define a string.
In the case of string handling, the operator + is used to concatenate two strings
as the operation "hello"+" python" returns "hello python".
Output:
he
o
hello javathello javat
hello javat how are you
List
Lists are similar to arrays in C. However; the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed
within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation
operator (+) and repetition operator (*) works with the list in the same way as
they were working with the strings.
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of
the items of a tuple.
1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "[Link]", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative
array or a hash table where each key stores a specific value. Key can hold any
primitive data type whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma and enclosed in the
curly braces {}.
Output:
Python Keywords
Python Keywords are special reserved words which convey a special meaning
to the compiler/interpreter. Each keyword have a special meaning and a
specific operation. These keywords can't be used as variable. Following is the
List of Python Keywords.
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both
single as well as double quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known
as Single line Strings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known
as Multiple line String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
Eg:
1. >>> str2='''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
[Link] literals:
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of
lists in Python.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
[Link] Collections.
List:
o List contain items of different data types. Lists are mutable i.e.,
modifiable.
o The values stored in List are separated by commas(,) and enclosed
within a square brackets([]). We can store different type of data in a
List.
o Value stored in a List can be retrieved using the slice operator([] and
[:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the
repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
Python Operators
The operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on
which the logic is built in a particular programming language. Python provides a
variety of operators described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two
operands. It includes +(addition), - (subtraction), *(multiplication), /(divide), %
(reminder), //(floor division), and exponent (**).
Operator Description
- (Subtraction) It is used to subtract the second operand from the first operand. If
the first operand is less than the second operand, the value result
negative. For example, if a = 20, b = 10 => a ? b = 10
/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the
division) two operands.
Comparison operator
Comparison operators are used to comparing the value of the two operands
and returns boolean true or false accordingly. The comparison operators are
described in the following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the
condition becomes true.
>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.
<> If the value of two operands is not equal, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Operator Description
= It assigns the the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right operand
and assign the modified value back to left operand. For example, if a = 10, b
= 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assign the modified value back to left operand. For example, if a = 20, b
= 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assign the modified value back to left operand. For example, if a = 10, b
= 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assign the reminder back to left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two
operands.
For example,
1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the
resulting bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different otherwise the
xor) resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0,
the resulting bit will be 1 and vice versa.
<< (left The left operand value is moved left by the number of bits present in
shift) the right operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Logical Operators
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are
the two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b
are the two expressions, a → true, b → false => a or b → true.
not If an expression a is true then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value
inside a data structure. If the value is present in the data structure, then the
resulting value is true otherwise it returns false.
Operator Description
not in It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Identity Operators
Operator Description
is not It is evaluated to be true if the reference present at both side do not point to
the same object.
Operator Precedence
The precedence of the operators is important to find out since it enables us to
know which operator should be evaluated first. The precedence table of the
operators in python is given below.
Operator Description
Python Comments
Comments in Python can be used to explain any program code. It can also be
used to hide the code as well.
Comments are the most helpful stuff of any program. It enables us to
understand the way, a program works. In python, any statement written along
with # symbol is known as a comment. The interpreter does not interpret the
comment.
Comment is not a part of the program, but it enhances the interactivity of the
program and makes the program readable.
In case user wants to specify a single line comment, then comment must start
with ?#?
Eg:
Output:
Hello Python
eg:
1. ''''' This
2. Is
3. Multipline comment'''
eg:
Output:
Hello Python
Statement Description
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition to
be checked. If the condition provided in the if statement is false, then
the else statement will be executed.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow
the use of parentheses for the block level code. In Python, indentation is used
to declare a block. If two statements are at the same indentation level, then
they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.
Indentation is the most used part of the python language since it declares the
block of code. All the statements of one block are intended at the same level
indentation. We will see how the actual indentation takes place in decision
making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is
true, it executes a block of code known as if-block. The condition of if
statement can be any valid logical expression which can be either evaluated to
true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block
is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
Output:
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Example 2
1. marks = int(input("Enter the marks? "))
2. f marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. lif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. lif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. lif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. lse:
11. print("Sorry you are fail ?")
Python Loops
The flow of the programs written in any programming language is sequential by
default. Sometimes we may need to alter the flow of the program. The
execution of a specific code may need to be repeated several numbers of
times.
For this purpose, The programming languages provide various types of loops
which are capable of repeating some specific code several numbers of times.
Consider the following diagram to understand the working of a loop statement.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us
to alter the flow of the program so that instead of writing the same code again
and again, we can repeat the same code for a finite number of times. For
example, if we need to print the first 10 natural numbers then, instead of using
the print statement 10 times, we can print inside a loop which runs up to 10
iterations.
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
Example
1. i=1
2. n=int(input("Enter the number up to which you want to print the natural numbe
rs?"))
3. for i in range(0,10):
4. print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Output:
Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Example 1
1. n = int(input("Enter the number of rows you want to print?"))
2. i,j=0,0
3. for i in range(0,n):
4. print()
5. for j in range(0,i+1):
6. print("*",end="")
Output:
Example 1
1. for i in range(0,5):
2. print(i)
3. else:print("for loop completely exhausted, since there is no break.");
In the above example, for loop is executed completely since there is no break
statement in the loop. The control comes out of the loop and hence the else
block is executed.
Output:
0
1
2
3
4
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. print("The loop is broken due to break statement...came out of loop")
In the above example, the loop is broken due to break statement therefore the
else statement will not be executed. The statement present immediate next to
else block will be executed.
Output:
0
1. while expression:
2. statements
Example 1
1. i=1;
2. while i<=10:
3. print(i);
4. i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
Example 2
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number?"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i));
7. i = i+1;
Output:
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop");
Output:
Example 2
1. var = 1
2. while var != 2:
3. i = int(input("Enter the number?"))
4. print ("Entered value is %d"%(i))
Output:
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. else:print("The while loop exhausted");
Output:
1
2
3
4
5
The while loop exhausted
Example 2
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. if(i==3):
6. break;
7. else:print("The while loop exhausted");
Output:
1
2
The do while loop is used to check condition after executing the statement. It is
like while loop but it is executed at least once.
1. do {
2. //statement
3. } while (condition);
1. i = 1
2.
3. while True:
4. print(i)
5. i=i+1
6. if(i > 5):
7. break
Output:
1. 1
2. 2
3. 3
4. 4
5. 5