Python: Data Types and Operators with Simple Programs

Before write even the most elementary programs in any language, there are some fundamentals you need to know. This blog introduces some such fundamentals: data types, variables, operators and expression in Python.

DATA TYPES: It is a set of values, and the allowable operations on those values. It can be one of the following:

datatype

1. Number

Number data type stores Numerical Values. This data type is immutable i.e. value of its object cannot be changed (we will talk about this aspect later). These are of three different types:

a) Integer

  • Plain integer
  • Long integers                   
  • Boolean

 b) Float/floating point

c) Complex

 a) Integer:

Integers are whole numbers such as 5, 30, 1981,0 etc. They have no fractional parts. Integers can be positive or negative.

 -> Plain integer:

  • Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17.
  • Range of an integer in Python can be from -2147483648 to 2147483647. However, if the result of operation would fall outside this range, the result is normally returned as a long integer.
  • While writing a large integer value, don’t use commas to separate digits. Also integers should not have leading zeros.

-> Long integer:

  • When we want a value to be treated as very long integer value appends L to the value. Such values are treated as long integers by python.
  • Long integer has unlimited range subject to available memory. In python 2.2 and later, ints are automatically turned into long ints when they overflow.

Example:

>>> a = 10

>>> b = 5192L                                  #example of supplying a very long value to a variable

>>> c= 4298114

>>> type(c)                                     # type ( ) is used to check data type of value

<class ‘int’>

>>> c = c * 5669

>>> type(c)

<class ‘long’>

-> Boolean Type:

  • It is a unique data type, consisting of two constants, True & False.
  • A Boolean True value is Non-Zero, Non-Null and Non-empty.

Example

>>> flag = True

>>> type(flag)

<class ‘bool’>

b) Floating Point:

  • Numbers with fractions or decimal point are called floating point numbers.
  • A floating point number will consist of sign (+, -) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963.
  • These numbers can also be used to represent a number in engineering/ scientific notation.

-2.0X 105 will be represented as -2.0E5

2.0X10-5 will be 2.0E-5

Example

y= 12.36

A value when stored as floating point in Python will have 53 bits of precision.

c) Complex:

  • Complex number in python is made up of two floating point values, one each for real and imaginary part.
  • For accessing different parts of variable (object) x.
  • We will use real and x.image.
  • Imaginary part of the number is represented by ‘j’ instead of ‘i’, so 1+0j denotes zero imaginary part.

Example

>>> x = 1+0j

>>> print (x.real, x.imag)

1.0  0.0

Example

>>> y = 9-5j

>>> print (y.real, y.imag)

9.0  -5.0

Data Type Range
Plain integer -231 to +231 – 1 that is -2147483648 to 2147483647 – 1
Long integers An unlimited range, subject to available (virtual) memory only
Booleans Two values True (1) and False (0)
Floating point numbers An unlimited range, subject to available (virtual) memory on underlying machine architecture.
Complex numbers Same as floating point numbers because the real and imaginary parts represented as floats.

2. None:

  • This is special data type with single value. It is used to signify the absence of value/false in a situation. It is represented by None.

3. Sequence

  • A sequence is an ordered collection of items, indexed by positive integers.
  • It is combination of mutable and non mutable data types.
  • Three types of sequence data type available in Python are Strings, Lists & Tuples.
  • Sequential data types contain multiple pieces of data, each of which is numbered, or indexes.
  • Each piece of data inside a sequence is called an element.
  • Sequential data types are that which can manipulate the whole sequence, chunks of the  sequence, or individual elements inside the sequence.

-> String:

  • String is an ordered sequence of letters/characters. They are enclosed in single quotes (‘ ‘) or double (“ “).
  • The quotes are not part of string. They only tell the computer where the string constant begins and ends.
  • They can have any character or sign, including space in them. These are immutable data types.

Python offers two string type:

i) Normal ASCII string:

It is also called str type string. This string type holds string of zero or more ASCII character.

Example:

‘Boy’, Navin’, “ZIG 1981”

ii) Unicode string:

This string type can hold strings containing Unicode characters. Unicode string values are written as – normal strings prefixed with letter u (not in quotes).

Example:

u ‘BOY’, u”Hello mr.”,  u “امجد ”

