0% found this document useful (0 votes)
5 views

Chap2_ Types, Operators & Expressions

This document provides an overview of Python data types, including integers, floats, strings, and complex numbers, as well as their operations and methods. It explains the immutability of strings, the use of escape characters, and various string manipulation techniques. Additionally, it covers control flow statements and type conversion in Python.

Uploaded by

Ananya Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chap2_ Types, Operators & Expressions

This document provides an overview of Python data types, including integers, floats, strings, and complex numbers, as well as their operations and methods. It explains the immutability of strings, the use of escape characters, and various string manipulation techniques. Additionally, it covers control flow statements and type conversion in Python.

Uploaded by

Ananya Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

2.

Types, Operators and Expressions


Chapter Outline
 Introduction  Types  Operators
 Expressions  Control flow

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.

 Int (singed Integers): Intricate integer type, even in every


programming language we can use this data types casually and can
execute the values as like in python, it is also corresponding to the
hardware like ‘c long’ for the platform using in python 2.x unlimited
length in python 3.x
 Long (long Integers): It is also integer data type with limitless
measurement. In python 2.2 and later, ints are mechanically bowed
hooked on long ints whey they runoff where numerals and tracked by
an upper case or lower case L.
 Float (floating point real values): It is also a binary floating point
number. Whenever we are used float data type, the long and int are
routinely transformed into floats, as soon as the float is castoff an
expression, with the true-division/operator. Floats also be an
significant notation, with E or e indicating the power of 10 (2.5e2 =
2.5 X 102 =250)

 Complex (complex numbers): It is a compound quantity having of


two floats. Multifaceted literals are inscribed as a+bj when a and b are
floating-point numbers indicating the actual and unreal amounts resp.

General, sequence of this Integers are….


Int-> Long-> Float-> Complex. The out of to the right you go, the
higher precedence.

Here are some examples…


Int Long Float Complex
20 45368763L 0.0 2.13j
300 -0x54387L 25.10 34.j
-566 2112L -13.6 9.344e-43j
085 0Xdredrtgyewsuytgfdiu 34.3+e16 .678j
-0560 34543787659876L -50 -.4565+Oj
-0x350 -876234165843L -23.45e200 3e+34j
0x57 -6574389734373L 60.2 – E22 5.45e-6j

 Python gives the instruction to you use a lowercase L with long,


because used for an uppercase L to evade the misperception with the
numeral 1.
 Complex numbers consists have an well-ordered pair of actual
floating point numerals represented by a+bj, wherever a is actual
part and b is imaginary part.

Number Type Conversion

Python coverts the numerals as usually inside in an expression comprising


varied kinds to a collective type of assessment.
 Int(x) will be converted as plain integer.
 Long(x) will be converted as long integer.
 Float(x) will be converted as floating-point number.
 Complex(x) will be converted as complex number with real part x and
imaginary part zero.
 Complex(x, y) will be converted as complex number with real part x
and imaginary part y.
Let us see one good example how the integer types will work.

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.

Let us see one more example on these operands

Example
>>> 5/2
2.5
>>> 5/2.
2.5
>>> 5./2
2.5

Output

All built-in numeric categories sustenance the next actions.


