UNIT - 2
Data Types
◦ Programming languages need a variety of data types in order to better model/match the
world
◦ more data types make programming easier but too many data types might be confusing
◦ Almost all programming languages provide a set of primitive data types
◦ primitive data types are those not defined in terms of other data types
◦ some primitive data types are implemented directly in hardware (integers, floating point,
etc) while others require some non-hardware support for their implementation.
Data Types
Data Types
• Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fraction or decimal).
• In Python there is no limit to how long an integer value can be.
• Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point.
• Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Data Types
Data Types
Boolean
▪ Data type with one of the two built-in values, True or False.
▪ Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false
▪ It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid Booleans otherwise
python will throw an error.
Operators
Python has many operators. Some examples are:
+, -, *, /, %, >, <, ==, //, print
Operators perform an action on one or more operands. Some
operators accept operands before and after themselves:
operand1 + operand2, or 3 + 5
Others are followed by one or more operands until the end of
the line, such as: print “Hi!”, 32, 48
When operators are evaluated, they perform action on their
operands, and produce a new value.
Operators
Some operators should be familiar from the world of
mathematics such as Addition (+), Subtraction (-), Multiplication
(*), and Division (/).
Python also has comparison operators, such as Less-Than (<),
Greater-Than (>), Less-Than-or-Equal(<=), Greater-Than-or-Equal
(>=), and Equality-Test (==). These operators produce a True or
False value.
A less common operator is the Modulo operator (%), which gives
the remainder of an integer division. 10 divided by 3 is 9 with a
remainder of 1:
10 // 3 produces 3, while 10 % 3 produces 1
Operators
NOTE! Some operators will work in a different way depending
upon what their operands are. For example, when you add two
numbers you get the expected result: 3 + 3 produces 6.
But if you “add” two or more strings, the + operator produces a
concatenated version of the strings: “Hi” + “Jay” produces
“HiJay”
Multiplying strings by a number repeats the string!
“Hi Jay” * 3 produces “Hi JayHi JayHiJay”
The % sign also works differently with strings:
“test %f” % 34 produces “test 34” (try this and let me know the
answer)
Operators
In Python, all data has an associated data “Type”.
You can find the “Type” of any piece of data by using the type()
function:
type( “Hi!”) produces <type 'str'>
type( True ) produces <type 'bool'>
type(5) produces <type 'int'>
type(5.0) produces <type 'float'>
Note that python supports two different types of numbers,
Integers (int) and Floating point numbers (float). Floating Point
numbers have a fractional part (digits after the decimal place),
while Integers do not!
Effect of Data Types on Operator Results
Math operators work differently on Floats and Ints:
int + int produces an int
int + float or float + int produces a float
This is especially important for division, as integer division
produces a different result from floating point division:
10 // 3 produces 3
10 / 3 produces 3.3333
10.0 / 3.0 produces 3.3333333
Other operators work differently on different data types: +
(addition) will add two numbers, but concatenate strings.
Type Conversion
Data can sometimes be converted from one type to another. For example,
the string “3.0” is equivalent to the floating point number 3.0, which is
equivalent to the integer number 3
Functions exist which will take data in one type and return data in another
type.
int() - Converts compatible data into an integer. This function will truncate floating
point numbers
float() - Converts compatible data into a float.
str() - Converts compatible data into a string.
Examples: Try other
int(3.3) produces 3 str(3.3) produces “3.3” Combinations
which may
float(3) produces 3.0 float(“3.5”) produces 3.5
give error
int(“7”) produces 7
int(“7.1”) throws an ERROR!
float(“Test”) Throws an ERROR!
Python Arithmetic Operators
a= 10 b=20
Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left a - b will give -10
hand operand
* Multiplication - Multiplies values on either side of the a * b will give 200
operator
/ Division - Divides left hand operand by right hand b / a will give 2
operand
% Modulus - Divides left hand operand by right hand b % a will give 0
operand and returns remainder
** Exponent - Performs exponential (power) calculation on a**b will give 10 to the power
operators 20
// Floor Division - The division of operands where the result 9//2 is equal to 4 and 9.0//2.0
is the quotient in which the digits after the decimal point is equal to 4.0
are removed.
Python Comparison Operators:
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then (a == b) is not true.
condition becomes true.
!= Checks if the value of two operands are equal or not, if values are (a != b) is true.
not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if values are (a <> b) is true. This is
not equal then condition becomes true. similar to != operator.
> Checks if the value of left operand is greater than the value of right (a > b) is not true.
operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right (a < b) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value (a <= b) is true.
of right operand, if yes then condition becomes true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to c = a + b will assigne
left side operand value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand c += a is equivalent to c
and assign the result to left operand =c+a
-= Subtract AND assignment operator, It subtracts right operand from the c -= a is equivalent to c =
left operand and assign the result to left operand c-a
*= Multiply AND assignment operator, It multiplies right operand with the c *= a is equivalent to c
left operand and assign the result to left operand =c*a
/= Divide AND assignment operator, It divides left operand with the right c /= a is equivalent to c =
operand and assign the result to left operand c/a
%= Modulus AND assignment operator, It takes modulus using two operands c %= a is equivalent to c
and assign the result to left operand =c%a
**= Exponent AND assignment operator, Performs exponential (power) c **= a is equivalent to c
calculation on operators and assign value to the left operand = c ** a
//= Floor Division and assigns a value, Performs floor division on operators c //= a is equivalent to c
and assign value to the left operand = c // a
Assume if a = 60; and b = 13;
Python Bitwise Now in binaryformat they will be as follows:
Operators:
a = 0011 1100
b = 0000 1101
Operator Description Example
& Binary AND Operator copies a bit to the result if it (a & b) will give 12 which is
exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in either (a | b) will give 61 which is
operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (a ^ b) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has (~a ) will give -60 which is
the effect of 'flipping' bits. 1100 0011
<< Binary Left Shift Operator. The left operands value is a << 2 will give 240 which is
moved left by the number of bits specified by the 1111 0000
right operand.
>> Binary Right Shift Operator. The left operands value is a >> 2 will give 15 which is
moved right by the number of bits specified by the 0000 1111
right operand.
Python Logical Operators:
Operato
Description Example
r
and Called Logical AND operator. If both the operands are (a and b) is true.
true then then condition becomes true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition becomes
true.
not Called Logical NOT Operator. Use to reverses the not(a and b) is false.
logical state of its operand. If a condition is true then
Logical NOT operator will make false.
Python Membership Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here in results in a 1
specified sequence and false otherwise. if x is a member of sequence
y.
not in Evaluates to true if it does not finds a variable x not in y, here not in
in the specified sequence and false otherwise. results in a 1 if x is a
member of sequence y.
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, 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
Strings
◦ Strings are not like integers, floats, and booleans. A string is a sequence, which means it is an ordered
collection of other values.
◦ A string is a sequence: A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
◦ >>> fruit = 'banana'
◦ >>> letter = fruit[1]
◦ The second statement selects character number 1 from fruit and assigns it to letter.
◦ The expression in brackets is called an index. The index indicates which character in the sequence you
want (hence the name). But you might not get what you expect:
◦ >>> letter
◦ 'a’
Strings
◦ For most people, the first letter of 'banana' is b, not a. But for computer scientists, the
index is an offset from the beginning of the string, and the offset of the first letter is zero.
◦ >>> letter = fruit[0]
◦ >>> letter
◦ 'b'
◦ So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the
2th letter (“two-eth”).
◦ As an index you can use an expression that contains variables and operators:
◦ >>> i = 1
◦ >>> fruit[i]
◦ 'a'
◦ >>> fruit[i+1]
◦ 'n'
Strings
◦ But the value of the index has to be an integer. Otherwise you get:
◦ >>> letter = fruit[1.5]
◦ TypeError: string indices must be integers
Strings: len
◦ len is a built-in function that returns the number of characters in a string:
◦ >>> fruit = 'banana'
◦ >>> len(fruit)
◦6
◦ To get the last letter of a string, you might be tempted to try something
like this:
◦ >>> length = len(fruit)
◦ >>> last = fruit[length]
◦ IndexError: string index out of range
◦ >>> last = fruit[length-1]
◦ >>> last
◦ 'a'
Strings: len
◦ Fruit[-1]=??
◦ Fruit[-2]=??
◦ The expression fruit[-1] yields the last letter, fruit[-2] yields the second to
last, and so on.
String slices
◦ A segment of a string is called a slice. Selecting a slice is similar to
selecting a character:
◦ >>> s = 'Monty Python'
◦ >>> s[0:5]
◦ 'Monty'
◦ >>> s[6:12]
◦ 'Python’
◦ The operator [n:m] returns the part of the string from the “n-eth”
character to the “m-eth” character, including the first but excluding the
last.
String slices
◦ If you omit the first index (before the colon), the slice starts at the beginning of the string.
◦ If you omit the second index, the slice goes to the end of the string:
◦ >>> fruit = 'banana'
◦ >>> fruit[:3]
◦ 'ban'
◦ >>> fruit[3:]
◦ 'ana’
◦ If the first index is greater than or equal to the second the result is an empty string,
represented
◦ by two quotation marks:
◦ >>> fruit = 'banana'
◦ >>> fruit[3:3]
◦ ''
String slices
◦ If you omit the first index (before the colon), the slice starts at the beginning of the string.
◦ If you omit the second index, the slice goes to the end of the string:
◦ >>> fruit = 'banana'
◦ >>> fruit[:3]
◦ 'ban'
◦ >>> fruit[3:]
◦ 'ana’
◦ If the first index is greater than or equal to the second the result is an empty string,
represented
◦ by two quotation marks:
◦ >>> fruit = 'banana'
◦ >>> fruit[3:3]
◦ ''
String slices
◦ An empty string contains no characters and has length 0, but other than that, it is the same as
any other string.
◦ Continuing this example, what do you think fruit[:] means? Try it and see.
◦ Strings are immutable
◦ It is tempting to use the [] operator on the left side of an assignment, with the intention
of changing a character in a string. For example:
◦ >>> greeting = 'Hello, world!'
◦ >>> greeting[0] = 'J’
◦ TypeError: 'str' object does not support item assignment
◦ The “object” in this case is the string and the “item” is the character you tried to assign.
Strings are immutable
◦ The reason for the error is that strings are immutable, which means you
can’t change an existing string. The best you can do is create a new
string that is a variation on the original:
◦ >>> greeting = 'Hello, world!'
◦ >>> new_greeting = 'J' + greeting[1:]
◦ >>> new_greeting
◦ 'Jello, world!'
◦ This example concatenates a new first letter onto a slice of greeting. It
has no effect on the original string..
String methods
◦ Strings provide methods that perform a variety of useful operations.
◦ The method upper takes a string and returns a new string with all uppercase
letters.
◦ >>> word = 'banana'
◦ >>> new_word = word.upper()
◦ >>> new_word
◦ 'BANANA’
◦ This form of dot notation specifies the name of the method, upper, and the name
of the string to apply the method to, word. The empty parentheses indicate that
this method takes no arguments.
String methods
◦ >>> word = 'banana'
◦ >>> index = word.find('a')
◦ >>> index
◦1
◦ In this example, we invoke find on word and pass the letter we are looking for as
a parameter.
◦ The find method can find substrings, not just characters:
◦ >>> word.find('na')
◦2
◦ By default, find starts at the beginning of the string, but it can take a second argument, the index
where it should start:
◦ >>> word.find('na', 3)
◦4
String methods
◦ find can also take a third argument, the index where it should stop:
◦ >>> name = 'bob'
◦ >>> name.find('b', 1, 2)
◦ -1
◦ This search fails because b does not appear in the index range from 1 to 2, not
including 2.
◦ Searching up to, but not including, the second index makes find consistent with
the slice operator.
The in operator
◦ The word in is a boolean operator that takes two strings and returns True if
the first appears as a substring in the second:
◦ >>> 'a' in 'banana'
◦ True
◦ >>> 'seed' in 'banana'
◦ False