The Unicode string are used to store Unicode letters (ASCII character + many more)

Conversion from one type to another

In general, the number types are automatically ‘up cast’ in this order:

Int → Long → Float → Complex. The farther to the right you go, the higher the precedence.

Example:

>>> x = 5

>>> type(x)

<type ‘int’>

>>> x = 187687654564658970978909869576453

>>> type(x)

<class ‘long’>

>>> x = 1.34763

>>> type(x)

<class ‘float’>

>>> x = 5 + 2j

>>> type(x)

<class ‘complex’>

It is possible to change one type of value/ variable to another type. It is known as type conversion or type casting. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type).

For explicit type casting, we use functions (constructors):

int ()

float ()

str ()

bool ()

Example

>>> a= 12.34

>>> b= int(a)

>>> print (b)

12

Example

>>>a=25

>>>y=float(a)

>>>print (y)

25.0

-> Lists: A list is a mutable (can change) sequence data type, elements in a list can be added or removed due to its mutable  feature. List can contain mixed data types which means list elements don’t have to be of the same type.

A list contains items separated by commas and enclosed within square brackets []. List elements are numbered internally starting from 0. There can have nesting of lists one inside other

>>> l = [1,2,3,4,”xyz”,2.34,[10,11]]

>>> l[0]

1

>>> l[4]

‘xyz’

>>> l[6]

[10, 11]

>>> l[6][0]

10

Add element in an existing list

>>> l.append(‘Vishal’)

>>> l

[1, 2, 3, 4, ‘abc’, 2.34, [10, 11], ‘Vishal’]

Remove element from list

>>> del l[0]

>>> l

[2, 3, 4, ‘abc’, 2.34, [10, 11], ‘Vishal’]

Slicing elements of list

>>>1 [1 : 4 ]

[3,4,’abc’]

-> Tuples: Tuples are a sequence of values of any type, and are indexed by integers. Tuples are enclosed in (). A tuple in Python is much like a list except that it is immutable (unchangeable) once created. Tuple can be index, sliceand concatenate, but one cannot append or alter the values of the tuple after it  has been initialized. Tuples are created using round brackets.

>>> t = (1,2,3,4,’abc’,2.34,(10,11))

>>> t[0]

1

>>> t[4]

‘abc’

>>> t[6]

(10,11)

4. Sets:

  • A set stores multiple items, which can be of different types, but each item in a set must be  unique.
  • Use of sets is to find unions, intersections, differences, and so on.
  • Unlike sequence objects such as lists and tuples, in which each element is indexed.
  • Basic uses include membership testing and eliminating duplicate entries.

Operations on sets

#Creating set

>>> s1=set([‘a’, ‘i’, ‘e’, ‘u’, ‘o’])

>>> s2=set([‘m’, ‘w’, ‘d’, ‘i’, ‘t’, ‘o’])

>>> print (s1)

{‘a’, ‘i’, ‘e’, ‘u’, ‘o’}

>>> print (s2)

{d’, ‘i’, ‘m’, ‘o’, ‘t’, ‘w’}

#Add single member in set

>>> s1.add(32)

>>> print (s1)

{‘a’, 32, ‘e’, ‘i’, ‘o’, ‘u’}

#Add group of members in set

>>> s1.update([26, 9, 14])

>>> print (s1)

{‘a’, 32, ‘e’, ‘i’, 9, ‘o’, ‘u’, 14, 26}

#Different types of Membership Testing

>>> 32 in s1

True

>>> ‘o’ in s1

True

>>> 35 not in s1

True

>>> 32 not in s1

False

>>> ‘w’ in s1

False

#Intersection Operation

>>> s1 & s2                              OR                           >>> s1.intersection(s2)