Operation Result Comments
a+b sum of a and b
a–b difference of a and b
a*b product of a and b
a/b quotient of a and b 1
a // b quotient (floored) of a and b 4, 5
a%b remainder of a / b 4
-a a negated
+a a unchanged
abs(a) absolute value or magnitude of a 3
int(a) a transformed to integer value 2
long(a) a transformed to long integer 2
float(a) a transformed to floating point 6
complex(re,.im) complex with real and imaginary default
to 0
c.conjugate() conjugate the complex number c
divmod(a ,b) the pair (a//b, a%b)
pow(a,b) a to the power of b
a ** b a to the power of b

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

Use bitwise operation on Integer Type

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 -.

Table shows the bitwise operations…


Operation Result
a|b bitwise or of a and b
a^b bitwise exclusive or of a and b
a%b bitwise of a and b
a << n a moved left by n bits
a >> n a moved right by n bits
~a the bits of x reversed

Additional Methods on integer Types


Integer categories implement the numbers.Integral abstract base class. In
calculation, they support more than one method like:
 int.bit_length()
 long.bit_length() : Gives the number of bit required.
Example
>>> n = -25
>>> bin(n)
'-0b11001'
>>> n.bit_length()
5
Output

Where x is nonzero, then x.bit_length() is the distinctive positive


integer k such that 2**(k-1) <= abs(x) < 2**K. It is equivalent to..

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

Superfluous Methods on Float Types

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

 Float.hex() : gives the floating point number as a hexadecimal string.


 Float.fromhex(s): Technique to give return the float by a hexadecimal
string s.
Types - Strings
String is a arrangement of characters. A character is merely say that a sign
representation. For instance, our English alphabets are 26 characters. If we
want to deal directly to computer it doesn’t understand the characters, the
arrangement with number that is binary number. Even nevertheless you
could realize characters on your canopy, inside it is store and influenced as
a permutation of 0’s and 1’s.

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.

In python string is arrangement of Unicode character. Unicode was


familiarized and to consist of each character in all languages and convey
consistency in encoding.

How to Create a String?

Strings can be built by enclosing characters privileged a single quote or


double quotes. Sometimes we use triple quotes also in python but generally
used to signify multiline strings and docstrings.

String operations (methods)

String operators, e.g., + < <=, ==, etc

Constructors/literals:

 Quotes: single or double. #Escaping quotes and other special


characters with a back-slash.
 Triple quotes: use triple single or double quotes to define multi-line
strings.
 Str() – constructor and the name of the type/class
 ‘aSeparator’. Join(aList)
 Escape characters in strings -- \t, \n, \\, etc

Example

Syntax:
>>>help(str)

Or

>>>dir(“abc”)

Output:

>> str1 = “Hello Dr.murali”

>>> print(str1)

Output

Hello Dr.murali

>>> str2 = “good for learning python programming”

>>> print(str2)

Output
good for learning python programming

Printscreen Output

Strings in python are immutable.

What is it mean? Once string is created it can’t be modified. Let’s take an


example to illustrate this point.

>>> str1 = “welcome”

>>> str2 = “welcome”

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.

What is id(): Every object in python is stored somewhere in memory. We


can use id() to get the memory address.

>>> 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.

>>> str1 + = “dr.Murali”


>>> str1

‘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 within Strings


The characters that can appear within strings include letters of the alphabet
(A-Z, a-z), digits (0-9), punctuation (.,:.,etc.), and other printable symbols
(#, %, &, etc). In addition to these “normal” characters, we may embed a
special characters called as control code.

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.

Here the list of table explain the strings methods.

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.

Output: methods returns a copy of the string


have been expanded using spaces.
Str.find(sub[, start[, Gives last index string wherever substring sub is
end]]) bring into being with in the slice.
Note: find() method must be castoff only if you
want to distinguish the location of the sub. To find
out if “sub” is a substring or not, use the in
operator.

Output: Index if originate and -1 else.


Str.format(*args, Used for a string configuring operation. Comprise
**kwargs) literal text or replacement field delimited by
braces{}.

Output: formatting operation


Str.line(sub[, start[, Similar to find(), increase valueError where
end]]) substring is not found
Output: Gives the line of the method
Str.isalnum() Gives the result right all characters a string are
alphanumeric and atleast one character, else
false.
Output: TRUE all characters in a string else at
least one character, FALSE otherwise
Str.isalphs() Gives the result all characters are alphabetic
atleast one one character false.
Output: returns true if all characters in the string
Str.isdigit() Gives the result if all the characters are digits and
if and if only atleast one character, else false.
Output: true if all characters in the string are
digits.
Str.islower() Gives the result if all cased characters[4] are
lowercase and atleast one cased characters, else
false.
Output: True if all cased characters in the string
are lowercase.
Str.isspace() Gives the result true only whitespace characters in
the string.
Output: True, whitespace characters are
available.
Str.istitle() Gives the true value result string is a title cased
string and need at least one character.
Output: String is a title cased string
Str.isupper() Gives the true if all cased characters are
uppercased and need at least one character, else
false.
Output: True all characters in the string are upper
case
Str.join(iterable) Gives the result which is the concatenation strings
are iterable.
Output: Concatenation of the string is sequence
seq.
Str.ljust(width[, fillchar]) Gives the result the string is mentioned a left
justified of length width.
Output: Left justified in a string.
Str.lower() Gives the result a copy of the string with all the
cased characters transformed into lowercase.
Output: Returns a copy of the string.
Str.lstrip() Gives the result leading characters removed. The
char argument is a string stipulating the usual of
characters to be detached.

Output: Returns a copy of the string in which all


char from the beginning.
Str.partition(sep) Gives the result to split the string, starting
incidence of sep and reappearance a 3-tuple.
Output: Give the partitions by separation
Str.replace(old, new[, Gives the copy of string, with incidences of
count]) substring long-standing replace by original.
Output: Replaced by old to new.
Str.find(sub[, start[, Gives the result for highest index of a string.
end]]) Output: Index if found and -1 otherwise
Str.rfind(sub[, start[, Gives the result for highest index of a string,
end]]) somewhere the substring is found.
Output: Returns last index if found.
Str.rindex(sub[, start[, Similar to rfind() but increases ValueError when
end]]) the substring sub is not originate.
Output: Returns last index if found an exception
Str.rjust(width[, fillchar]) Shows the right defensible in a string of length
width.
Output: String is returned, width is less than
len(s).
Str.rpartition(sep) Gives the result of string of last manifestation of
separator.
Output: Separator used for partition
Str.rsplit([sep[, Gives the list of words in a string, use sep as
maxsplit]]) delimiter string.
Output: split the separation with max limit
Str.split([sep[, Returns a list words in a string, use separator as
maxsplit]]) the delimiter string. If maxsplit is specified, at
most maxsplit splits are finished.
Output: Returns a list of lines
Str.splitlines([keepends]) Used for list of lines in a string, at a contravention
at line boundaries. Python identifies ‘\r”, “\n” and
“\r\n” as line margins.

Output: Returns true if found matching string


Unicode.splitlines([keepe Unicode methods separations line boundaries,
nd]) they are a superset of the collective newlines
standard for 8-bit strings.
Representation Description
\n Line feed
\r Carriage return
\r\n Carriage Return + Line Feed
\v or\x0b Line tabulation
\f or \x0c Form feed
\x1c File separator
\x1d Group separator
\x1e Record separator
\x85 Next line(c1 is control code)
\u2028 Line separator
\u2029 Paragraph separator
Str.startswith(prefix[, Gives the result True if string starts with the prefix
start[, end]]) otherwise return false.
Output: True if found matching.
Str.strip([chars]) Returns a copy of the string leading and trailing
characters removed.
Output: Gives a copy of the string in which all
chars have been unprotected.
Str.swapcase() Copy of the string with uppercase converted to
lowercase and vice versa
Output: copy the string where all the case-based
characters.
Str.tanslate(table[, Reads all the strings where all the characters are
deletechars]) optional arguments delete char are removed.
Output: Translate the value
Str.zfill(width) Returns the numeral string left filled with zeros in
a string of length width.
Output: Return padding string
String Configuring Processes
String and Unicode object need one unique built-in operations that is: the %
operators(modulo). It is similarly identified by as simple, then we can call
them as string configuring or exclamation operator. Specified format %
values (format is a string or Unicode object), % changes of provisions in
setup are substituted with zero or more features of standards. This is very
familiar and parallel to the string sprint() in c language. Format is a Unicode
object, or any of the substances existence by transformed by means of the
%s transformation are Unicode objects, output will be a Unicode object.

If design needs a solitary argument, values may be single non-tuple object.


If not, values essential be a tuple and number of stated by the format
string. The adaptation specifier holds two or more characters and has the
following components, which is this order:

 % character, starts of the specifier


 Plotting key (optional), containing of a parenthesized seq of
characters (for example (somename)).
 Transformation flags (optional), which affect the output of about
translation types.
 Conversion type is also supported
 Length of modifier is also optional
 Precision mention as ‘.’ Followed by precision. If mentioned by *
asterisk, width is read from the next element.
 Minimum filed width is necessary.

The transformation flag characters be situated as:

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.

Conversion Importance Comments


‘d’ Used for Signed integer decimal --
‘I’ Used for signed integer decimal --
‘o’ Used for Signed octal value (1)
‘u’ Used for obsolete type – it is identical to ‘d’.
‘x’ Used for signed hexadecimal (lowercase) (2)
‘X’ Used for signed hexadecimal (uppercase) (2)
‘e’ Floating point exponential format (lowercase) (3)
‘E’ Floating point exponential format (uppercase) (3)
‘f’ Floating point deciaml format (3)
‘F’ Floating point decimal format (3)
‘g’ Floating point for lower exponential is less (4)
than -4 or not less than precision, decimal
format
‘G’ Floating point for upper exponential is less (4)
than -4 or not less than precision, decimal
format
‘c’ Single character (accepts integer or single --
character string)
‘r’ String (converts any python object using (5)
repr())
‘s’ String (converts any python object using (6)
str())
‘%’ No argument is converted, results in a ‘%’ --
character in the result

Note:

1. Another method form roots a important zero (‘0’) be introduced


amongst left-hand padding and the arranging the number of foremost
character of the output is not already a zero.
2. Different methods from origins a leading ‘0x’ or ‘0X’.
3. Alternate method origins the output comprise a decimal point, if there
is no digits follows it.
4. Results always comprise a decimal point, and sprawling zeroes are not
detached as they would or else be.
5. The %r conversion was additional in python 2.0.
6. Object or format as long as in a Unicode string, output string is also
be Unicode.
Some reinforced symbols and their functionality mentioned below
table:

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.

The table below shows Boolean Comparison Operators.

Operator What it means


== Equal to
!= Not Equal to
< Less than
> Greater Than
<= Less than or equal to
>= Greater than or equal
to

Boolean Actions – and, or, not

Boolean operations, arranged by ascending importance:

Basic Result Comments


Functionality
a or b If A is false, then y, else a See Note 1
a and b If A is false, then a, else b See Note 2
Not a If A is false, then True else False See Note 3
Note:

1. It is a short-circuit operator, calculate the second argument if the first


one is false.
2. It is also a short-circuit Method, only it evaluates the second argument
if it is first one is True.
3. Not has a lower priority than non-Boolean operators, so not a ==b is
interpreted as not (a == b), and a == not b is a syntax error.

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”.

There are different kinds of operators are available in python language.


They are…

 Arithmetic operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us study one by one with detail methodologies.

Arithmetic Operators:

Common binary operators for arithmetic are + for addition, - for


subtraction, * for multiplication, and / for division, % for modulo, ** for
exponent.

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

>>>print (“line1 – value of c is “, c)

>>>c = a – b

>>>print (“line2 – value of c is “, c)

>>>c = a * b

>>>print (“line3 – value of c is “, c)

>>>c = a / b

>>>print (“line4 – value of c is “, c)

>>>c = a % b

>>>print (“line5 – value of c is “, c)

>>>a =2

>>>b = 3

>>>c = a**b

>>>print (“line6 – value of c is “, c)

>>>a = 10

>>>b = 5
>>>c = a//b

>>>print (“line7 – value of c is “, c)

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 3 - Value of C is 210

Line 4 – Value of C is 2.1

Line 5 – Value of C is 2

Line 6 – value of C is 8

Line 7 – Value of C is 2
Comparison (Relational) Operators:

Besides the arithmetic operators we need to use comparison operators in


python language. These operators match the values on either side of the
operand and find relations between them. And it is also called as Relational
operator. These operators match the values on either side of them and
decided with amongst them.

See below list of table for comparison operators…

Symbol Operator Description Expression


== Equal to Both operands are equal X == Y
Both operands are not
!= Not Equal to X != Y
equal
If values of both operand
<> Conditional are not equivalent, then X <>Y
condition becomes true.
True left operand is
> Greater than X>Y
greater than right
True Left operand is less
< Less than X<Y
than right
Greater than Left operand is greater
>= X >= Y
Equal to than or equal to right
Less than True if left operand is less
<= X <= Y
Equal to than or equal to the right

Example
a = 20

b = 10

c=0

if (a == b):

print ("line1 - a is equal to b")

else:

print ("line2 - a is not equal to b")

if (a != b):
print ("line2 - a is not equal to b")

else:

print ("line2 - a is equal to b")

if (a < b):

print ("line3 - a is less than b")

else:

print ("line3 - a is not less than b")

if (a > b):

print ("line4 - a is greater than b")

else:

print ("line4 - a is not greater than b")

a = 5;

b = 20;

if (a <= b):

print ("line5 - a is either less than or equal to b")

else:

print ("line5 - a is neither less than not equal to b")

if (b >= a):

print ("line6 - b is either greater than or equal to b")

else:

print ("line6 - b is neither greater than nor equal to b")

Output

line2 - a is not equal to b

line2 - a is not equal to b

line3 - a is not less than b


line4 - a is greater than b

line5 - a is either less than or equal to b

line6 - b is either greater than or equal to b

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…

Operator Example Equivalent to


= X=3 X=3
+= X+=3 X = X+ 3
-= X-=3 X=X–3
*= X*=3 X = X*3
/= X /= 3 X = X/3
%= X%=3 X = X%3
//= X//=3 X = X//3
**= X**=3 X = X**3
&= X&=3 X=X&3
|= X|= 3 X=X|3
^= X^=3 X=X^3
>>= X >>= 3 X = X >>3
<<= X <<= 3 X = X <<3

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

print ("Line1 - value of num1 : ", num1)

print ("Line2 - value of num2 : ", num2)

Output

Line1 - value of num1 : 5

Line2 - value of num2 : 8

PrintScreen Output
Example 2

a = 20

b = 10

c=0

c=a+b

print ("Line1 - value of c is ", c)

c += a

print ("Line2 - value of c is ", c)

c *= a

print ("Line3 - value of c is ", c)

c /= a

print ("Line4 - value of c is ", c)

c=2

c %= a

print ("Line5 - value of c is ", c)

c **= a

print ("Line6 - value of c is ", c)

c //= a
print ("Line7 - value of c is ", c)

Output

Line1 - value of c is 30

Line2 - value of c is 50

Line3 - value of c is 1000

Line4 - value of c is 50.0

Line5 - value of c is 2

Line6 - value of c is 1048576

Line7 - value of c is 52428

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.

See list of below table operator and its description…

Operator Description Example


And Logical AND Both operands are TRUE, then working (a and b)
function becomes true is False
Or logical OR Any two operands are non-zero then (a or b) is
working function becomes true True
Not Logical NOT Used to reverse the logical state of its Not(a and
operand b) is TRUE

Example

a = True

b = False

print ("a and b is", a and b)

print ("a or b is", a or b)

print ("not a is", not a)

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;

print ("result of AND is", c, ':', bin(c))

c = a | b;

print ("result of OR is ", c, ':', bin(c))

c = a ^ b;

print ("result of EXOR is ", c, ':', bin(c))

c = ~ a;

print ("result of COMLEMENT is ", c, ':', bin(c))

c = a << 2;

print ("result of LEFT SHIFT is ", c, ':', bin(c))

c = a >> 2;

print ("result of RIGHT SHIFT is ", c, ':', bin(c))

Output

a= 60 : 0b111100

b= 13 : 0b1101

result of AND is 12 : 0b1100

result of OR is 61 : 0b111101

result of EXOR is 49 : 0b110001

result of COMLEMENT is -61 : -0b111101

result of LEFT SHIFT is 240 : 0b11110000

result of RIGHT SHIFT is 15 : 0b1111


Printscreen Output

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):

print ("line1 - m is available in the given list")

else:
print ("Line1 - m is not available in the given list")

if ( n not in list ):

print ("Line2 - n is not available in the given list")

else:

print ("Line2 - n is available in the given list")

Output

line1 - m is available in the given list

Line2 - n is not available in the given list

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 ):

