python 1 and 2
python 1 and 2
The implementation of Python was started in the December 1989 by Guido Van
Rossum at CWI in Netherland.
In February 1991, van Rossum published the code (labeled version 0.9.0) to
alt.sources.
In 1994, Python 1.0 was released with new features like: lambda, map, filter, and
reduce.
Python 2.0 added new features like: list comprehensions, garbage collection system.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language
which was capable of Exception Handling and interfacing with Amoeba Operating
System.
Python is influenced by following programming languages:ABC language & Modula3
Python Features:
1. Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and
high level programming language.
5. Free and Open Source: Python language is freely available at offical web
address.The source-code is also available. Therefore it is open source.
7. Large Standard Library: Python has a large and broad library and provides rich set of
module and functions for rapid application development.
Python Interpreter:
Installing Python
Step 1) to download and install Python visit the official website of Python
http://www.python.org/downloads/ and choose your version. We have chosen
Python version 3.6.3
Step 2) once the download is complete, run the exe for install Python. Now click
on Install Now.
Step 4) when it finishes, you can see a screen that says the Setup was successful.
Now click on "Close".
Variable is a name which is used to refer memory location. Variable also known as identifier and
used to hold value. In Python, we don't need to specify the type of variable because Python is a
type infer language and smart enough to get variable type. Variable names can be a group of both
letters and digits, but they have to begin with a letter or an underscore.
It is recommended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.
Python does not bound us to declare variable before using in the application. It allows us to
create variable at required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable
that variable is declared automatically.
Ex:
a=10
b=10.5
Multiple Assignments:
Python allows us to assign a value to multiple variables in a single statement which is also
known as multiple assignments.
We can apply multiple assignments in two ways either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Lets see given examples,
Eg:
x=y=z=50
print (x )
print (y)
print (z)
Eg:
a,b,c=5,10,15
print (a)
print (b)
print (c)
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
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b
= 30
- (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 two
division) 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 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.
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.
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.
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 Python data structure. If the value is present in the data structure, then the
resulting value is true otherwise it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).
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 It is evaluated to be true if the reference present at both sides point to the same
object.
is not It is evaluated to be true if the reference present at both side do not point to the
same object.
Variables can hold values of different data types. Python is a dynamically typed language hence
we need not define the type of the variable while declaring it. The interpreter implicitly binds the
value with its type.
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.
A=20
b="Hi Python developers…"
c = 10.45
print(type(a));
print(type(b));
print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person's name must be stored as a
string whereas its id must be stored as an integer.
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;
Python allows us to use a lower-case L to be used with long integers. However, we must always
use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).
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.
String handling in python is a straightforward task since there are various inbuilt functions and
operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".
Output:
he
o
hello javahello java
hello java 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.
print (l * 3);
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.
t = ("hi", "python", 2)
print (t[1:]);
print (t[0:1]);
print (t);
print (t + t);
print (t * 3);
print (type(t))
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 "main.py", 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 String:-
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Here, if we check the type of the variable str using a python script
In python, strings are treated as the sequence of strings which means that python doesn't support
the character data type instead a single character written as 'p' is treated as the string of length 1.
String Operators:
Operator Description
+ It is known as concatenation operator used to join the strings given either side
of the operator.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python". To
define any string as a raw string, the character r or R is followed by the string.
str = "python"
# Calling function
str2 = str.capitalize()
# Displaying result
print("Old value:", str)
print("New value:", str2)
2. Center() Method:- Python center() method alligns string to the center by filling
paddings left and right of the string. This method takes two parameters, first is a width
and second is a fillchar which is optional. The fillchar is a character which is used to fill
left and right padding of the string.
Ex:
4. endswith() Method:-
Python endswith() method returns true of the string ends with the specified substring,
otherwise returns false.
Signature
endswith(suffix[, start[, end]])
Parameters
o suffix : a substring
o start : start index of a range
o end : last index of the range
Ex:-
str = "Java"
str2 = "C#"
# Calling function
str3 = "{} and {} both are programming languages".format(str,str2)
# displaying result
print(str3)
Output:
6. find() Method:- Python find() method finds substring in the whole string and returns
index of the first match. It returns -1 if substring does not match.
str = "Welcome to the python."
# Calling function
str2 = str.find("the")
# Displaying result
print(str2)
7. istitle() Method: Python istitle() method returns True if the string is a titlecased string.
Otherwise returns False.
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.
Advantages of loops
There are the following advantages of loops in Python.
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Python for loop example: printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
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
Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax of the
nested for loop in python is given below.
Example 1
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.
while expression:
statements
Here, the statements can be a single statement or the group of statements. The expression should
be any valid python expression resulting into true or false. The true is any non-zero value.
Example 1
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
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.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output: