0% found this document useful (0 votes)
3 views

1.3 Basic Datatypes and Operators in Python-1

Python

Uploaded by

boyalakshmi212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

1.3 Basic Datatypes and Operators in Python-1

Python

Uploaded by

boyalakshmi212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module 1

Basics of Python

Contents

• Introduction

• Features

• Python building blocks – Identifiers, Keywords, Indention, Variables and


Comments

• Basic data types (Numeric, Boolean, Compound)

• Operators: Arithmetic, comparison, relational, assignment, logical,


bitwise, membership, identity operators, operator precedence

• Control flow statements: Conditional statements (if, if…else, nested if),


Looping in Python (while loop, for loop, nested loops)

• Loop manipulation using continue, pass, break

• Input/output Functions

• Decorators

• Iterators and

• Generators

VASAVI. A
Datatypes in Python
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. Every value
in Python has a datatype.

Data can be of many types e.g., character, integer, real, string etc.,

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
1. Numbers:

Integers, floating point numbers, boolean and complex numbers fall


under python numbers category. They are defined as int, float, bool and
complex class in python.

2. Strings:

A String datatype lets you hold string data, i.e., any number of valid
characters into a set of quotation marks.

It can hold any type of known characters i.e., letters, numbers, and
special characters.

We can use single quotes or double quotes to represent strings.

Each character of string is accessed using its index.

Multi-line strings can be denoted using triple quotes, ‘’’ or “ “ “.

VASAVI. A
S= “This is a string”

S=’’’a multiline’’’

3. List:

List is an ordered sequence of items. It is one of the most used


datatypes in python and is very flexible. All the items in a list do not need
to be of the same type.

Lists are mutable (can be changed/modified)

Items separated by commas are enclosed within brackets [ ].

a = [ 1, 2.2, ‘python’]

b= [1,2,3,4,5]

c= [‘Neha’, 102, 79.6]

4. Tuple:

Tuple is an ordered sequences of items same as list. The only


difference is that tuples are immutable. Tuples once created cannot be
modified.

It is defined within parentheses () where items are separated by


commas.

p= (1,2,3,4,5)

q= (2,4,6,8)

r= (‘a’,’e’,’i’,’o’,’u’)

s= (7,8,9,’A’,’B’,’C’)

VASAVI. A
5. Dictionary:

The dictionary is an unordered set of comma-separated Key:Value


pair, within { }.

Within a dictionary, no two keys can be the same i.e., there are
unique keys within a dictionary.

>>>> vowels={‘a’:1, ‘e’: 2, ‘i’: 3, ‘o’: 4, ‘u’: 5 }

>>>> vowels[‘a’]

>>>> 1

>>>> vowels[‘u’]

>>>> 5

VASAVI. A
Operators in Python
Operators:

Operators are used to perform operations on variables and values.

OPERATORS: Special symbols. Eg: + , * , /


OPERAND: It is the value on which the operator is applied.

Python supports different types of operators:


1. Arithmetic operators
2. Comparison (Relational) operators
3. Assignment operators
4. Logical operators or Boolean operators
5. Membership operators
6. Identity operators
7. Bitwise operators
8. Ternary operators