print ("m & n are SAME idenity")

n = 30

if (m is not n ):

print ("m & n have DIFFERENT identity")

Output

m & n are SAME idenity

m & n have DIFFERENT identity

PrintScreen Output

- Declare the value for variable m and n


- Use the operator “is” in code to check the value of m is same as n
- Run the code – output of the result is as expected
- Next use the operator “is not” in code if value of m is not equal to n
Operator Precedence
The operator precedence is that which operator evaluates first. To avoid
ambiguity in values, precedence operators are compulsory. Its like in normal
multiplication method, multiplication has a higher precedence than addition.
Let us see one example the mathematical calculation ie., 2+3*4, the answer
is 14, to change the order of precedence we use a square brackets i.e.,
(2+3)*4, now the answer is 20. Precedence operator are used in python are
(unary + - ~, **, */, +-, &) etc.,

See the below list of table…

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;

print ("Output is (a+b)* c/d is", f)

Output

Output is (a+b)* c/d is 36.0


Printscreen Output
Expressions
You have wide-range of the standard forward arrangement of processes with
their meanings on loop statements. To find your complete influence of over
your programs, you must focus on essential to extra creations that varying
the flow of control: decision choosing among alternative (if statements), and
more and more common rounds that are not necessity to be measured by
the basics necessary information of a collection.

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.

