Data Types and Operators
Data Types
Data types are nothing but variables you use to reserve some space in memory. Python variables do not need an explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable.
Number: Numbers have four types in Python. i.e int, long, float and complex.
int_num = 10 #int value float_num = 10.2 #float value complex_num = 3.14j #complex value long_num = 1234567L #long value
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants, True and False.
String: String are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Strings are immutable sequence data type, i.e each time one makes any changes to a string, completely new string object is created.
For example, "Hello, World!", "What is your name?" or "KA30V2Y556."
List Data Type: A list contains items separated by commas and enclosed within square brackets []. Lists are almost similar to arrays in C. One difference is that all the items belonging to a list can be of different data type.
list 1= [123,'abcd',10.2,'d'] #can be an array of any data type or #single data type. List2 = ['hello','world'] print(list1) #will output whole list. [123,'abcd',10.2,'d'] print(list1[0:2]) #will output first two element of list. [123,'abcd'] print(list1 * 2) #will gave list1 two times. ['hello','world','hello','world'] print(list1 + list2) #will gave concatenation of both the lists.[123,'abcd',10.2,'d','hello','world']
Tuple Data Type: Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are enclosed inparentheses ( ) and cannot be updated. Tuples are immutable.
tuple = (123,'hello') tuple1 = ('world') print(tuple) #will output whole tuple. (123,'hello') print(tuple[0]) #will output first value. (123) print(tuple + tuple1) #will output (123,'hello','world') tuple[1]='update' #this will give you error.
Set Data Type: 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.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket)
Dictionary Data Type: Dictionary consists of key-value pairs. It is enclosed by curly braces {} and values can be assigned and accessedusing square brackets[].
Dictionary Data Typeis only one standard mapping data type in Python called dictionary. Mapping is an unordered data type in Python.
dic={'name':'red','age':10} print(dic) #will output all the key-value pairs. {'name':'red','age':10} print(dic['name']) #will output only value with 'name' key. 'red' print(dic.values()) #will output list of values in dic. ['red',10] print(dic.keys()) #will output list of keys. ['name','age']
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 False nor 0 (zero).
myVar = None print(type(myVar)) <class 'NoneType'> print(myVar) Non
Mutable and Immutable Data Types:
Sometimes we may require to change or update the values of certain variables used in a program. However, for certain data types, Python does not allow us tochange the values once a variable of that type has been created and assigned values.
Variables whose values can be changed after they are created and assigned are called mutable. Variables whose values cannot be changed after they are created and assigned are called immutable. When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory.
Deciding Usage of Python:
Data Types It is preferred to use lists when we need a simple iterable collection of data that may go for frequent modifications.
For example, if we store the names of students of a class in a list, then it is easy to update the list when some new students join or some leave the course.
Tuples are used when we do not need any change in the data. For example, names of months in a year.
When we need uniqueness of elements and to avoid duplicity it is preferable to use sets, for example, list of artefacts in a museum.
If our data is being constantly modified or we need a fast lookup based on a custom key or we need a logical association between the key : value pair, it is advised to use dictionaries. A mobile phone book is a good application of dictionary.
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 whose categorisation is briefly explained in this section.
Arithmetic Operators
Python supports arithmetic operators that are used to perform the four basic arithmetic operations as well as modular division, floor division and exponentiation.
Operator | Description | Example | Result x = 10 and y = 5 |
---|---|---|---|
+ | Addition Adds the two numeric values on either side of the operator This operator can also be used to concatenate two strings on either side of the operator |
x + y | x + y will give 15 |
- | Subtraction Subtracts the operand on the right from the operand on the left |
x - y | x - y will give 5 |
* | Multiplication Multiplies the two values on both side of the operator Repeats the item on left of the operator if first operand is a string and second operand is an integer value |
x * y | x * y will give 50 |
/ | Division Divides the operand on the left by the operand on the right and returns the quotient |
x / y | x / y will give 2 |
% | Modulus or remainder Divides the operand on the left by the operand on the right and returns the remainder |
x % y | x % y will give 0 |
// | Floor Division Divides the operand on the left by the operand on the right and returns the quotient by removing the decimal part. It is sometimes also called integer division. |
x // y | x // y will give 2 |
** | Exponent Performs exponential (power) calculation on operands. That is, raise the operand on the left to the power of the operand on the right |
x ** y | x ** y will give 100000 |
Relational Operators
Relational operator compares the values of the operands on its either side and determines the relationship among them.
Operator | Description | Example | Result x = 10 and y = 5 |
---|---|---|---|
== | Equals to If the values of two operands are equal, then the condition is True, otherwise it is False |
x == y | x == y will give False |
!= | Not equal to If values of two operands are not equal, then condition is True, otherwise it is False |
x != y | x != y will give True |
> | Greater than If the value of the left-side operand is greater than the value of the rightside operand, then condition is True, otherwise it is False |
x > y | x > y will give True |
< | Less than If the value of the left-side operand is less than the value of the rightside operand, then condition is True, otherwise it is False |
x < y | x < y will give False |
>= | Greater than
or equal to If the value of the left-side operand is greater than or equal to the value of the right-side operand, then condition is True, otherwise it is False |
x >= y | x >= y will give True |
<= | Lass than
or equal to If the value of the left operand is less than or equal to the value of the right operand, then is True otherwise it is False |
x <= y | x <= y will give False |
Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
Operator | Description |
---|---|
= |
Assigns value from right-side operand to leftside operand |
+= |
It adds the value of right-side operand to the
left-side operand and assigns the result to the
left-side operand |
-= |
It subtracts the value of right-side operand from
the left-side operand and assigns the result to
left-side operand
|
*= |
It multiplies the value of right-side operand
with the value of left-side operand and assigns
the result to left-side operand |
/= |
It divides the value of left-side operand by the
value of right-side operand and assigns the
result to left-side operand |
%= |
It performs modulus operation using two
operands and assigns the result to left-side
operand |
//= |
It performs floor division using two operands
and assigns the result to left-side operand |
**= |
It performs exponential (power) calculation on
operators and assigns value to the left-side
operand |
Logical Operators
The logical operator evaluates to either True or False based on the logical operands on either side. Every value is logically either True or False. By default, all values are True except None, False, 0 (zero), empty collections "", (), [], {}, and few other special values.
There are three logical operators supported by Python. These operators (and, or, not) are to be written in lower case only.
Operator | Description | Example | Result x = 10 and y = -20 |
---|---|---|---|
and | Logical AND If both the operands are True, then condition becomes True |
x and y | x and y will give True |
or | Logical OR If any of the two operands are True, then condition becomes True |
x or y | x or y will give True |
not | Logical NOT Used to reverse the logical state of its operand |
not x | not x will give False |
Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or not. Identity operators can also be used to determine whether two variables are referring to the same object or not. There are two identity operators.
Operator | Description | Example |
---|---|---|
is | Evaluates True if the variables on either side of the operator point towards the same memory location and False otherwise. var1 is var2 results to True if id(var1) is equal to id(var2) |
>>> num1 = 5 >>> type(num1) is int True >>> num2 = num1 >>> id(num1) 1433920576 >>> id(num2) 1433920576 >>> num1 is num2 True |
is not | Evaluates to False if the variables on either side of the operator point to the same memory location and True otherwise. var1 is not var2 results to True if id(var1) is not equal to id(var2) |
>>> num1 is not num2 False |
Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not.
Operator | Description | Example |
---|---|---|
in | Returns True if the variable/value is found in the specified sequence and False otherwise |
>>> a = [1,2,3] >>> 2 in a True >>> '1' in a False |
not in | Returns True if the variable/value is not found in the specified sequence and False otherwise |
>>> a = [1,2,3] >>> 10 not in a True >>> 1 not in a False |
Expressions
An expression is defined as a combination of constants, variables, and operators. An expression always evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression. Some examples of valid expressions are given below.
(i) 100 (iv) 3.0 + 3.14 (ii) num (v) 23/3 -5 * 7(14 -2) (iii) num – 20.4 (vi) "Global" + "Citizen
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains different kinds of operators, precedence determines which operator should be applied first.
Higher precedence operator is evaluated before the lower precedence operator. Most of the operators studied till now are binary operators.
Binary operators are operators with two operands. The unary operators need only one operand, and they have a higher precedence than the binary operators. The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not is a unary logical operator.
The following table lists precedence of all operators from highest to lowest.
Order of Precedence | Operators | Description |
---|---|---|
1 | ** | Exponentiation (raise to the power) |
2 | ~ ,+, - | Complement, unary plus and unary minus |
3 | * ,/, %, // | Multiply, divide, modulo and floor division |
4 | +, - | Addition and subtraction |
5 | <= , < , > , >=, == , != | Relational and Comparison operators |
6 | =, %=, /=, //=, -=, +=,*=, **= | Assignment operators |
7 | is, is not | Identity operators |
8 | in, not in | Membership operators |
9 | not | Logical NOT |
10 | and | Logical AND |
11 | or | Logical OR |
Note:
a) Parenthesis can be used to override the precedence of operators. The expression within () is evaluated first.
b) For operators with equal precedence, the expression is evaluated from left to right
Example (expression evaluation in Python)
15.0 / 4 + (8 + 3.0) = 15.0 / 4 + (8.0 + 3.0) #Step 1 = 15.0 / 4.0 + 11.0 #Step 2 = 3.75 + 11.0 #Step 3 = 14.75 #Step 4
Statement
In Python, a statement is a unit of code that the Python interpreter can execute.
Example
>>> x = 4 #assignment statement >>> cube = x ** 3 #assignment statement >>> print (x, cube) #print statement
Type Conversion
Type Conversion change the data type of a variable in Python from one type to another.
Such data type conversion can happen in two ways: either explicitly (forced) when the programmer specifies for the interpreter to convert a data type to another type; or implicitly, when the interpreter understands such a need by itself and does the type conversion automatically.
Explicit type conversion functions in Python
Function | Description |
---|---|
int(x) | Converts x to an integer |
float(x) | Converts x to a floating-point number |
str(x) | Converts x to a string representation |
int(x) | Converts x to an integer |
chr(x) | Converts ASCII value of x to character |
ord(x) | returns the character associated with the ASCII code x |
Debugging
A programmer can make mistakes while writing a program, and hence, the program may not execute or may generate wrong output. The process of identifying and removing such mistakes, also known as bugs or errors, from a program is called debugging. Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors
Like other programming languages, Python has its own rules that determine its syntax. The interpreter interprets the statements only if it is syntactically (as per the rules of Python) correct. If any syntax error is present, the interpreter shows error message(s) and stops the execution there.
For example, parentheses must be in pairs, so the expression (10 + 12) is syntactically correct, whereas (7 + 11 is not due to absence of right parenthesis. Such errors need to be removed before the execution of the program.
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A logical error produces an undesired output but without abrupt termination of the execution of the program. Since the program interprets successfully even when logical errors are present in it, it is sometimes difficult to identify these errors. The only evidence to the existence of logical errors is the wrong output. While working backwards from the output of the program, one can identify what went wrong.
For example, if we wish to find the average of two numbers 10 and 12 and we write the code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not the average of 10 and 12. The correct code to find the average should have been (10 + 12)/2 to give the correct output as 11.
Logical errors are also called semantic errors as they occur when the meaning of the program (its semantics) is not correct.
Runtime Error
A runtime error causes abnormal termination of program while it is executing. Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it. Runtime errors do not appear until after the program starts running or executing.
For example, we have a statement having division operation in the program. By mistake, if the denominator entered is zero then it will give a runtime error like "division by zero".
Let us look at the following program showing two types of runtime errors when a user enters non-integer value or value '0'. The program generates correct output when the user inputs an integer value for num2.
#Runtime Errors Example num1 = 10.0 num2 = int(input("num2 = ")) #if user inputs a string or a zero, it leads to runtime error print(num1/num2)
Example Programs
1.Write a Python program to compute area of a circle
# Assign a value to radius radius = 10 # radius is now 20 # Compute area area = radius * radius * 3.14159 # Display results print("The area for the circle of radius", radius, "is", area) OUTPUT: The area for the circle of radius 10 is 314.159
2.Write a Python program to compute area of a circle (reading radius from the Console)
# Prompt the user to enter a radius radius = eval(input("Enter a value for radius: ")) # Compute area area = radius * radius * 3.14159 # Display results print("The area for the circle of radius", radius, "is", area) OUTPUT: Enter a value for radius: 20 The area for the circle of radius 20 is 1256.636
3.Write a Python program to convert temperature in degree Celsius to degree Fahrenheit. If water boils at 100 degree C and freezes as 0 degree C, use the program to find out what is the boiling point and freezing point of water on the Fahrenheit scale. (Hint: T(°F) = T(°C) × 9/5 + 32)
# defining the boiling and freezing temp in celcius boil = 100 freeze = 0 print('Water Boiling temperature in Fahrenheit::') # Calculating Boiling temperature in Fahrenheit tb = float(boil * (9 / 5) + 32) # Printing the temperature print(tb) print('Water Freezing temperature in Fahrenheit::') # Calculating Boiling temperature in Fahrenheit tf = float(freeze * (9 / 5) + 32) # Printing the temperature print(tf) OUTPUT: Water Boiling temperature in Fahrenheit:: 212.0 Water Freezing temperature in Fahrenheit:: 32.0
5. Write a Python program to calculate the amount payable if money has been lent on simple interest.
Principal or money lent = P, Rate of interest = R% per annum and Time = T years. Then Simple Interest (SI) = (P x R x T)/ 100.
Amount payable = Principal + SI. P, R and T are given as input to the program.
# Asking the user for Principal, rate of interest and time P = float(input('Enter the principal: ')) R = float(input('Enter the rate of interest per annum: ')) T = float(input('Enter the time in years: ')) # calculating simple interest SI = (P * R * T) / 100 # caculating amount = Simple Interest + Principal amount = SI + P # Printing the total amount print('Amount payable:', amount) OUTPUT: Enter the principal: 10000 Enter the rate of interest per annum: 12 Enter the time in years: 2 Amount payable: 12400.0
6.Write a program that swap the values stored in the variables a and b.
a = 50 b = 35 a, b = b, a print("a:", a, "b:", b) OUTPUT: a: 35 b: 50
7.Write a program that adds the digits in a 2 digit number. e.g. if the input was 52, then the output should be 5 + 2 = 7
# Get the two digit number twoDigitNumber = input("Type a two digit number: ") # #Get the first and second digits using subscripting then convert string to int. firstDigit = int(twoDigitNumber[0]) secondDigit = int(twoDigitNumber[1]) # Add the two digits together sum = firstDigit + secondDigit print("Sum of the digits in ", twoDigitNumber, "is:", sum) OUTPUT: Type a two digit number: 85 Sum of the digits in 85 is: 13
8.Write a program that calculates the Body Mass Index (BMI) from a user's weight and height.
The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m).
# Get weight and height weight = float(input("Type weight in Kg: ")) height = float(input("Type height in m: ")) # calculate and print BMI bmi = weight / (height * height) print("bmi", format(bmi, '0.2f')) OUTPUT: Type weight in Kg: 55 Type height in m: 1.72 bmi 18.59