1. Arithmetic operators:
• To do arithmetic, Python uses arithmetic operators.
• Each of these operators is a binary operator i.e., it require two
values (operands) to calculate final value (answer).
• Python arithmetic operators are Addition (+), Subtraction (-),
Multiplication (*), Division (/), Modulus (%), Exponent (**),
Floor division (//) ( Returns only integer value).

VASAVI. A
Example:

X=15

Y=4

print(‘X+Y=’, X+Y) // 19

print(‘X-Y=’, X-Y) // 11

print(‘X*Y=’, X*Y) // 60

print(‘X/Y=’, X/Y) // 3.75

print(X**Y=’, X**Y) // 50625

print(‘X//Y=’, X//Y) // 3

Taking input from user:

X=int(input(“Enter the first number:”))

Y=int(input(“Enter the second number:”))

Z=X+Y

print(“Addition is:”, Z)

Z=X-Y

Print(“Subtraction is:”, Z)

Output:

Enter the first number:20


Enter the second number:10
Addition is: 30
Subtraction is: 10

VASAVI. A
2. Comparison or Relational Operators:
Relational or Comparison operators are used for comparing
two expressions and results in either true or false.
The six relational operators are <, >, <=, >=, ==, !=
Example:
A=1, B=2
print(A==B) False
print(A!=B) True
print(A<B) True
print(A>B) False
print(A<=B) True
print(A>=B) False

3. Assignment Operators:

Assignment operator assigns the value specified on RHS to the


variable/object on the LHS of =.

Python Assignment operators:


=, +=, -=, *=, /=, %=, **=, //=
Example:
>>> a= 10
>>> a+=10 a= a+10
= 10+10
= 20
>>> a
>>> 20
>>> a-=5 a=a-5
= 20-5
= 15

VASAVI. A
>>> a
>>> 15
>>> a*=3 a=a*3
= 15*3
= 45
>>> a
>>> 45
>>> a/=2 a=a/2
=45/2
= 22.5
>>> a
>>> 22.5
>>> a-=3.5 a=a-3.5
= 22.5-3.5
= 19.0
>>> a
>>>19

4. Logical Operators or Boolean Operators:

Python provides three logical operators to combine existing


expressions. These are OR, AND and NOT.

The OR Operator:

If any of 2 operands are true then condition become true.

VASAVI. A
X Y X OR Y
0 0 0
0 1 1
1 0 1
1 1 1

Example:
(4==4) or (5==8) // True
T F
(5>8) or (5<2) // False
F F

X= True; Y=False
Print(X or Y) // True

The AND Operator:


If any of 2 operands are false then condition become false.

X Y X AND Y
0 0 0
0 1 0

1 0 0
1 1 1

Example:
(4==4) and (5==8) // False
T F
VASAVI. A
(5>8) and (5<2) // False
F F
(5>8) and (2<5) // False
F T
X= True; Y=False
Print(X and Y) // False

The NOT Operator:

The NOT operator reverses the logical state of its operand.

X NOT X
T F
F T

Example:
not True // False
not False // True

5. Membership Operators:
Membership operators are used to test whether a value or variable is
found in sequence (string, list, set and dictionary).

Python Membership operators are:

(a) In (b) Not in

NOTE:

In a dictionary, we can only test for presence of key, not the value.

VASAVI. A
(a) In operator:
Returns True if value/variable is found in the sequence.
(b) Not in operator:

Returns True if value/variable is not found in the sequence.

Example:

pystr=”PYTHON”

print(‘i’ in pystr) // False

pystr=”Bigdata”

print(‘i’ in pystr) // True

X=’Hello World’

Y={ 1:’a’, 2:’b’ }

Print(‘h’ in X) // False

Print(‘Hello’ not in X) // False

Print(1 in Y) // True

Print(‘a’ in Y) // False

print('e' in X) // True

print('e' not in X) // False

VASAVI. A
6. Identity operators:

Identity operators compare the memory locations of two objects.


There are two Identity operators in python:

(a) is
(b) is not
(a) is operator:
Evaluates to true if the variables on either side of the operator point
to the same object and false otherwise.
>>> x=’hello’
>>> y=’hello’
>>> x is y
True
Example:

# Python program to illustrate the use of 'is' identity operator

x=5
y=5
print(x is y)
id(x) // Memory location
id(y) // Memory location
(a) is not operator:
Evaluates to false if the variables on either side of the operator
point to the same object and true otherwise.

>>> x=’hello’

>>> y=’hello’

>>> x is not y

False

VASAVI. A
Example:

x=5

if (type(x) is not int):


print("true")
else:
print("false")
x = 5.6
if (type(x) is not int):
print("true")
else:
print("false")
Output:
false
true

7. Bitwise operators:
In Python, bitwise operators are used to performing bitwise
calculations on integers. The integers are first converted into binary and
then operations are performed on bit by bit, hence the name bitwise
operators. Then the result is returned in decimal format.

Note:
Python bitwise operators work only on integers.
Python bitwise operators are:
(a) Bitwise AND &
(b) Bitwise OR |
(c) Bitwise NOT ~
(d) Bitwise XOR ^

VASAVI. A
(e) Bitwise right shift >>
(f) Bitwise left shift <<
(a) Bitwise AND &:
Returns 1 if both the bits are 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
&
0100
= 0000
= 0 (Decimal)

>>> a=10
>>> b=4
>>> a&b
0
(b) Bitwise OR |:

Returns 1 if either of the bit is 1 else 0.


Example:

a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010
|
0100
= 1110
= 14 (Decimal)

VASAVI. A
>>> 10|20
>>> 10 1010
>>> 20 10100
01010
10100
11110
>>> 30

(c) Bitwise NOT ~:


Returns one’s complement of the number.
Example:

a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
>>> X= 43
>>> print("~x =", ~x)
>>> -44
>>> x=-10
>>> print(~x)
>>> 9

VASAVI. A
(d) Bitwise XOR ^:

Returns 1 if one of the bits is 1 and the other is 0 else returns


false.
Example:

a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)

(e) Bitwise Right shift >>:

The individual bits of the number are shifted to the right, and
the gaps on the left are filled with 0 (or 1 if the number is negative).
The result is similar to dividing a value by a power of 2.
Example:
10>>2 // 10/2^2
// 10/4
// 2
20>>3 // 20/2^3
// 20/8
// 2

VASAVI. A
(f) Bitwise Left shift <<:

The individual bits of the integer to the left are filled with 0. The
result is similar to multiplying a value by a power of 2.
Example:
10<<2 // 10*2^2=10*4=40
15<<4 // 15*2^4=15*16=240

8. Ternary operators:

Ternary operators are also known as conditional expressions are


operators that evaluate something based on a condition being true or false.

It simply allows testing a condition in a single line replacing the


multiline if-else making the code compact.

Syntax:

[on_true] if [expression] else [on_false]


Example:
# Program to demonstrate conditional operator

a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)
Output:
10

VASAVI. A
Operator Precedence in Python

This is used in an expression with more than one operator with


different precedence to determine which operation to perform first.

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'

^| 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

VASAVI. A
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.

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)

Output:

Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

VASAVI. A

You might also like