These (decision making) constructions calculate different (sometimes


various) expression which we gives Either True or False as output. When we
want to regulate which action to proceeds and which statement to perform if
result based is True or False required and else.

Here below shows the common system of usual decision making


construction used in maximum general software design dialects: i.e..,

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).

In general, we need to execute the number of statements consecutively.


The primary declaration function is performed initially, and followed by
others. Sometimes we want to perform the chunk of code more and more
times. It’s best practice you can used loop statement to execute the
statements or group of statement for multiple times.

Here the flow of diagram shows the loop statements:


Python also supports different kinds of loops to execute the number of more
statements.

Loop Type Description


While loop Like a if statement, the test condition is true: statements get
executed. Difference is after the statement have been
executed, the test condition is checked again.
For loop Is similar to while, but little differently, for statements are
often used to process lists such a range of numbers
Nested loop Used more and more loop privileged any additional while
and for.

Loop statement

Loop control statements are need to transformation of implementation from


its standard arrangement. While execution some leaves a choices, all
automatic objects will be built in that scope are demolished. Python also
maintain some of the statements are mentioned below table..

Here the list of statement are mentioning below.

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.

Let us start our python programming with if statements:

If statement

It is also equal to the additional dialects. The if statement have a logical


expression by means of which data need to compare and choice made
depend on the results.

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