output:  {[‘i’, ‘o’}

#Union Operation

>>> s1 | s2                              OR                           >>> s1.union(s2)

output:  {‘a’, ‘e’, ‘d’, ‘i’, ‘m’, ‘o’, ‘u’, ‘t’, ‘w’}

#Difference Operation

>>> s1 – s2                              OR                           >>> s1.difference(s2)

output: {‘a’, ‘u’, ‘e’}

#Symmetric Difference

>>>s1 ^ s2                                 OR                           >>> s1.symmetric_difference(s2)

output: {‘a’, ‘e’, ‘d’, ‘w’, ‘u’, ‘m’, ‘t’}

5. Mapping

This data type is unordered and mutable. Dictionaries fall under Mappings.

-> Dictionaries: Can store any number of python objects. What they store is a key – value pairs, which are accessed using key. Dictionary is enclosed in curly brackets.

Example

d = {1:’a’,2:’b’,3:’c’}

Syntax for creating dictionary→ >>> d = {‘key1′:’value1′,’key2′:’value2’,…. }

#Create dictionary

>>> phonebook={‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter

Power’:7658344, ‘Lewis Lame’:1122345}

#Show dictionary phonebook

>>>phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter Power’:7658344, ‘Lewis

Lame’:1122345}

#Display keys and its respective values of all the items from dictionary

>>> phonebook.items()

[(‘Emily Everett’, 6784346),(‘Andrew Parson’, 8806336), (‘Lewis Lame’, 1122345),(‘Peter Power’, 7658344)]

#Display the key of value from dictionary

>>> phonebook.keys()

[‘Emily Everett’, ‘Andrew Parson’, ‘Lewis Lame’, ‘Peter Power’]

#Display the value of lists from dictionary

>>> phonebook.values()

[6784346, 8806336, 1122345, 7658344]

#Display the value of a specific key

>>> phonebook.pop(‘Andrew Parson’)

8806336

#Add a new numbers to the phonebook

>>> phonebook[‘Gingerbread Man’] = 1234567

>>> phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’:6784346, ‘Peter Power’:7658344, ‘Lewis

Lame’:1122345, ‘Gingerbread Man’: 1234567}

#Remove item from dictionary

>>> del phonebook[‘Peter Power’]

>>> phonebook

{‘Andrew Parson’:8806336, ‘Emily Everett’: 6784346, ‘Lewis Lame’: 1122345,

‘Gingerbread Man’: 1234567}

Mutable and Immutable Variables

A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

Example

>>>x=5

Will create a value 5 referenced by x

x 5

>>>y=x

This statement will make y refer to 5 of x

image1

>>> x=x+y

As x being integer (immutable type) has been rebuild.

In the statement, expression on RHS will result into value 10 and when this is assigned to LHS (x), x will rebuild to 10. So now

x    ————>       10 and

y   ————>        5

Operators:

  • These are those lexical units that trigger some computation when applied to variables and other objects in an expression.
  • Operators are functionality that do something and can be represented by symbols such as + or by special keywords.
  • Operators require some data to operate on and such data is called operands.
  • For example: >>>x = 2+ 3. In this case, 2 and 3 are the operands.
Unary Operator:  
unary plus + The unary (+) must have arithmetic type and the result is the value of the argument. If a = 5 then +a means 5.

If a = 0 then +a means 0.

If a = -4 then +a means -4.

unary minus The unary (+) must have arithmetic type and the result is the negative of its operand’s value If a = 5 then -a means -5.

If a = 0 then -a means 0.

If a = -4 then -a means 4.

Bitwise complement ~ The bit-wise inversion of x is -(x+1) ~5 give -6.
Logical negation not If x is True, it returns False. If x is False, it returns

True.

>>> x=4

>>> y=3

>>> not x<y

True

>>> not x>y

False

Arithmetic Operator:
Addition + Adds two objects 3 + 5 gives 8. ’a’ + ’b’ gives ’ab’.
Subtraction Gives the subtraction of one number from the other; if the first

operand is absent it is assumed to be zero.

-5.2 gives a negative number and 50 – 24 gives 26.
Multiplication * Gives the multiplication of the two numbers or returns the string

repeated that many times.

2 * 3 gives 6. ’la’ * 3 gives ’lalala’.
Division / Divide x by y 4 / 3 gives 1.3333333333333333.
Remainder % Returns the remainder of the division 8 % 3 gives 2. -25.5 % 2.25 gives 1.5.
Exponent ** Returns x to the power of y 3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3)
Floor division // Returns the floor of the quotient 4 // 3 gives 1.
Bitwise Operator:
Bitwise AND & Bit-wise AND of the numbers 5 & 3 gives 1.
Bitwise exclusive OR (XOR) ^ Bitwise XOR of the numbers 5 ˆ 3 gives 6
Bitwise OR | Bitwise OR of the numbers 5 | 3 gives 7
Shift operators:  
Shift left << Shifts the bits of the number to the left by the number of bits

