phython-UNIT-I Notes Mar18
phython-UNIT-I Notes Mar18
kirankumar
Assistant Professor
CMRTC
UNIT–I 8L
IntroductiontoPython:History,Features,Applications
,FirstPythonProgram,Variables,Data Types,
Numbers, Operators, Input and Outputstatements.
ControlStatements:ConditionalStatements,AWordo
nIndentation,LoopingStatements,the else Suite,
break, continue, pass, assert,return.
•What is Python?
•Python is a general purpose, dynamic-typed, high-level, interpreted and Object Oriented
programming language.
•Python was invented by Guido Van Rossum in the year 1989, but it was introduced into the
market on 20th February 1991.
•Using Python, one can solve complex problems in less time with fewer lines of code.
•On December 3, 2008, Python 3.0 (also called "Py3K") was released.
It was designed to rectify the 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
the Amoeba Operating System.
•On the other hand, Python 3 uses input() function which automatically
interpreted the type of input entered by the user. However, we can cast
this value to any type by using primitive functions (int(), str(), etc.).
•In Python 2, the implicit string type is ASCII, whereas, in Python 3,
the implicit string type is Unicode.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run
Module". It will display the output to the shell.
The output will be
shown as follows.
Variable:
•A Python Variable is a name given to memory location. Python variable
is also known as an identifier and used to hold value.
•Python Variable is containers that store values.
•In Python, we don't need to specify the type of variable.
•When a variable is defined, we must create it with a value. If the value
is not assigned the variable gives an error stating that variable is not
defined
Syntax
variable_name = value
Ex:
roll_no = 101
print('Student rollno is’,roll_no)
Output:
<class 'int'>
250
Displaying data type of a variable
The Python programming language provides a built-in function type( ) to
display the data type of a variable
Syntax:
Type(variable name)
Ex:
a = 105
print(type(a))
a = 10.66
print(type(a))
a = 'rama'
print(type(a))
Python Variable Types
There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
•A Variable declared with in the function is known as Local variable
Local variable have scope within the function.
•We can access local variable with in the function
•Local variable cannot be accessed outside the function.
Global Variables
•A variable declared outside the function is known as global variable .Its
Scope is in the entire program (global).
•global variable can be accessed inside or outside of the function.
•Python provides the global keyword to use global variable inside the
function.
Delete a variable
We can delete the variable using the del keyword. The syntax is given
below.
Syntax -
del <variable_name>
Ex:
# Assigning a value to x
x = 10
print(x)
# deleting a variable.
del x
print(x)
Defining and accessing local variables
Ex:1
# Declaring a function
def add():
# Defining local variables.
a = 20
b = 30
c = a+b
print(“The sum is “,c)
# Calling a function
add()
Output: 50
Ex2: Local variable
# Local variable
def greet():
message = 'Hello'
print('Local', message)
greet()
Output:
Local Hello
Ex :global variable
# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Output:
Local Hello
Global Hello
Multiple Assignment
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
•Assigning single value to multiple variables
•Assigning different values to multiple variables.
Assigning single value to multiple variables:Python allows assigning a
single value to several variables simultaneously with “=” operators.
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
Assigning different values to multiple variables:
In Python, it is possible to define more than one variable using a
single statement. When multiple variables are created using a
single statement, the variables and their corresponding value must
be separated with a comma symbol “ ,”.
Eg:
a, b, c = 1, 10.2, “CMRTC"
print(a)
print(b)
print(c)
Output:
1
10.2
CMRTC
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value
and type.
Ex:
a = 10
a = “CMRTC"
print(a)
Object Identity
In Python, every created object identifies uniquely in Python. Python
provides the guaranteed that no two objects will have the same identifier.
The built-in id() function, is used to identify the object identifier
Ex:
# Object Identity
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a)) output:
140703137527176
140703137527176
What is datatype?
Data type specify the type of data that can be stored inside a variable.
num = 24
Here, 24 (an integer) is assigned to the num variable. So the data type of
num is of the int class.
Note:
•Since everything is an object in Python programming, data types are
actually classes and variables are instances(object) of these classes.
•Python is a dynamically typed language; hence we do not need to define
the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.
type()
•Python enables us to check the type of the variable used in the program.
•Python provides the type() function to know the data-type of the
variable.
Ex: to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'>
<class 'str'>
Standard data types
The data types defined in Python are given below.
Numbers (Numeric)
Sequence Type
Boolean
Set
Dictionary
Numeric Data type
•Numeric data type is used to hold numeric values.
•The integer, float, and complex values belong to a Python Numeric
data-type.
•They are defined as int, float and complex classes in Python.
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
Output
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
Dictionary:
•Dictionary is a ordered collection of elements. It stores elements in
key/value pairs.
•Key can hold any primitive data type, whereas value is an arbitrary
Python object.
•In Python, the dictionary data type (data structure) has implemented
with a class known as dict
•The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
•If we want to store information about countries and their capitals, we
can create a dictionary with country names as keys and capitals as
values.
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, ...}
Note:
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
Access Dictionary Values Using Keys
The dictionary elements are organized based on the keys.
So we can access dictionary elements based on key
print(capital_city[‘India'])
Output: Delhi
Ex to illustrate Dictionary
# create a dictionary named capital_city
capital_city = {'India': 'Delhi', 'Italy': 'Rome', 'England': 'London'}
print(capital_city)
Output:
•Note:
•Since sets are unordered collections, indexing has no meaning. Hence,
the slicing operator [] does not work.
•The set is created by using a built-in function set().
Creating Set
Syntax
set_name = {element_1, element_2, element_3, ...}
In Python, a set can also be created using the set( ) constructor. The
set() constructor takes only one argument.
Syntax
set_name = set((element_1, element_2, element_3, ...))
Accessing Elements of a set in Python
•In Python, the set elements are organized without any index values. So,
accessing individual elements of a set is not allowed.
•However, we can access the entire set using the name of the set.
Ex: print(set_name)
•
Ex1:
# Creating Empty set
set1=set()
set2={'Van Rossum',2,3,'Python'}
#Printing Set value
print(set2)
Output:
{3, 'Van Rossum', 2, 'Python'}
Ex:2
#Creating Set
student_data = {1, 'Ram', '2nd Year', 'CSE', 85.80}
print(type(student_data))
print(student_data)
Output:
<class 'set'>
{1, 85.8, 'Ram', '2nd Year', 'CSE'}
Ex3:
# create a set named student_id
student_id = {112, 114, 116, 118, 115}
# display student_id elements
print(student_id)
# display type of student_id
print(type(student_id))
Output:
{112, 114, 115, 116, 118}
<class 'set'>
Sequence datatype
Output:
{1, '3rd Year', 86.5, 'Rama'}
<class 'set'>
Python List Data Type
•List is an ordered collection of elements of different data types.
•The items stored in the list are separated with a comma (,) and enclosed
within square brackets [].
•Python Lists are similar to arrays in C.
•A single list may contain DataTypes like Integers, Strings, as well as
Objects.
•Lists are mutable, and hence, they can be altered even after their creation.
•All the elements of a list are ordered and they are indexed. Here, the
index starts from '0' (zero) and ends with 'number of elements - 1'.
Creating the List
Lists in Python can be created by just placing the sequence inside the
square brackets[]
Syntax:
list_name = [element_1, element_2, element_3, ...]
Ex:
languages = [“C++", "Java", "Python“]
Accessing elements from the List
•In order to access the list items refer to the index number.
•Use the index operator [ ] to access an item in a list. The index must be
an integer.
Syntax
list_name[index]
Ex:
languages = [“C++", "Java", "Python“]
Print[languages[0]]
Output:
C++
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.
Ex to illustrate List Data type
# Access List Items
languages = [“C++", "Java", "Python"]
# access element at index 0
print(languages[0])
# access element at index 2
print(languages[2])
Output:
C++
Python
Ex 2:
list1=[1,"hi","Python",2]
#Checking type of given list
print(type(list1))
#Printing the list1
print(list1)
Output:
<class 'list'>
[1, 'hi', 'Python', 2]
Python Tuple Data Type
•Tuple is same as list it contains the ordered collection of the items of
different data types
•The only difference is that tuples are immutable. Tuples once created
cannot be modified.
•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. They are indexed by integers.
Creating a Tuple
Syntax:
tuple_name = (element_1, element_2, element_3, ...)
For example:
tup= (1,”python”)
Note:
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
In python, we have 7 different types of operators, they are:
•Arithmetic Operators
•Comparison Operators
•Assignment Operators
•Logical Operators
•Bitwise Operators
•Membership Operators
•Identity Operators
While the first five are commonly used operators the last two i.e
Membership and Identity operators are exclusive to python.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on
operands like addition, subtraction, multiplication etc.
Operator Description
+ (Addition) It is used to add two operands.
It is used to subtract the second operand
- (Subtraction)
from the first operand
It returns the quotient after dividing the first
/ (divide)
operand by the second operand.
It is used to multiply one operand with the
* (Multiplication)
other.
It returns the reminder after dividing the first
% (reminder)
operand by the second operand.
As it calculates the first operand's power to
** (Exponent) the second operand, it is an exponent
operator.
// (Floor division) It provides the quotient's floor value, which
is obtained by dividing the two operands.
# Arithmetic Operators Ex Ex to illustrate Arithmetic Operators
a=7
b=2
print ('Sum: ', a + b) # addition output:
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
print ('floor Division: ', a // b)
Assignment Operators
Assignment operators are used to assign values to variables.
Ex: x = 5 Here, = is an assignment operator that assigns 5 to x.
Operator Description
Assigns right-hand side value to left-hand side variable
= (Assignment)
Ex: a = 10
Adds right operand to the left operand and assign the
+= (Add and Assign)
result to left operand Ex: If a = 10, b = 20 => a+ = b will
be equal to a = a+ b and therefore, a = 30.
Subtracts right operand from the left operand and assign
-=(Subtract and Assign) the result to left operand Ex: if a = 20, b = 10 => a- = b
will be equal to a = a- b and therefore, a = 10.
Multiplies right operand with the left operand and assign
*=(Multiply and Assign)
the result to left operand Ex: if a = 10, b = 20 => a* = b
will be equal to a = a* b and therefore, a = 200.
Divides left operand with the right operand and assign
/=(Division and Assign) the result to left operand Ex: if a = 20, b = 10 => a /= b
will be equal to a = a /b and therefore, a = 0.
Ex To illustrate Assignment Operators
# assignment operators
a = 10
b=5
print("=",a) output:
a += b
print("+=",a)
a*=b
print("*=",a)
a-=b
print("/=",a)
a/=b
Comparision operators:
Comparison operators compare two values/variables and return a
boolean value: True or False
Ex: a = 5 b =2 print (a > b) output: True
Here, the > comparison operator is used to compare whether a is
greater than b or not.
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.
The condition is met if the first operand is smaller than
<=
or equal to the second operand.
The condition is met if the first operand is greater than
>=
or equal to the second operand.
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.
Ex To illustrate Comparison Operators
a=5
b=2
# equal to operator
print( a == b)
# not equal to operator
print( a != b)
# greater than operator
print(a > b)
# less than operator
print( a < b)
# greater than or equal to operator
print(a >= b)
# less than or equal to operator
print(a <= b)
Logical operators
•Logical operators are used to check whether an expression is True or
False. Logical operators are used to perform Logical operations
•Python has three logical operators
•and
•or
•not
•Sometimes, you may want to check multiple conditions at the same
time. To do so, you use logical operators.
•They are used in decision-making.
For example: a = 5 b = 6 print((a > 2) and (b >= 6)) output: True
Operator Description
and True only if both the operands are True
or True if at least one of the operands is True
not True if operand is false
Ex To illustrate Logical Operators
#logical operators
a = 10
b=3
c = 20
print(a < b and a > c)
print(a < b or a > c)
print(not a > b)
Output:
False
False
False
bitwise operators
The bitwise operators are used to performs bit by bit operation.
let's consider two variables a with value 10 equivalent binary value is
1010, b with value 15 equivalent binary value is 1111.
Operator Description
Result bit 1,if both operand bits are 1;otherwise results
& (Bitwise AND)
bit 0. x & y
Result bit 1,if any of the operand bit is 1; otherwise
|(Bitwise OR)
results bit 0. x | y
~(Bitwise NOT) inverts individual bits. ~x
Results bit 1,if any of the operand bit is 1 but not both,
^(Bitwise XOR) otherwise .results bit 0. x ^ y
Operator Description
Returns True if the variables on either side of the
Is (is identical) operator point to the same object otherwise returns
False. a is b
Returns False if the variables on either side of the
is not (is not identical) operator point to the same object otherwise returns
True. a is not b
# identical operators
a = 10
b=3
print(a is b)
print(a is not b) Output: False
True
Membership operators
In Python, in and not in are the membership operators. They are used to
test whether a value or variable is found in a sequence (string, list, tuple
, set and dictionary).
Operator Description
in True if value/variable is found in the sequence. 5 in x.
True if value/variable is not found in the sequence. 5 not
not in
in x.
Ex:
# Member ship operators
x = 'Hello world'
print('H' in x)
print('welcome' not in x)
Output:
True
True