weight = float(input("How many pounds does your suitcase weigh? "))

if weight > 50:

print("There is a $25 charge for luggage that heavy.")

print("Thank you for your business.")


Output

How many pounds does your suitcase weigh? 65

There is a $25 charge for luggage that heavy.

Thank you for your business.

Printscreen Output

If-else Statement

A If-else statement can be used having a block of code it executes if the


conditional expression in the if statement resolves to 0 or False value.
Syntax

if condition :
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition

or

if expression:

Statement(s)

else:

Statement(s)

Flow Diagram
Example

temperature = float(input('What is the temperature? '))

if temperature > 25:

print('Wear shorts.')

print('Drink more water')

else:

print('Wear long pants.')

print(‘Take Some Precautions.')

Output

What is the temperature outside in degrees? 35

Wear shorts.

Drink more water

What is the temperature outside in degrees? 21

Wear long pants.

Take Some Precautions.

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:

print ("1 - Got a true expression value,")

elif var == 150:

print ("2 - Got a true expression value,")

elif var == 100:

print ("3 - Got a true expression value,")

else:

print ("4 - Got a false expression value,")

print ('Good bye')


Output

3 - Got a true expression value,

Good bye

PrintScreen Output

Single statement Set:

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

if (var == 100): print ('value of var is 100')

print ("thanks")

Printscreen Output
While Statement

While loop statement in python program design dialectal frequently


performs a objective declaration as extended to available condition is true.

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)