specified. (Each number is represented in memory by bits or binary digits

i.e. 0 and 1)

2 << 2 gives 8. 2 is represented by 10 in bits.

Left shifting by 2 bits gives 1000 which represents the decimal 8.

Shift right >> Shifts the bits of the number to the right by the number of

bits specified.

11 >> 1 gives 5.

11 is represented in bits by 1011 which when right shifted by 1 bit gives

101which is the decimal 5.

Identity operator:  
Is the identity same? is  X ix Y Return True if both its operands are pointing to same object (i.e, both referring to same memory location), returns false otherwise
Is the identity not same? is not X is not Y Return True if both its operands are pointing to different object (i.e, both referring to different memory location), returns false otherwise
Relational Operator: Assume variable x holds 100 and y holds 200
Less than < Returns whether x is less than y. All comparison operators return

True or False.

x < y will return True
Greater than < Returns whether x is greater than y If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False. x > y will return False
Less than or equal to >= Returns whether x is less than or equal to y x <= y will return True
Greater than or equal to >= Returns whether x is greater than or equal to y x >= y will return False
Equal to == Compares if the objects are equal x = 2; y = 2; x == y returns True.

x = ’str’; y = ’stR’; x == y returns False.

x = ’str’; y = ’str’; x == y returns True.

Not equal to != Compares if the objects are not equal x != y will return True
Not equal to <> Compares if the objects are not equal x < > y will return True
Assignment Operators: Assume variable x holds 12
Assignment = Assigned values from right side

operands to left variable

>>>x=12

>>>y=‟greetings‟

Assign quotient /= divided and assign back the

result to left operand

x/=2

x will become 6

Assign sum += added and assign back the result

to left operand

 

>>>x+=2

The operand/expression /constant written on RHS of operator is will change the

value of x to 14

Assign product *= multiplied and assign back the result to left operand x*=2 x will become 24
Assign remainder %= taken modulus using two operands and assign the result to left operand x%=2

x will become 0

Assign difference -= subtracted and assign back the result to left operand x-=2 x will become 10
Assign Exponent **= Performed exponential (power)

calculation on operators and

assign value to the left operand

x**=2

x will become 144

Assign floor division //= performed floor division on

operators and assign value to

the left operand

x / /= 2 x will become 6
Logical Operators:
Logical AND and If both the operands are true, then the condition becomes true. >>> True and True

True

>>> True and False

False

>>> False and True

False

>>> False and False

False

Logical OR or If any one of the operand is true, then the condition becomes true. >>> True or True

True

>>> True or False

True

>>> False or True

True

>>> False or False

False

Membership Operators:
Whether variable in sequence in
Whether variable not in sequence not in

 

Operator Description
 ** Exponentiation (raise to the power)
+ , – unary plus and minus
* , /, %, // Multiply, divide, modulo and floor division
+ , – Addition and subtraction
<, <=, >, >= Comparison operators
==, != Equality operators
% =, / =, // = , -=, + =, * = Assignment operators
not and or Logical operators

Precedence of operator – Listed from high precedence to low precedence.

Statement: A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.

Example of statement are:

>>> x=5

>>> area=x**2                                    #assignment statement

>>>print (x)                                            #print statement

        5

In Python, there are compound/ group statements also. They are sometimes called nested block. Statements belonging to a block are indented (usually by 4 spaces). Leading whitespace at the beginning of logical line is used to determine the indentation level of line. That means statement(s) which go together must have same indentation level.

Example

if i<0:

print (“i is negative”)

else:

print (“i is non-negative”)

Example

if i>0:

print (“i is positive”)

else:

print (“i is equal to 0”)

While writing Python statements, keep the following points in mind:

  1. Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
  2. Comment starts with “#” outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by interpreter.
  3. For a long statement, spanning multiple physical lines, we can use “/” at the end of physical line to logically join it with next physical line. Use of the “/”for joining lines is not required with expression consists of ( ), [ ], { }
  4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
  5. Indentation is used to represent the embedded statement(s) in a compound/ Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
  6. White space in the beginning of line is part of indentation, elsewhere it is not significant.

 

