2. LEARNING
OBJECTIVES
❖ To know how to explain and use data types.
❖ The Difference between Mutable and
Immutable Types
❖ To learn about the operators in python
❖ To learn more about Python Standard Library
Modules.
3. DATA TYPES
Data type specifies to the type of data we are going to store, the amount of
memory it will take and type of operation we can perform on that variable.
Build in core data type
● Numbers
● String
● List
● Tuple
● Dictionary
4. Numbers
❏ Store numeric values
❏ Types :
1. Integers - whole numbers without fractional part.
● integers(signed)
It is the normal representation of whole numbers. Maybe signed or unsigned as well.
● Boolean
Represents the truth values TRUE AND FALSE . It is a subtype of integers as TRUE AND FALSE behave
as 1 and 0 respectively
1. Floating point numbers - A number with a fractional part.
● Fractional form - Normal decimal form
● Exponent notation - represented with Mantissa and Exponential notation
They can represent values between the integers and can represent a greater range of values. But
floating point operations are slower than integer operations.
5. 3. Complex numbers-
In python complex numbers are represented in the form A+Bj. To represent imaginary
numbers, python uses j or J in place of i . so in python j = √-1
Both real and imaginary parts are of type float
To retrieve real and imaginary part of complex numbers, the following attributes are used:
If the complex number is a then a.real and a.imag are used
Eg. >>>: a=3+45j
>>>print(a.real)
3.0
>>> print(a.imag)
45.0
6. Questions…..
1. Why is Boolean considered a subtype of integer ?
Boolean values True and False internally map to integers 1 and 0. That is,
internally True is considered equal to 1 and False equal to 0 (zero). When
1 and 0 are converted to Boolean through bool() function, they return
True and False. That is why Booleans are treated as a subtype of integers
7. 1. Identify the data types of the values given below : 3, 3j, 13.0, ‘13’,
“13”, 2+0j, 13
3 integer
3j complex number
13.0 Floating-point number
‘13’ string
“13” string
2+0j complex number
13 integer
8. String
➔ Collection of any valid characters in single, double or triple quotation
marks.
➔ Used to store information like address, name, description etc.
➔ Each character stored in string is a Unicode character. Unicode is
system designed to represent every character from every language.
➔ A python string is a sequence of characters and each character can be
individually accessed using it’s INDEX.
➔ Strings in python are stored by storing
each character separately in contiguous
locations.
➔ Index is also called Subscript.
9. ➔ To access can character as
<stringname>[<index>]
➔ The first character of the string is at index 0
or -length
➔ The last character is at index(length-1) or -1.
➔ As string is immutable, item assignment is not supported..
Eg .
➔ However, a string as a whole can be replaced by another string.
10. Lists
➢ A list represents a list of comma-separated values of any data type within
square brackets[ ]
➢ List is mutable.
11. Tuples
❏ Tuples are similar to list.. Except that they are written in Parentheses or
Round Brackets, ( )
❏ And they are immutable.
12. SETS
● Sets are created by specifying comma-separated values enclosed in curly
brackets { }
● Sets elements are unordered and unindexed unlike lists.
● Sets do not allow duplicate entries like lists.
● Sets cannot contain mutable elements but set itself is mutable.
13. Dictionary
❖ Dictionary is an unordered set of comma-separated key:value pairs with { }.
❖ Within a dictionary, no two keys should be same.
❖ Dictionary is mutable
14. MUTABLE AND IMMUTABLE
❖ Those types whose value can
be changed in place.
❖ Lists , sets and dictionaries
are mutable.
❖ Those types that never change
their value in place.
❖ Integers,floating point numbers,
boolean, strings, tuples are
immutable .
15. Mutable types are those whose values can be changed in place whereas
Immutable types are those that can never change their value in place.
Mutable types in Python are:
1. Lists
2. Dictionaries
3. Sets
Immutable types in Python are:
1. Integers
2. Floating-Point numbers
3. Booleans
4. Strings
5. Tuples
What are Immutable and Mutable types in Python? List immutable and
mutable types of Python.
16. Variable internals
Python calls every entity that stores any values or any type of data as object.
Every python object has three key attributes associated to it.
They are :
➔ The Type of an object
The type an object determines the operations that can be performed on the
object. The build-in function type() returns the type of an object.
➔ The Value of an object
It is the data item contained in the object. For a literal, the value is the literal
itself and for a variable , the value is the data item it is currently referencing.
Using print statement you can display the value.
➔ The Id of an object
The id is the memory location of the object. The id() returns the id of an object.
17. Operators
➔ Symbols that trigger the operation or action are called operators.
➔ The data on which operation is being carried out is called operands .
➔ Python has the following types of operators :-
★ Arithmetic operators
★ Relational operators
★ Identity operators
★ Logical operators
★ Bitwise operators
★ Membership operators
18. Arithmetic operators
Unary operators - The operators that act on one operand.
➔ Unary +
● The operator unary ‘+’ precedes an operand. The operand of the unary +
operator must have arithmetic type .
Eg., if a = 5 , then +a = 5
If a = -5, then +a = -5
➔ Unary -
● The operator unary - precedes an operand. The operand of the unary -
operator must have arithmetic type.
Eg, if a = 5 , then -a = -5
If a = -5, then -a = 5
19. Binary Operator
Operators that act upon two operands are referred to as Binary Operators.
➔ Addition operator +
➔ Subtraction operator -
➔ Multiplication operator *
➔ Division operator /
➔ Floor Division operator //
➔ Modulus operator %
➔ Exponentiation operator **
20. What are three internal key-attributes of a value-variable in Python ? Explain
with example
22. Relational operator
In the term of relational operator, relational refers to the relationship that value
can have with one another. Python provides 6 relational operators for comparing
values, thus they are also called comparison operators. They result in Boolean
True and False.
The six operators are:
< - less than
> - greater than
<= - less than or equal to
>= - greater than or equal to
== - equal to
!= - not equal to
They work on certain principles (pg.176)
23. Relational operators with arithmetic operators
Relational operators have lower precedence than arithmetic operators.
So the expression a + 5 > c - 5 will correspond to (a+5) > (c-5)
Another common mistake is to use the assignment operator = in place of
the relational operator == .
The assignment operator = is used for assigning values while the relational
operator == is used for comparison.
24. Identity operator - is and is not
They are used to check if both operands refer to the same object memory.. I.e, the
identity operators compare the memory locations of two objects and returns True
or False accordingly.
➔ The is operator returns True if both its operands are pointing to the same
object (objects with the same memory location) , returns False otherwise.
➔ The is not operator returns True if both its operands are pointing to
different object (objects with different memory location) , returns False
otherwise.
25. Equality (==) and Identity (is)
Is the relational operator (==) and the identity operator (is) the same?
The == tests for equality of the value stored while Is operator tests for the same
identity .
For a value stored and another value which is asked from the user…
The relational operator will give True is they are same values .
But the identity operator will return False because in some special cases python
creates different id locations even though the values are same
Those special cases are
● Input of strings from console
● Writing integers literals with many digits
● Writing floating point and complex numbers.
26. Is it true that if two objects return True for is operator, they will also return
True for == operator?
Yes, if is operator returns true, it implicitly means that the equality operator
will also return True. is operator returning true implies that both the variables
point to the same object and hence == operator must return True
27. Are these values equal? Why/why not?
1. 20 and 20.0
2. 20 and int(20)
3. str(20) and str(20.0)
4. 'a' and "a"
1. The type of 20 is int whereas the type of 20.0 is float so they are two different objects.
Both have the same value of 20. So, as values are same equality (==) operator return
True but as objects are different is operator returns False.
2. The value and type of both 20 and int(20) are the same and both point to the same
object so both equality (==) and is operator returns True.
3. For str(20) and str(20.0), both equality (==) and is operator returns False as their
values are different and they point to two different objects.
4. For 'a' and "a", both equality (==) and is operator returns True as their values are
same and they point to the same object.
28. Logical operators
Truth value testing . pg 182
The or Operator
Relational expressions
When or operator has its operands as
Relational expression then the or operator
performs as per this principle
Numbers / strings / lists as operands
When or operator has its operands as numbers or strings or lists then the or
operator performs as per the following.
29. X Y X or Y
false false Y
false true Y
true false X
true true X
30. The and operator
The and operator combines two expressions, which make its operands. The and
operator works in these ways:
➔ relational expressions as operands
X Y X and Y
True True True
True False False
False False False
False True False
32. The not operator
➔ It is a unary operator
➔ The logical not operator reverses the truth value of the expression .
Bitwise Operator
The AND operator &
It compares two bits and
generates a result of 1
if both bit are 1,
otherwise it will return 0.
X Y X & Y
0 0 0
0 1 0
1 0 0
1 1 1
33. The inclusive OR operator ( | )
It compares two bits and generates
a result of 1 , if any bit is 1 ,
otherwise it will return 0.
The eXclusive OR (^)
It compares two bits and generate
result of 1 if either bit is 1 and returns
0 if both values are 0 or 1 .
X Y X | Y
0 0 0
0 1 1
1 0 1
1 1 1
X Y X^Y
0 0 0
0 1 1
1 0 1
1 1 0
34. The Complement Operator ~
It inverts the value of each bit of the operand.
If the operand bit is 1 the result is 0 and is the operand is 0 the result is 1.
X X~
0 1
1 0
36. Expression
An expression in Python is any valid combination of operators and
atoms. An expression is composed of one or more operations.
An Atom is somethings that has a value. Identifiers, literals,strings,lists
etc are all atoms.
There are different types of expression in python, they are:
❖ Arithmetic Expression
❖ Relational Expression
❖ Logical Expression
❖ String Expression
❖ Compound Expression
38. Relational Expression
An expression having literals and/or variables of any valid type and
relational operators is an relational expression.
For example:
➔ X > Y
➔ a <= c
➔ z==y
39. Logical Expression
An expression having literals and/or variables of any valid type and
logical operators is a logical expression.
For example:
➔ A or B
➔ x and y
➔ c and not b
40. String Expression
Python also provides two string operators + and *, when combined with
string operands and integers, form string expressions.
➢ With operator +, the concatenation operator, the operands should
be of string type only.
For example:
➔ Concatenation ➔ Replication
41. Compound Expression
An expression can be compound expression if it involves multiple types
of operators i.e, A compound expression can involve arithmetic as well
as relational as well as logical operators.
For example:
➔ a+b>c**d or a*b<c**d
➔ p*y >=z*x and x-p<= x*y
42. Evaluating Expressions
Evaluating Arithmetic Expressions
In order to evaluate the arithmetic expression Python follows certain
rules.
❏ Determine the order of evaluation by considering operator
precedence and associativity.
❏ Implicit conversion takes place if mixed type is used in an
expression.
43. Implicit Conversion ( Coercion)
An implicit type conversion is a conversion performed by the compiler
without programmer’s intervention. An implicit conversion is applied
generally whenever different data types are intermixed in an expression
so as not to lose information.
The rule is very simple Python, converts all operands up to the type of
the largest operand. This is called type promotion.
44. If both arguments are standard numeric types, the following
coercions are applied:
➢ If either argument is a complex number, the other is converted to
complex;
➢ Otherwise, if either argument is a floating point number, the
other is converted to floating point;
➢ No conversion if both operands integers.
★ If the operator is division (/) then the answer will always be in
floating point even if both the operands are integer types.
46. Evaluating Relational
Expressions
➢ Executed based on operator precedence and associativity.
➢ All relational expressions yield boolean value True or False.
➢ For chained comparisons like x < y < z is equivalent to x < y and y < z
48. Evaluating Logical Expressions
➢ The precedence of logical operators is lower than arithmetic
operators, so arithmetic sub expressions are evaluated first and
then logical operators are applied.
➢ The precedence of logical operators among themselves is not, and ,
or.
49. ➢ While evaluating logical expressions Python minimizes the internal
work by following these rules:
➔ In or evaluation, Python only evaluates the second argument if the
first one is false
➔ In and evaluation, Python only evaluates the second argument if
the first one is true
tval
tval
50. Questions
1. What is an expression?
2. Types of expressions in python.
3. What is coercion?
4. Find the output:
a= 5
b= 3.5
c= 25
X= (a+b)*c
Y= b/2 * c/5
51. Type Casting
Python internally changes the data type of
some operands so that all operands have
same data type. This data type of conversion
is automatic, i.e implicit conversion without
programmer’s intervention. But Python also
supports explicit type conversion.
The explicit conversion of an operand to a
specific type is called type casting.
52.
53. Python Standard Library
MODULES
Other than built-in functions, standard library also provides some
modules having functionality for specialized actions. A Python module
is a file which contains some variables and constants, some functions,
objects etc. defined in it, which can be used in other Python programs.
In order to use a module, you need to first import the module in a
program and then you can use the module functions, variables,
constants and other objects in your program file.
56. Using randrange() function
It can be used in 3 ways:
I. random.randrange(stop value): generates a random number from 0
to stop value.
II. random.range(start,stop):generates a random number from the
range of start value to stop value.
I. random.range(start,stop,step): generates a random number in the
range of start value to stop value with a multiple of step value.
59. 1) Write a program to read
the base and height of a
right triangle and
compute the hypotenuse.
(using math module)
2) Write a program to read
the radius of a circle and
find its circumference
and area.
Question
60. Debugging
An error causing disruption in program's running or in producing right
output, is a 'program bug. Debugging involves rectifying the code so
that the reason behind the bug gets resolved and thus bug is also
removed.
Errors in a Program
An error, sometimes called 'a bug', is anything in the code that prevents a
program from compiling and running correctly. There are broadly three
types of error: Compile-time errors, run-time errors and logical errors.
61. Compile-time errors
Errors that occur during compile-time, are compile-time errors. When a program
compiles, is source code is checked for whether it follows the programming
language's rules or not. Two types of errors fall into category of compile-time
errors.
1. Syntax Errors
Syntax errors occur when rules of a programming language are misused.
Eg: X<-Y*Z
If X = (X*Y)
2. Semantic Errors
Semantics Errors occur when statements are not meaningful.
Eg: X*Y=Z
62. Logical Errors
Sometimes, even if you don't encounter any error during compile-time
and run-time, your program does not provide the correct result. This is
because of the programmer's mistaken analysis of the problem he or
she is trying to solve.
Eg: an incorrectly implemented algorithm, or use of a variable before its
initialization, or unmarked end for a loop, or wrong parameters passed
are often the hardest to prevent and to locate.
63. Run-Time Errors
Errors that occur during the execution of a program are run-time errors.
These are harder to detect errors. Some run-time errors stop the
execution of the program which is then called program "crashed" or
"abnormally terminated".
Eg: an infinite loop or wrong value (of different data type other than
required) is input
64. Exceptions
An Exception refers to any irregular situation occurring during
execution/run-time, which you have no control on.
65. Debugging using
Code Tracing
Code tracing means executing code one
line at a time and watching its impact on
variables. One way of code tracing is
using Dry run. Code tracing can also be
done by debugging tools or debugg
available in software form.
66. 1. What is debugging?
2. What are the errors in python?
3. An infinite loop is an example of
what type of error?
Question