The output is looks like this…

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

While loop body of


statements Exit

Note: The important point of the while loop is loop strength not always run.

Example 1

Write a python to print numbers in sequential order

count = 1

while count <= 5:

print (count)

count +=1
Output

PrintScreen Output

Example 2

Write a python program to sum of n Natural numbers

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

Definite loops and Indefinite Loops

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

Write a program to print n numbers in a serial order

n=1

while n<=5:

print(n)

n += 1

Output

5
PrintScreen Output

Example2
n=1

print (‘enter the range’)

stop = int(input())

while n <= stop:

print(n)

n += 1

Output

enter the range

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

done = False #Enter the loop at least once

print ('Enter the range')

while not done:

entry = eval(input()) # Get value from user

if entry == 9: # did user provide the magic number?

done = True # if so, get out

else:

print(entry) # if not, print it and continue


Output

Enter the range

PrintScreen Output

The for Statement


Iterative over a sequence or an “iterable” object.

Iterative means something than can be used in an iterator context. For


example in for: statement, a list comprehension, and in a generator
expression. Sequences and containers are iterable. Example: tuple, string,
lists, dictionaries. Classes that obey the iterator protocol are iterable. We
can create an iterator object in functions such as iter() and enumerate().
Functions Yield statement, produce an iterator.
Syntax