Expression:

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions

(Assuming that the variable x has been assigned a value):

It always evaluate into a single value.

17

x

x + 17

Types of expression:

1.Arithmetic Expression:-

Arithmetic expressions involve numbers and arithmetic operators. It can belong to one of these types:

a) Pure Expressions:-

Pure arithmetic expressions are those that have all operators of same numeric type.                    For Example:

x + y , c/y      ( integer expressions if x, y ,c are all integer type)

p + q , t/u      (real expressions if p, q, t and u all float type)

b) Mixed Expression:-

Mixed arithmetic expressions are that have operands of different numeric types.

For Example:

If a,b are integer variable and c, d are floating point and e, f are complex type than

i) 8+d                                  ii) c/a +a                    iii) e*a +f

2. Relational Expression:-

An expression having literals and /or variables of any valid type and relational operators is a relational expression.

For Example:

x > y ,        y>=z,        z==a

3. Logical Expression:-

An expression having literals and /or variables of any valid type and logical operators is a logical expression.

For Example:

x or y ,        y and z,        not z or not a

4. String Expression:-

Python also provides two string operators + and *, when combined with string operands and integer, form string expression.

With operator +, the concatenation operator, the operands should be of string type only.

With operator *, the replication operator, the operands should be one string type and one integer.

For Example:

“now” + “then”        =>    nowthen (concatenation of “now” and “then”)

“now” * 2                  =>    nownow (replication of now two times)

 

Program 1: Write a python program to input two numbers from user and calculate their
sum. The Python program to add two numbers and display their sum as output.
How to add two numbers in Python programming.

For Example

Input

Input first number: 20

Input second number: 10

Output

Sum = 30

For Solution Click on        Solution of Program 1

Program 2: Write a python program to input two numbers and perform all arithmetic operations. How to perform all arithmetic operation between two numbers in python programming. A Python program to find sum, difference, product, quotient and modulus of two given numbers.

For Example
Input
First number: 10
Second number: 5
Output
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Modulus = 0

For Solution Click on  Solution of Program 2

Program 4. Write a python program to input temperature in Celsius (centigrade) and convert to Fahrenheit. How to convert temperature from degree centigrade to degree Fahrenheit in python programming. Python program for temperature conversion.

For Solution Click on  Solution of Program 4

Program 5. Write a python program to input radius of a circle from user and find diameter, circumference and area of the circle. How to calculate diameter, circumference and area of a circle whose radius is given by user in program programming. Logic to find diameter, circumference and area of a circle in python.

For Solution Click on  Solution of Program 5

Program 6. Write a python program to input number of days from user and convert it to years, weeks and days. How to convert days to years, weeks in python programming. Logic to convert days to years, weeks and days in python program.

For Solution Click on  Solution of Program 6

Program 7. Write a python program to input temperature in degree Fahrenheit and convert it to degree centigrade. How to convert temperature from Fahrenheit to Celsius in python programming. Python program for temperature conversion. Logic to convert temperature from Fahrenheit to Celsius in python program.

For Solution Click on  Solution of Program 7

Program 8. Write a python program to input length and width of a rectangle and calculate perimeter and area of the rectangle. How to find perimeter and area of a rectangle in python programming. Logic to find the perimeter and area of a rectangle if length and width are given in python programming.

For Solution Click on  Solution of Program 8

Program 9. Write a python program to input principle (amount), time and rate (P, T, R) from user and find Simple Interest. How to calculate simple interest in python programming.

For Solution Click on  Solution of Program 9

Program 10. Write a python program to input marks of five subjects of a student and calculate total, average and percentage of all subjects. How to calculate total, average and percentage of marks of five subjects in python programming.

For Solution Click on  Solution of Program 10

Program 11. Write a python Program to input two angles of a triangle and find third angle of the triangle. How to find all angles of a triangle if two angles are given by user using python programming. Python program to calculate the third angle of a triangle if two angles are given.

For Solution Click on  Solution of Program 11

 

Leave a comment