Python Unit 1
Python Unit 1
Introduction
Feature of Python
• Python is a high level language. It is a free and open source language.
• It is an interpreted language, as Python programs are executed by an
interpreter.
• Python programs are easy to understand as they have a clearly
defined syntax and relatively simple structure.
• Python is case-sensitive. For example, NUMBER and number are not
same in Python.
• Python is portable and platform independent, means it can run on
various operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services
and applications are built using Python.
• Python uses indentation for blocks and nested blocks.
To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter. The
interpreter is also called Python shell. A sample screen of Python interpreter is
shown in Figure.
3
In the above screen, the symbol >>> is the Python prompt, which indicates that the
interpreter is ready to take instructions. We can type commands or statements on
this prompt to execute them using a Python interpreter.
Execution Modes
There are two ways to use the Python interpreter:
(A) Interactive mode
(B) Script mode
Interactive mode allows execution of individual statement instantaneously. Whereas,
Script mode allows us to write more than one instruction in a file called Python
source code file that can be executed.
4
Working in the interactive mode is convenient for testing a single line code for
instant execution. But in the interactive mode, we cannot save the statements for
future use and we have to retype the statements to run them again.
(B) Script Mode
In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it. Python scripts are saved as files where file name has
extension “.py”. By default, the Python scripts are saved in the Python installation
folder. To execute a script, we can either:
a) Type the file name along with the path at the prompt. For example, if the
name of the file is prog5-1.py, we type prog5-1.py. We can otherwise open
the program directly from IDLE as shown in Figure 5.3.
b) While working in the script mode, after saving the file, click [Run]->[Run
Module] from the menu as shown in Figure 5.4.
c) The output appears on shell as shown in Figure 5.5.
5
6
PYTHONKEYWORDS
Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which
it has been defined. As Python is case sensitive, keywords must be written exactly
as given below.
IDENTIFIERS
In programming languages, identifiers are names used to identify a variable,
function, or other entities in a program. The rules for naming an identifier in Python
are as follows:
1. The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_). This may be followed by any combination of characters
a–z, A–Z, 0–9 or underscore (_). Thus, an identifier cannot start with a digit.
2. It can be of any length. (However, it is preferred to keep it short and
meaningful).
3. It should not be a keyword or reserved word.
4. We cannot use special symbols like !, @, #, $, %, etc.
For example, to find the average of marks obtained by a student in three subjects,
we can choose the identifiers as marks1, marks2, marks3 and avg rather than a, b,
c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
7
Similarly, to calculate the area of a rectangle, we can use identifier names, such as
area, length, breadth instead of single alphabets as identifiers for clarity and more
readability.
area = length * breadth
VARIABLES
A variable in a program is uniquely identified by a name (identifier). Variable in
Python refers to an object, an item or element that stores some value and occupies
some memory spaces. In Python we can use an assignment statement to create
new variables and assign specific values to them.
Ex:-
gender = 'M'
message = "Keep Smiling"
price = 987.9
Program 5-2 Write a program to display values of variables in Python.
#Program 5-2
#To display values of variables message = "Keep Smiling" print(message)
userNo = 101
print('User Number is', userNo)
Output:
Keep Smiling
User Number is 101
Variable declaration is implicit in Python, means variables are automatically
declared and defined when they are assigned a value the first time. Variables
must always be assigned values before they are used in expressions as otherwise it
will lead to an error in the program. Wherever a variable name occurs in an
expression, the interpreter replaces it with the value of that particular variable.
Program 5-3 Write a Python program to find the area of a rectangle given that
its length is 10 units and breadth is 20 units.
#Program 5-3
#To find the area of a rectangle length = 10
breadth = 20
8
area = length * breadth print(area)
Output:
200
COMMENTS
Comments are used to add a remark or a note in the source code. Comments are
not executed by interpreter.
In Python, a comment starts with # (hash sign). Everything following the # till the end
of that line is treated as a comment and the interpreter simply ignores it while
executing the statement.
Ex:-
#Variable amount is the total spending on #grocery
amount = 3400
#totalMarks is sum of marks in all the tests #of Mathematics
totalMarks = test1 + test2 + finalTest
Program 5-4 Write a Python program to find the sum of two numbers.
#Program 5-4
#To find the sum of two numbers num1 = 10
num2 = 20
result = num1 + num2 print(result)
Output:
30
OPERATORS
An operator is used to perform specific mathematical or logical operation on
values. The values that the operators work on are called operands.
For example, in the expression 10 + num, the value 10, and the variable num are
operands and the + (plus) sign is an operator. Python supports several kinds of
operators.
Types of Operator
Python language supports the following types of operators.
9
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
10
// Floor Division - The division of operands where 9//2 = 4
the result is the quotient in which the digits after
9.0//2.0 = 4.0,
the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e., -11//3 = -4,
rounded away from zero (towards negative
infinity) − -11.0//3 = -4.0
Comparison Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is
becomes true. similar to != operator.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to (a >= b) is not true.
the value of right operand, then condition becomes
true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
11
value of right operand, then condition becomes true.
Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
//= Floor Division It performs floor division on operators and c //= a is equivalent to
assign value to the left operand c = c // a
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively. Following table lists out the bitwise operators supported by Python
12
language with an example each in those, we use the above two variables (a and b)
as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
& Binary AND Operator copies a bit to the result if (a & b) (means 0000
it exists in both operands 1100)
13
Logical Operators
There are following logical operators supported by Python language. Assume
variable a holds 10 and variable b holds 20 then
[ Show Example ]
and Logical AND If both the operands are true then condition (a and b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. There are two membership operators as explained below −
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if
variable in the specified sequence and x is not a member of sequence y.
false otherwise.
Identity Operators
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −
14
is Evaluates to true if the variables on either
x is y, here is results in 1 if id(x)
side of the operator point to the same object
equals id(y).
and false otherwise.
Operators Precedence
The following table lists all operators from highest precedence to lowest.
1
**
Exponentiation (raise to the power)
2
~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3
* / % //
Multiply, divide, modulo and floor division
4
+-
Addition and subtraction
5
>><<
Right and left bitwise shift
6
&
Bitwise 'AND'
15
7
^|
Bitwise exclusive `OR' and regular `OR'
8
<= <>>=
Comparison operators
9
<> == !=
Equality operators
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
12
in not in
Membership operators
13
not or and
Logical operators
16
DATA TYPES
Every value belongs to a specific data type in Python. Data type identifies the type
of data values a variable can hold and the operations that can be performed on
that data. Data types available in Python:-
Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True value is non-zero, non-null and non-
empty. Boolean False is the value zero.
Variables of simple data types like integers, float, boolean, etc., hold single
values. But such variables are not useful to hold a long list of information, for
example, names of the months in a year, names of students in a class, names and
numbers in a phone book or the list of artefacts in a museum. For this, Python
provides data types like tuples, lists, dictionaries and sets.
SEQUENCE
A Python sequence is an ordered collection of items, where each item is indexed by
an integer. The three types of sequence data types available in Python are Strings,
Lists and Tuples.
String
17
String is a group of characters. These characters may be alphabets, digits or special
characters including spaces. String values are enclosed either in single quotation
18
marks (e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”). The quotes are not a
part of the string, they are used to mark the beginning and end of the string for the
interpreter.
For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2.
List
List is a sequence of items separated by commas and
the items are enclosed in square brackets [ ].
Example 5.4
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
Tuple
Tuple is a sequence of items separated by commas and items are enclosed in
parenthesis ( ). This is unlike list, where values are enclosed in brackets [ ]. Once
created, we cannot change the tuple.
Example 5.5
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a') #print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Set
Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have
duplicate entries. Once created, elements of a set cannot be changed.
Example 5.6
19
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
None
None is a special data type with a single value. It is used to signify the absence of
value in a situation. None supports no special operations, and it is neither same as
False nor 0 (zero).
Example 5.7
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }. Dictionaries permit faster access to data. Every key is
separated from its value using a colon (:) sign.
The key: value pairs of a dictionary can be accessed using the key. The keys are
usually strings and their values can be any data type. In order to access any value in
the dictionary, we have to specify its key in square brackets [ ].
Example 5.8
20
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)']) 120
The leading whitespaces (space and tabs) at the start of a line are used
to determine the indentation level of the line. We have to increase the
indent level to group the statements for that code block. Similarly,
reduce the indentation to close the grouping.
The four white spaces or a single tab character are used to create or
increase the indentation level of the code. Let’s look at an example to
understand the code indentation and grouping of statements.
deffoo():
print("Hi")
ifTrue:
print("true")
else:
print("false")
21
print("Done")
22
Input and Output
In Python, we have the input() function for taking the user input.
The input() function prompts the user to enter data. It accepts all
user input as string. The user may enter a number or a string but the
input() function treats them as strings only. The syntax for input() is:
Example 5.14
23
The syntax for print() is:
print(“Message”)
print(Variable)
print(“Message”, variable)
Note:- if you want to stop changing the new line use end=’ ‘.
Statement Output
print("Hello") Hello
print(10*2.5) 25.0
Type Conversion
Explicit conversion
24
Explicit conversion, also called type casting happens when data type
conversion takes place because the programmer forced it in the
program. The general form of an explicit data type conversion is:
Syntax:- new_data_type(expression)
Following are some of the functions in Python that are used for
explicitly converting an expression or a variable to a different type.
Output:
30.0
<class 'float'>
Conditional blocks
26
If statement:- when given condition is true then if block statement
executes otherwise control passes to next statement of the program.
Syntax:-
If condition:
statement(s)
Example
age = int(input("Enter your age "))
if age>=18:
print("Eligible to vote")
28
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
Loops
In general, statements are executed sequentially: The first statement
in a function is executed first, followed by the second, and so on.
There may be a situation when you need to execute a block of code
several number of times.
Programming languages provide a loop statement allows us to
execute a statement or group of statements multiple times.
The ‘While’ Loop
The while statement executes a block of code repeatedly as long as
the control condition of the loop is true. The control condition of the
while
loop is executed before any statement inside the loop is executed.
After each iteration, the control condition is tested again and the
loop continues as long as the condition remains true. When this
condition becomes false, the statements in the body of loop are not
executed and the control is transferred to the statement immediately
following the body of while loop. If the condition of the while loop is
initially false, the body is not executed even once.
29
body of while
Output:
1
2
3
4
5
If condition:
# execute these statements
else:
30
# execute these statements
and while loop like this are similar
While condition:
# execute these statements
else:
# execute these statements
count =0
while(count < 3):
count =count +1
print("Hello World")
else:
print("In Else Block")
Output:
Hello World
Hello World
Hello World
In Else Block
33
by default the value increases by 1 in each iteration. All parameters of
range() function must be integers. The step parameter can be a
positive or a negative integer excluding zero.
Example
#start and step not specified
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
Output:-
Dictionary Iteration
xyz 123
abc 345
Output:-
Sam
Ruby
java
Inside Else Block
Nested Loops: Python programming language allows to use one loop
inside another loop. Following section shows few examples to illustrate
the concept.
Syntax:
For iterator_var in sequence:
For iterator_var in sequence:
statements(s)
statements(s)
While expression:
While expression:
statement(s)
statement(s)
37
For example,
# Python program to illustrate nested for loops in Python
Loop Manipulation:
Output:
Current Letter : p
Current Letter : o
Current Letter : a
Current Letter : m
Current Letter : m
38
Current Letter : i
Current Letter : n
Break Statement: It brings control out of the loop
For letter in 'programming':
If letter =='r'or letter =='g':
break
print 'Current Letter :', letter
Output:
Current Letter : p
Ex:-
if(condition):
pass
else:
statement
39