For iterating var in sequence:

Statement(s)

if a sequence having an expressions list, it calculates Primarily. First item in


the arrangement is allocated to the repeating variable iterating_var.

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

Statements in for loop Exit for loop


Example 1

Write a program to print numbers

for i in [ 1,2,3,4,5,6]

Print i

Output

123456

Example 2

Write a program to find the sum of all number stored in a list.

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

sum = 0

for val in numbers:

sum = sum+val

print("The sum is", sum)

Output

>>> The sum is: 48

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

for iterating_var in sequence:

for iterating_var in sequence:

statement(s)

statement(s)

Nested while loop in Python are mentioned below:

Syntax

While expression:

While expression:

Statement(s)

Statement(s)

Example

persons = [ "Mohan", "Ravi", "Govind", "Abhi" ]

restaurants = [ "Apple", "Mango", "Guava", "Strawberry" ]

for person in persons:

for restaurant in restaurants:

print(person + " eats " + restaurant)


Output

Mohan eats Apple


Mohan eats Mango
Mohan eats Guava
Mohan eats Strawberry
Ravi eats Apple
Ravi eats Mango
Ravi eats Guava
Ravi eats Strawberry
Govind eats Apple
Govind eats Mango
Govind eats Guava
Govind eats Strawberry
Abhi eats Apple
Abhi eats Mango
Abhi eats Guava
Abhi eats Strawberry

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

while count < 6:

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.

The metamorphosis amongst a pass and comment i.e.., interpreter ignores


a comment, but pass is not ignored. The only one thing that is the
difference. However, nothing to worry when a pass is performed, it results
no action.

Syntax

pass

For suppose, we written in a program on loop or a function that is not


executed yet, if you want to implement may in forthcoming. This cannot
have an unfilled body. The translator would complain. So, you can use the
pass statement to build a body that prepares nothing.

Example

Count = 0

While (count < 4)

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

for number in range(10):

number = number + 1
if number == 5:

pass # pass here

print('Number is ' + str(number))

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:

One of the very important characteristics of a student is to question. Let the


students ask questions.

--A. P. J. Abdul kalam

You might also like