Chap2_ Types, Operators & Expressions
Chap2_ Types, Operators & Expressions
Objectives
Learn about python integers, non-decimal integers, and float.
Understand Python strings and string manipulations.
Learn about escape characters and their role in strings.
Learn the string formatting basics.
Learn about Python Boolean.
Learn about different types of operators and their functionalities.
Easy to implement to work on for, while, if, elif, else statement
Learn about break, continue and pass statements.
Types-Integers
Python versions from 2.x onwards supported 4 built-in types i.e., int, long,
float and complex. All these data types supported very well in all equations.
Of course, the long data type will be released in the python version 3.x the
type is present of infinite extent as a avoidance. You don’t need to stipulate
which type of adjustable for your requirement; python ensures and
sustenance habitually.
Example
>>> type(x)
<class 'int'>
>>> x = 1828384857364223892624
>>> type(x)
<class 'int'>
>>> x = 5467839254735836192748295637582548583967
>>> type(x)
<class 'int'>
>>> x = 1.2376
>>> type(x)
<class 'float'>
>>> x = 3 + 5j
>>> type(x)
<class 'complex'>
PrintScreen Output
Output of division is little bit confusion. In Python2.x using the / operator
on two integer numbers will get additional integer number, by means of
floor division. For example 7/2 will give you 3. You need to stipulate
solitary of the operands as float to acquire the real/true division. For
example 7/2. or 7./2(the period describes you need to effort with float) will
get 3.5. But in python 3.x the output of spending the / operator is always
correct division.
Example
>>> 5/2
2.5
>>> 5/2.
2.5
>>> 5./2
2.5
Output
Comments:
1. Pure or long integer division, the output as integer.
2. Conversion from float using int() or long()
3. Built-in functions like abs(), all(), bool() etc.
4. Division operator used as divmod() function used as longer for comlex.
5. Referred as integer division.
6. Floats as well as agree to take the strings “and” and “inf” with an
optional prefix ‘+” or “-“.
7. Python define pow(0,0) and 0 ** 0 to be1 as is common for
programming language.
All Real numbers (int, long and float) support the subsequent operations:
Operation Result
Math.trunc(a) A abridged to integral
Round(a[, n]) A round to n digits. If n is mislaid, it evasions to 0
Math.floor(a) Maximum integer as a float <= a
Math.ceil(a) Minimum integer as a float >= a
Bitwise operations are solitary type intellect for integers. Negative numbers
are act as 2’s counterpart value. The importance of binary bitwise
operations are very poorer than the numeric actions and higher than
evaluations. The Unary operation has the equal significance as the extra
unary operations like + and -.
def bit_length(self):
s = bin(self) # binary representation: bin(-25) --> '-0b11001'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len(‘11001') --> 5
The float type works the numbers.Real abstract base class. Float
correspondingly has the subsequent procedures.
Float.as_integer_ratio(): Gives result a pair of Integers. Raises
OverflowError on infinites and a Value Error of available.
Float.is_integer(): Gives Right if the float occurrence of finite with
integral value, and incorrect or else.
Example
>>> (-3.0).is_integer()
True
>>> (5.4).is_integer()
False
Output
Strings are most common popular types in Python language. One major
difference is that Python strings are immutable, meaning that we are not
allowed to change individual parts of them as we could for a list. Through
strings we can build them merely by enfolding characters in quotation
marks. Python treats solitary quotation marks as similar as dual. Generating
strings is as very modest as passing on an assessment to a variable.
Constructors/literals:
Example
Syntax:
>>>help(str)
Or
>>>dir(“abc”)
Output:
>>> print(str1)
Output
Hello Dr.murali
>>> print(str2)
Output
good for learning python programming
Printscreen Output
Here str1 and str2 refers to the same string object “welcome” which is
stored somewhere in memory. You can test whether str1 refers to same
object as str2 using id() function.
>>> id (str1)
>>> 35146720
>>> id (str2)
>>> 35146720
As both str1 and st2 points to same memory location, hence they both
points to the same object. Lets try to modify str1 object by adding new
string to it.
‘welcomedr.murali’
>>>id(str1)
35213488
As you can see now str1 points totally different memory location, this
proves the point that concatenation doesn’t modify original string object
instead it create a new string object. Similarly Number (i.e. int type) is also
immutable.
Control codes control the way text is rendered in a console window or paper
printer. The string ‘\n’ contains single control code. The backslash (\)
signifies that the character that follows it is a control code, not a literal
character. The backslash is also known as escape symbol, and in this case
we say the n symbol is escaped.
\n represents a new line. Other control code is \t for tab, \f for form feed, \b
backspace, \a for alert.
Example
Print(‘A\bB\nC’)
Print(‘D\tE\tF’)
Print(‘WX\bYZ’)
Print(‘1\a2\a3\a4\5\a6’)
Output
A
B
C
D E F
WX*YZ
1*2*3*4*5*6
Printscreen Output
String Methods
Here some of the listed string methods which both 8-bit strings and Unicode
objects support. Around more than two are bytearray objects.
Apart, Python’s strings sustenance the order type methods defined in the
arrangement Types – like Str, Unicode, list, tuple, bytearray, buffer, xrange
segments. The result structured strings use a pattern strings or the %
operator defined in the String Configuring Operations Sections. And see the
remodule for string purposes established on regular expressions.
Syntax Explanation
Str.capitalize() Gives the result of the string first character
capitalized and remaining lowercased. when 8-bit
strings, are used this method is locale-dependent.
Output: String
Str.Center(width[, Shows the centered String length-width. Stuffing
fillchar]) is complete by means of the specific fill char.
Value: Centered string of length
Str.count(sub[, start[, Non-overlapping amounts of substring sub in the
end]]) range [start, end].
Output: Centered in string of length width.
Str.decode([encoding[, This method is used for codec registration for
errors]) encoding. Mistakes might be specified to set a
dissimilar error control structure.
Output: Decoded string
Str.encode([encoding[, Gives the result determined version of the string.
errors]) Default encoding is the present avoidance string
encoding.
Output: Encoded String
Str.endswith(suffix[, Return True string close with the specified suffix,
start[, end]]) else gives output False.
Output: TRUE the string with suffix, else FALSE.
Str.expandtabs([tabsize]) It will expand the tabs and replaced by one or
more spaces.
Flag Importance
‘#’ Used for value transformation. Where as an “alternate form”.
‘0’ Used for transformation as zero (0) expanded to numeric values
‘-‘ Used for transformed values is left adjusted.
‘‘ Used as blank (space0 should be left earlier a positive number
made by a signed conversion.
‘+’ Used for as signed character (‘+’ or ‘-‘) will precede the
conversion (overrides a “space” flag).
The length modifier (h, 1, or L) might be available, in somecases it is
overlooked as it as not essential for python. Example %1d is
indistinguishable to %d.
Some of conversion types are mentioned below.
Note:
Symbol Meaning
* Argument specified width or precision
- Left explanation
+ Demonstration the sign
<sp> Consent a total space formerly a positive number
# Octal leading zero(‘0’) or hexadecimal leading ‘0x’ or
‘0X’ depending on whether the ‘x’ or ‘X’ were used.
0 From left with zeros (instead of spaces)
% ‘%%’ leaves you with a single literal ’%’
(var) For Plotting variable
Types - Booleans
What is Boolean?
Boolean values are two different constant objects that is True or False. Here
they are used to signify truth values (other values can also be measured
false or true. In numeric situation (for sample, if you used as the argument
to an arithmetic operator), they act as identical the integers either 0 and 1,
resp. The built-in-function bool() should be used to cast any assessment to
a Boolean, if the value can be understood as a truth value. They are written
as False and True, respectively.
Booleans represents the truth values that are associated with logic branch of
mathematics, which informs algorithms in computer science. Named for the
mathematician George Boole, the word Boolean always being with a
capitalized B. The values TRUE and FALSE will also always be with a capital
letter staring with first letter T or F respectively and they are special values
in python.
In this basic functionalities we will represent how the Booleans are working
with comparison Operators.
Let us see some simple example how it will works with operators.
Example
x=5
y=8
print("x == y:", x == y)
print("x != y:", x != y)
print("x < y:", x < y)
print("x > y:", x > y)
print("x <= y:", x <= y)
print("x >= y:", x >= y)
Output
x == y: False
x != y: True
x < y: True
x > y: False
x <= y: True
x >= y: False
Prinstscreen Output
Operators
Operators are the creations; it could be manipulating the value of operands.
There are number of operators are available in our python language. Let us
with an simple consider an expression 1+4 = 5. Here, 1 and 4 are called
operands and + is called the operator. Operators are also used to perform
operations on different kinds of variables. Operators can be deploy
individual items and returns a result. The data items are referred as
operands or arguments. Operators are either represented by Keywords or
Special Characters. For example for identify operators we use keyword “is”
and “is not”.
Arithmetic operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators:
Assume variable X holds the value 10 and variable Y hold a value 21, then
Symb Expre
Operator Description Example
ol ssion
1. Adds values on both
sides of the operator.
2. X added to y, if x and y
+ Addition X+Y x + y = 31
are numbers
3. x concatenated to y, if x
and y are strings
1. Subtracts right hand
X–Y=-
- Subtraction operand from left hand X–Y
11
operand.
2. X take away y, if x and y
are numbers
1. Multiplies values on both
side of the operator.
2. X time y, if x and y
numbers
3. X concatenated with
X*Y=
* Multiplication itself y times, if x is a X *Y
210
string and y is and
integer. Y contacted with
itself x times, if y is a
string and x is an
integer
1. Divisions on left hand
operand by right hand
/ Division operand. X/Y y / x = 2.1
2. X divided by y, if x and y
are numbers
1. Divisions on left hand
operand by right hand
operand and give
% Modulus remainder. X%Y Y%X=1
2. Remainder of x divided
by y, if x and y are
numbers.
1. Makes exponential
(power) control on x**y = 10
** Exponent operators. X ** Y to the
2. X raised to y power, if x power 20
and y are numbers
1. Separation of operand
where the output is the
9//2 = 4
quotient in which the
Floor and
// digits later the decimal X // Y
Division 9.0//2.0
point are removed.
= 4.0
2. Floor of x divided by y, if
x and y are numbers
Example
>>>a = 21
>>>b = 10
>>>c = 0
>>>c = a + b
>>>c = a – b
>>>c = a * b
>>>c = a / b
>>>c = a % b
>>>a =2
>>>b = 3
>>>c = a**b
>>>a = 10
>>>b = 5
>>>c = a//b
Output
If you execute the above program, the output looks like this…
Line 1 – value of C is 31
Line 2 – Value of C is 11
Line 5 – Value of C is 2
Line 6 – value of C is 8
Line 7 – Value of C is 2
Comparison (Relational) Operators:
Example
a = 20
b = 10
c=0
if (a == b):
else:
if (a != b):
print ("line2 - a is not equal to b")
else:
if (a < b):
else:
if (a > b):
else:
a = 5;
b = 20;
if (a <= b):
else:
if (b >= a):
else:
Output
Printscreen Output
Assignment Operators
Assignment operators are castoff in python to allocate values to variables.
For example if x=3 is a simple task operator it allocates the value 3 on the
right side of the variable x on the left.
Here, there are different kinds of operators are available in python like x
+=3 it add to the variable and later assign the same. It is equal to x = x +
3.
See below the list of table…
We can assign different model with operands and variable but here I will
show you one simple example that assign the value to the operand.
Example1
num1 = 5
num2 = 8
Output
PrintScreen Output
Example 2
a = 20
b = 10
c=0
c=a+b
c += a
c *= a
c /= a
c=2
c %= a
c **= a
c //= a
print ("Line7 - value of c is ", c)
Output
Line1 - value of c is 30
Line2 - value of c is 50
Line5 - value of c is 2
PrintScreen Output
Logical Operators
The logical operators in python are used to check whether the conditional
statements are true or false. Logical operators in python are AND, OR and
NOT. For logical operators following conditions are applied.
- For AND Operator: if both operands are true gives the result TRUE
(Right side and Left side)
- For OR Operator: if either of the operand is true gives the result True
(Right side or Left Side)
- For NOT Operator: Gives the result TRUE if operand is False.
Example
a = True
b = False
Output
a and b is False
a or b is True
not a is False
PrintScreen output
Bitwise Operators
Bitwise operators work on bits and it perform bit-by-bit operation. Python’s
built-in-function bin() can be used to obtain binary representation of an
integer number. The following bitwise operators are supported by python
language.
Operator Description
& Binary AND Prints a bit output, if it available in both are operands
| Binary OR prints a bit, if it is available in either one of the operand.
^ Binary XOR Prints a bit, fix any one of the operand, but not both.
~ Binary Ones Unary and has the effect of flipping bits
complement
<< Binary left Left operand’s changed to left by the number of bits
Shift mentioned by right
>> Binary Right Left operand’s changed to right by the number of bits
Shift mentioned by the right
Example
a = 60
b = 13
print ('a=', a, ':', bin(a), 'b=', b, ':', bin(b))
c=0
c = a & b;
c = a | b;
c = a ^ b;
c = ~ a;
c = a << 2;
c = a >> 2;
Output
a= 60 : 0b111100
b= 13 : 0b1101
result of OR is 61 : 0b111101
Membership Operators
Membership operators are the operators check for membership in sequences
like lists, strings or tuples. Here, two different kinds of membership
operators that are used in python. (i.e., in, not in). It shows the output
based on the variable present in specified sequence or string.
Operator Description
in Calculate the value true (if it is available a variable in the
particular arrangement else false)
Not in Calculate the value true, (it if doesn’t find a variable in the
particular arrangement else false.
Example
m=5
n=8
list = [1, 2, 3, 4, 5]
if ( m in list):
else:
print ("Line1 - m is not available in the given list")
if ( n not in list ):
else:
Output
Identity Operators
Identity operators are used to match the memory locations of two objects.
There are two different kinds of identity operators are used in python
language. They are... “is”, and “is not”.
is: Returns true—two variable point are the same object otherwise false.
is not: Returns false—two variable point are the same object and true
otherwise.
Operator Description
is Evaluate true - if variable is moreover any side of the
operator is similar object and false otherwise.
is not Evaluate false – if variable is moreover any side of the
operator is similar object and true otherwise.
Example
m = 20
n = 20
if (m is n ):
n = 30
if (m is not n ):
Output
PrintScreen Output
Operator Description
** Exponentiation
~+- Complement, unary plus and minus
*/%// 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
Example
a=4
b=5
c=8
d=2
e=0
f = (a+b)* c / d;
Output
Among all the statements we may confuse which one is need to take to
match the perfect solution. For that we need a decision making statements
are required for expectation of situations happening whereas
implementation of the program and stipulating movements occupied
permitting by circumstances.
In general, the python software design dialectal also accepts any non-zero
and non-null values are also TRUE, and whether the value Zero or valueless,
formerly it is assumes as False value.
Here list of statements are mentioned python provides a decision making
statements.
Statement Description
if statement Used for Boolean Expression (execute one or
more statement)
if…else statement Used by an optional statement, gives the
output when Boolean expression is false
nested if statement either if, or else if or other in else if
statement(s).
Loop statement
Control Description
Statement
Break Terminates from the loop or switch. If a condition is met the
requirements.
Continue Rejects remaining statements from current iteration of the
loop.
Pass Used for a declaration is necessary for syntactically but not
necessary require any command or code to execute.
If statement
Syntax:
if expression:
statement(s)
If the Boolean expression calculates True, then the block of statement(s)
inside the if statement will be executed. If Boolean expression calculates to
False, then first block of the code next the completion of the if statement is
executed
or
if condition:
indentedStatementBlock
if the condition is true, the output will be executed based on the indented
statements. If it is not true, it will skip the next statements.
Flow Diagram
Example
Printscreen Output
If-else Statement
if condition :
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition
or
if expression:
Statement(s)
else:
Statement(s)
Flow Diagram
Example
print('Wear shorts.')
else:
Output
Wear shorts.
Printscreen output
elif statement
The elif statement is a usage to allow to find out various expressions for
TRUE and perform a block of code in a little while as one of the situations
calculate true.
It is equal to else, the elif declaration is an elective. Disparate else, there
can be maximum single statement, there can be an random number of elif
statement followed by if.
Core python will not afford switch or case statements as they are in
additional dialects, but then we use if..elif..statement is equal to switch
case as follows.
Syntax
if expression1:
Statement(s)
elif expression2:
Statement(s)
elif expression3
Statement(s)
else:
Statement(s)
Example
var = 100
if var == 200:
else:
Good bye
PrintScreen Output
It clause consists only if single line, and we can drive on the similar route
with heading declarations. Here is an example…
Example
var = 100
print ("thanks")
Printscreen Output
While Statement
Generally, in python we can write the program for a given number upto
some count either five or six etc., by using this method.
Print(1)
Print(2)
Print(3)
Print(4)
Print(5)
This is the small count we can write easily but if you want to increase your
count it is difficult to use this methodology. Instead of writing this functions
if you use loop it is very easy to write the code.
By using the while loop condition we can get the same output .
Syntax
While expression:
Statement(s)
Flow Diagram
Enter into
while
loop
False
Test
Condition
True
Note: The important point of the while loop is loop strength not always run.
Example 1
count = 1
print (count)
count +=1
Output
PrintScreen Output
Example 2
i = 10
sum = 0
n=1
while n <= i:
sum = sum + n
n = n+1
print("The sum is", sum)
Output
The sum is 55
Printscreen Output
There are two different methods we will work on definite loops and indefinite
loops. Let us see one example on both of the functions.
Definite Loop
Example
n=1
while n<=5:
print(n)
n += 1
Output
5
PrintScreen Output
Example2
n=1
stop = int(input())
print(n)
n += 1
Output
6
PrintScreen Output
Indefnite Loop:
In indefinite loop we cannot predict at any point during the loop’s execution
how many iterations the loop will perform. The value to match 999 is know
before and during the loop, but variable entry can be anything the user
enters.
Example
else:
PrintScreen Output
Statement(s)
or
For item in list:
action
action consists one or more statement, all the same indentation level. The
statements are also known as body of the loop. Item is a variable name, list
is a list.
Flow diagram
Each item in
sequence
Yes
If last item in
sequence
No
for i in [ 1,2,3,4,5,6]
Print i
Output
123456
Example 2
sum = 0
sum = sum+val
Output
PrintScreen output
Nested Loop
Python works to support Nested Loop and permits to habit to work single
loop privileged to different loop. Below shows how the nested loop will
works…
Syntax
statement(s)
statement(s)
Syntax
While expression:
While expression:
Statement(s)
Statement(s)
Example
Printscreen Output
Loop Control Statement
Break Statement
Like in C, the break statement, breaks out of the innermost enclosing for or
while loop. Loop statements may have an else clause: it is executed when
the loop ends through overtiredness of the list(with for) or when the
condition becomes false(with while), but not when the loop is terminated by
a break statement.
Syntax
break
Flow Chart
Model
count = 0
while True:
count += 1
if count > 5:
break
print ('count')
Output
count
count
count
count
count
Printscreen Output
Continue statement
Gets the output from the control from the starting of the while loop.
Continue statements discards all the outstanding declarations in existing
repetition of the loop and goes to the control back to the top of the loop.
Syntax
continue
Flow Chart
Example
count = 0
count += 1
if count % 2 == 0:
continue
print ('count')
Output
Count
Count
Count
PrintScreen output
Pass statement
Pass is a null statement. Nothing will happen when it performs the program.
Pass is used want to execute a statement is necessary syntactically but you
need not use any command or any code while perform the code.
Syntax
pass
Example
Count = 0
Pass
This is your code, but you are not finished writing the while loop, and want
to move to something else and go back to it later. It’s a perfect time to used
a pass statement. Your code won’t actually do anything. But you have got it
set up, properly formatted, and ready to go for when your code is
completed.
Example 2
number = 0
number = number + 1
if number == 5:
print('Out of loop')
Output
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop
PrintScreen Output
Summary
- Different kinds of methods for arithmetic calculation in python as you
can use the evaluate function, declare variable and calculate, or call
functions.
- In python strings are immutable meaning that we are not allowed to
change individual parts of them as we could for a list.
- Boolean values are two different constant objects that is True or False.
Here it is used to symbolize truth values (other values can also be
measured false or true
- Python also allows you to use a compound assignment operator, in a
complicated arithmetic calculation, where you can assign the result of
one operand to the other.
- For AND operator – return true if mutually the operands are true
- For OR operator – return false if moreover of the operand is true.
- For NOT operator – return true if operand is false.
- Use two membership operators are used in python i.e., in, not in
- Use two identity operators used in python i.e., is, is not
- Precedence operator are also very useful to set priority for which
calculations.
- The operator precedence is that which operator want to calculate first.
To avoid ambiguity in values, precedence operators are compulsory.
Quote: