Module 3
Module 3
• Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
• Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
print(counter)
print(miles)
print(name)
• Variable Scope: Most variables in Python are local in scope to their own function or
class. For instance if you define a = 1 within a function, then a will be available within
that entire function but will be undefined in the main program that calls the function.
Variables defined within the main program are accessible to the main program but not
within functions called by the main program.
• Global Variables: Global variables, however, can be declared with the global keyword.
Then you can change the values in the variable defined globally.
For example: But, this won’t work:
a=1 def ret_sum():
b=2 a=1
def print_sum():
b=2
print(a + b)
return a + b
print_sum()
print(a + b)
output: 3
output: NameError: name 'a' is not defined
Note: Can’t change a or b
• input: Allow the user to input a string. WARNING: input accepts your input as a command
and thus can be unsafe.
• import: Import a module into Python. Can be used as import math and all functions in
math can then be called by math.sin(1.57) or alternatively from math import sin and
then the sine function can be called with sin(1.57).
• A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $ and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.
6
© Nex-G Exuberant Solutions Pvt. Ltd.
Reserved Words in Python
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
7
© Nex-G Exuberant Solutions Pvt. Ltd.
Python expressions can include:
• Python allows you to assign a single value to several variables simultaneously. For
example −
a=b=c=1
• Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables. For example −
a, b, c = 1, 2, "john"
• Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the
same amount. Both blocks in this example are fine:
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False“
Thus, in Python all the continuous lines indented with similar number of spaces would form a
block.
10
© Nex-G Exuberant Solutions Pvt. Ltd.
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Statements contained within the [], {} or () brackets do not need to use the line continuation
character. For example:
11
© Nex-G Exuberant Solutions Pvt. Ltd.
Quotation in Python:
Python accepts single ('), double (") and triple (''' or """') quotes to denote string literals, as
long as the same type of quote starts and ends the string.
The triple quotes can be used to span the string across multiple lines. For example, all the
following are legal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to
the physical line end are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
A line containing only whitespace, possibly with a comment, is known as a blank line and Python
totally ignores it. In an interactive interpreter session, you must enter an empty physical line to
terminate a multiline statement
13
© Nex-G Exuberant Solutions Pvt. Ltd.
delete a variable
You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example:
del var
del var_a, var_b
The Python interpreter has a number of functions built into it that are always available.
Return the absolute value of a number. The argument may be a plain or long integer or a floating
point number. If the argument is a complex number, its magnitude is returned.
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent
to:
def any(iterable):
for element in iterable:
if element:
return True
return False
© Nex-G Exuberant Solutions Pvt. Ltd.
Built-in Functions
bin(x):
Convert an integer number to a binary string. The result is a valid Python expression. If x is
not a Python int object, it has to define an __index__() method that returns an integer.
class bool([x]) :
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth
testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool
is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only
instances are False and True.
callable(object)
Return True if the object argument appears callable, False if not. If this returns true, it is still
possible that a call fails, but if it is false, calling object will never succeed. Note that classes are
callable (calling a class returns a new instance); class instances are callable if they have a
__call__() method.
chr(i)
Return a string of one character whose Unicode number is the integer i. For example, chr(97)
returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255],
inclusive; ValueError will be raised if i is outside that range. See also unichr().
classmethod(function)
Return a class method for function. A class method receives the class as implicit first argument,
just like an instance method receives the instance.
enumerate(sequence, start=0)
Return an enumerate object. sequence must be a sequence, an iterator, or some other
object which supports iteration. The next() method of the iterator returned by enumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained
from iterating over sequence:
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary
of the current module (inside a function or method, this is the module where it is defined, not
the module from which it is called).
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard types that are used to define the operations possible on them and the storage method for
each of them.
• Numbers
• String
• List
• Tuple
• Dictionary
21
© Nex-G Exuberant Solutions Pvt. Ltd.
Number
22
© Nex-G Exuberant Solutions Pvt. Ltd.
Number
Python's built-in core data types are in some cases also called object types. There are four built-
in data types for numbers:
Integer
• Normal integers
e.g. 4321
• Octal literals (base 8)
A number prefixed by a 0o (Zero small-o) will be interpreted as an octal number, example:
>>> a = 0o10
>>> print(a)
8
25
© Nex-G Exuberant Solutions Pvt. Ltd.
Number Type Conversion
26
© Nex-G Exuberant Solutions Pvt. Ltd.
Numeric Display Formats
1 / 2.0
0.5
>>> num = 1 / 3.0
>>> num # Echoes
0.33333333333333331
>>> print(num) # print rounds
0.333333333333
>>> '%e' % num # String formatting expression
'3.333333e-001'
>>> '%4.2f' % num # Alternative floating-point format
'0.33'
>>> '{0:4.2f}'.format(num) # String formatting method (Python 2.6 and 3.0)
'0.33'
27
© Nex-G Exuberant Solutions Pvt. Ltd.
Bitwise Operations
Besides the normal numeric operations (addition, subtraction, and so on), Python supports
most of the numeric expressions available in the C language.\
This includes operators that treat integers as strings of binary bits. For instance, here it is
at work performing bitwise shift and Boolean operations
>>> x = 1 # 0001
>>> x << 2 # Shift left 2 bits: 0100
4
>>> x | 2 # Bitwise OR: 0011
3
>>> x & 1 # Bitwise AND: 0001
1
28
© Nex-G Exuberant Solutions Pvt. Ltd.
Division: Classic, Floor
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 / 4.0
2.5
>>> 10 // 4.0
2.0
29
© Nex-G Exuberant Solutions Pvt. Ltd.
Other Built-in Numeric Tools
• In addition to its core object types, Python also provides both built-in functions and
standard library modules for numeric processing.
import math
(3.1415926535897931, 2.7182818284590451)
0.034899496702500969
(12.0, 1.4142135623730951)
(16, 16)
(42.0, 10)
(1, 4)
30
© Nex-G Exuberant Solutions Pvt. Ltd.
Strings
Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus ( + ) sign is the string concatenation operator and the asterisk ( * ) is the
repetition operator. For example:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Immutable Strings
Like strings in Java and unlike C or C++, Python strings cannot be changed. Trying to
change an indexed position will raise an error:
>>> s = "Some things are immutable!"
>>> s[-1] = "."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
However what you can do is this:
>>> s = s[:-1] + ‘.’
As sequences, strings support operations that assume a positional ordering among items.
For example, if we have a four-character string, we can verify its length with the built-in len
function and fetch its components with indexing expressions:
>>> S = 'Spam'
'S'
'p'
34
© Nex-G Exuberant Solutions Pvt. Ltd.
Immutability
Every string operation is defined to produce a new string as its result, because strings are
immutable in Python—they cannot be changed in-place after they are created. For
example, you can’t change a string by assigning to one of its positions, but you can always
build a new one and assign it to the same name.
>>> S
'Spam'
>>> S = 'z' + S[1:] # But we can run expressions to make new objects
>>> S
'zpam'
35
© Nex-G Exuberant Solutions Pvt. Ltd.
Accessing Values in Strings
• Python does not support a character type; these are treated as strings of length one,
thus also considered a substring.
• To access substrings, use the square brackets for slicing along with the index or indices
to obtain your substring. For example −
Output:
var1[0]: H
var2[1:5]: ytho
36
© Nex-G Exuberant Solutions Pvt. Ltd.
Updating Strings
• You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string
altogether. For example −
37
© Nex-G Exuberant Solutions Pvt. Ltd.
Common string literals and operations
1) capitalize(): It returns a copy of the string with only its first character capitalized.
Example:
>>> str = "this is string example....wow!!!"
>>> print(str.capitalize())
This is string example....wow!!!
2) center(width, fillchar): The method center() returns centered in a string of length width.
Padding is done using the specified fill-char. Default filler is a space. In example below '18', '10' is
width and '*', '#' is fill-char.
Example:
>>> x = "Hello..."
>>> x.center(18, '*')
'*****Hello...*****'
>>> x.center(10, '#')
'#Hello...#'
39
© Nex-G Exuberant Solutions Pvt. Ltd.
3) count() : The method count() returns the number of occurrences of substring in the range
start & end.
Example:
>>> x = "Hello...Hi"
>>> x.count('H', 0, 12)
2
>>> x.count('He', 0, 12)
1
>>> x.count('H')
2
4) encoding(): The method encode() returns an encoded version of the string. Default
encoding is the current default string encoding.
Example:
>>> x = "Hello..."
>>> x.encode('base64')
'SGVsbG8uLi4=\n'
5) decoding() : The method decode() decodes the string using the codec registered for
encoding. It defaults to the default string encoding.
Example:
>>> x = "Hello..."
>>> x = x.encode('base64')
>>> x.decode('base64')
'Hello...'
6) endswith() : The method endswith() returns True if the string ends with the specified
suffix, otherwise return False optionally restricting the matching with the given range start
& end.
Example:
>>> x = "Hello"
>>> x.endswith('o')
True
>>> x.endswith('j')
False
41
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
7) expandtabs() : The method expandtabs() returns a copy of the string in which tab
characters i.e. '\t‘ have been expanded using spaces, optionally using the given tabsize
(default 8).
Example:
>>> x = "Hello,\tHow are you"
>>> print(x)
Hello, How are you
>>> x.expandtabs(10)
'Hello, How are you'
42
© Nex-G Exuberant Solutions Pvt. Ltd.
8) find() : The method find() determines if string str occurs in string, or in a
substring of string, if starting index and ending index end are given will
determines string in given range. This method returns index if found and -1
otherwise.
Example:
>>> x = "Hello, How are you"
>>> x.find('o')
4
>>> x.find('o', 7, 10)
8
>>> x.find('how')
-1
>>> x.find('How')
7
Example:
>>> x = "Hello, How are you"
>>> x.index('h')
10) isalnum(): The method isalnum() checks whether the string consists of alphanumeric
characters. This method returns true if all characters in the string are alphanumeric and there
is at least one character, false otherwise.
Example:
>>> x = "Hello"
>>> x.isalnum()
True
>>> x = "Hello5"
>>> x.isalnum()
True
>>> x = "Hello 5"
>>> x.isalnum()
False
45
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
11) isalpha() : The method isalpha() checks whether the string consists of alphabetic
characters only. This method returns true if all characters in the string are alphabetic and
there is at least one character, false otherwise.
Example:
>>> x = "Hello !!!"
>>> x.isalpha()
False
>>> x = "Hello"
>>> x.isalpha()
True
>>> x = "Hello54"
>>> x.isalpha()
False
46
© Nex-G Exuberant Solutions Pvt. Ltd.
12) isdigit() : The method isdigit() checks whether the string consists of digits only. This
method returns true if all characters in the string are digits and there is at least one
character, otherwise.
Example:
>>> x = "Hello"
>>> x.isdigit()
False
>>> x = "443"
>>> x.isdigit()
True
>>> x = "Hello 43"
>>> x.isdigit()
False
13) islower() : The method islower() checks whether all the case-based characters (letters) of
the string are lowercase. This method returns true if all cased characters in the string are
lowercase and there is at least one cased character, false otherwise.
Example:
>>> x = "Hello"
>>> x.islower()
False
>>> x = "hello"
>>> x.islower()
True
>>> x = "hello How are you ?"
>>> x.islower()
False
>>> x = "hello how are you ?"
>>> x.islower()
True
48
© Nex-G Exuberant Solutions Pvt. Ltd.
14) isspace() : The method isspace() checks whether the string consists of whitespace.
This method returns true if there are only whitespace characters in the string and there is at
least one character, false otherwise.
Example:
>>> x = "Hello Hi"
>>> x.isspace()
False
>>> x = " "
>>> x.isspace()
True
15) istitle() : The method istitle() checks whether all the case-based characters in the string
following non-casebased letters are uppercase and all other case-based characters are
lowercase.
This method returns true if the string is a titlecased string and there is at least one character,
for example uppercase characters may only follow uncased characters and
lowercase characters only cased ones.It returns false otherwise.
Example:
>>> x = "Hello, How Are You ?"
>>> x.istitle()
True
>>> x = "Hello, How are you ?"
>>> x.istitle()
False
50
© Nex-G Exuberant Solutions Pvt. Ltd.
16) isupper() : The method isupper() checks whether all the characters (letters) of the string
are uppercase. This method returns true if all cased characters in the string are uppercase
and there is at least one cased character, false otherwise.
Example:
>>> x = "HELLO, HOW ARE YOU ?"
>>> x.isupper()
True
>>> x = "HELLO, How Are You ?"
>>> x.isupper()
False
17) join() : The method join() returns a string. Which is the concatenation of the strings.
Example:
>>> x = "Hello World"
>>> y = ","
>>> y.join(x)
'H,e,l,l,o, ,W,o,r,l,d'
>>> x = "abcdef"
>>> y = "-"
>>> y.join(x)
'a-b-c-d-e-f'
18) len() : The method len() returns the length of the string.
Example:
>>> x = "HELLO, How Are You ?"
>>> len(x)
20
>>> x = "abcdef"
>>> len(x)
6
52
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
19) ljust() : This method returns the string left justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned if width is
less than len(s).
Example:
>>> x = "HELLO, How Are You ?"
>>> x.ljust(50, 'D')
'HELLO, How Are You ?DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD'
>>> x.ljust(10, 'D')
'HELLO, How Are You ?'
20) lower() : This method returns a copy of the string in which all characters have been
lowercased.
Example:
>>> x = "HELLO, HOW ARE YOU ?"
>>> x.lower()
'hello, how are you ?'
53
© Nex-G Exuberant Solutions Pvt. Ltd.
21) lstrip() : This method returns a copy of the string in which all chars have been stripped
from the beginning of the string (default whitespace characters).
Example:
22) partition() : Search for the separator sep in S, and return the part before it, the separator
itself, and the part after it. If the separator is not found, return S and two empty strings.
Example:
>>> x = "HELLO, HOW ARE YOU ?"
>>> x.partition(',')
('HELLO', ',', ' HOW ARE YOU ?')
>>> x.partition('?')
('HELLO, HOW ARE YOU ', '?', '')
>>> x.partition('#')
('HELLO, HOW ARE YOU ?', '', '')
23) replace() : The method replace() returns a copy of the string in which the occurrences of
old have been replaced with new, optionally restricting the number of replacements to
max.
Example:
>>> x = "Where are you?, Where is your Friend?"
>>> x.replace("Where", "How")
'How are you?, How is your Friend?'
>>> x.replace("Where", "How", 1)
'How are you?, Where is your Friend?'
55
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
24) rfind() : The method rfind() returns the last index where the substring str is found, or -1 if
no such index exists.
Example:
>>> x = "HELLO, HOW ARE YOU ?"
>>> x.rfind('you')
-1
>>> x.rfind('YOU')
15
>>> x.rfind('Y')
15
>>> x.rfind('A')
11
>>> x.rfind('A', 1, 7)
-1
56
© Nex-G Exuberant Solutions Pvt. Ltd.
25) rindex() : The method rindex() returns the last index where the substring str is found or
raises an exception if no such index exists.
Example:
26) rjust() : The method rjust() returns the string right justified in a string of length width.
Padding is done using the specified fillchar (default is a space). The original string is
returned if width is less than len(s).
Example:
>>> x = "HELLO, HOW ARE YOU ?"
>>> x.rjust(20, '*’)
'HELLO, HOW ARE YOU ?'
>>> x.rjust(30, '*')
'**********HELLO, HOW ARE YOU ?'
27) rstrip() : The method rstrip() returns a copy of the string in which all chars have been
stripped from the end of the string (default whitespace characters).
Example:
>>> x = "*** HELLO, HOW ARE YOU ? ***"
>>> x.rstrip('*')
'*** HELLO, HOW ARE YOU ? '
58
© Nex-G Exuberant Solutions Pvt. Ltd.
28) split() : The method split() returns a list of all the words in the string, using str as the
separator (splits on all whitespace if left unspecified), optionally limiting the number of
splits to num.
Example:
>>> x = "Where are you?, Where is your Friend?"
>>> x.split()
['Where', 'are', 'you?,', 'Where', 'is', 'your', 'Friend?']
>>> x.split(',')
['Where are you?', ' Where is your Friend?']
>>> x.split('Where')
['', ' are you?, ', ' is your Friend?']
29) splitlines() : The method splitlines() returns a list with all the lines in string, optionally
including the line breaks (if num is supplied and is true).
Example:
>>> x = "Hello\nHow are you?\nWhere i your friend?"
>>> x.splitlines()
['Hello', 'How are you?', 'Where i your friend?']
30) startswith() : The method startswith() checks whether string starts with str, optionally
restricting the matching with the given range start & end.
Example:
>>> x = "Where are you?, Where is your Friend?"
>>> x.startswith('Where')
True
>>> x.startswith('where')
False
>>> x.startswith('are')
False
60
© Nex-G Exuberant Solutions Pvt. Ltd.
31) strip() : The method strip() returns a copy of the string in which all chars have
been stripped from the beginning and the end of the string (default whitespace
characters).
Example:
>>> x = "*****Where are you?, Where is your Friend?******"
>>> x.strip('*')
'Where are you?, Where is your Friend?
32) swapcase() : The method swapcase() returns a copy of the string in which all the
characters have had their case swapped.
Example:
>>> x = "where are you?, where is your friend?"
>>> x.swapcase()
'WHERE ARE YOU?, WHERE IS YOUR FRIEND?'
>>> x = "HELLO WORLD...!!!"
>>> x.swapcase()
'hello world...!!!'
33) title() : The method title() returns a copy of the string in which first characters of all the
words are capitalized.
Example:
>>> x = "hello world...!!!"
>>> x.title()
'Hello World...!!!'
62
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
34) translate() : The method translate() returns a copy of the string in which all characters have
been translated using table (constructed with the maketrans() function in the string
module), optionally deleting all characters found in the string.
Example:
>>> from string import maketrans
>>> x = "where are you?, where is your friend?"
>>> a = "waifd"
>>> b = "*****"
>>> c = maketrans(a, b)
>>> x.translate(c)
'*here *re you?, *here *s your *r*en*?'
>>> x.translate(c, 'h')
'*ere *re you?, *ere *s your *r*en*?
35) upper() : The method upper() returns a copy of the string in which all characters have
been uppercased.
Example:
>>> x = "where are you?, where is your friend?"
>>> x.upper()
'WHERE ARE YOU?, WHERE IS YOUR FRIEND?'
63
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions.......
36) zfill() : The method zfill() pads string on the left with zeros to fill width.
Example:
>>> x = "where are you?, where is your friend?"
>>> x.zfill(30)
'where are you?, where is your friend?'
>>> x.zfill(40)
'000where are you?, where is your friend?'
>>> x.zfill(50)
'0000000000000where are you?, where is your friend?'
64
© Nex-G Exuberant Solutions Pvt. Ltd.
Pattern Matching
Example:
import re
>>> match = re.match('Hello[ \t]*(.*)world', 'Hello Python world')
>>> match.group(1)
'Python’
•The following pattern, for example, picks out three groups separated by slashes:
65
© Nex-G Exuberant Solutions Pvt. Ltd.
Escape Sequences Represent Special Bytes
Backslashes are used to introduce special byte codings known as escape sequences.
• The character \, and one or more characters following it in the string literal, are replaced
with a single character in the resulting string object.
• example, here is a five-character string that embeds a newline and a tab:
>>> s = 'a\nb\tc’
• The interactive echo shows the special characters as escapes, but print interprets them
instead:
>>> s
'a\nb\tc'
>>> print(s)
a
bc
66
© Nex-G Exuberant Solutions Pvt. Ltd.
Raw Strings Suppress Escapes
Raw strings don't treat the backslash as a special character at all. Every character you put
into a raw string stays , the way you wrote it:
print('C:\\nowhere’)
When the above code is executed, it produces the following result:
C:\nowhere
If you don’t want characters prefaced by \ to be interpreted as special characters, you can
use raw strings by adding an r before the first quote:
>>> print('C:\some\name’) # here \n means newline!
C:\some
ame
>>> print(r’C:\some\name’) # note the r before the quote
C:\some\name
67
© Nex-G Exuberant Solutions Pvt. Ltd.
String Conversion Tools
>>> "42" + 1
TypeError: cannot concatenate 'str' and 'int' objects
you need to employ conversion tools before you can treat a string like a number, or vice
versa. For instance:
>>> int("42"), str(42) # Convert from/to string
(42, '42')
>>> repr(42) # Convert to as-code string
'42‘
Now, although you can’t mix strings and number types around operators such as +, you
can manually convert operands before that operation if needed:
>>> S = "42"
>>> I = 1
>>> S + I
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(S) + I # Force addition
43
68
© Nex-G Exuberant Solutions Pvt. Ltd.
Lists
• Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([ ]). To some extent, lists
are similar to arrays in C.
• One difference between them is that all the items belonging to a list can be of
different data type.
• The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition
operator. For example:
A tuple consists of a number of values separated by commas. Unlike lists, however, tuples
are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example:
Following is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists:
A dictionary key can be almost any Python type, but are usually numbers or strings. Values,
on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed
using square braces ( [] ).
For example:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
75
© Nex-G Exuberant Solutions Pvt. Ltd.
Python Basic Operators
76
© Nex-G Exuberant Solutions Pvt. Ltd.
Arithmetic Operation
Addition (+) - Adds values on either side of the operator a + b will give 30
Subtraction(-) - Subtracts right hand operand from left hand operand a - b will give -10
Multiplication(*) - Multiplies values on either side of the operator a * b will give 200
Division(/) - Divides left hand operand by right hand operand b / a will give 2
Modulus (%) - Divides left hand operand by right hand operand and returns remainder
Floor Division(//) - The division of operands where the result is the quotient in which the
digits after the decimal point are removed.
77
© Nex-G Exuberant Solutions Pvt. Ltd.
== Checks if the value of two operands is equal or not, if yes then condition becomes true.
(a=b is not true)
!=Checks if the value of two operands is equal or not, if values are not equal then condition
becomes true. (a != b) is true.
<> Checks if the value of two operands is equal or not, if values are not equal then condition
becomes true. (a <> b) is true. This is similar to != operator.
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if
yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true. (a <= b) is true.
78
© Nex-G Exuberant Solutions Pvt. Ltd.
Python Assignment Operators:
= Simple assignment operator, Assigns values from right side operands to left side
operand c = a + b will assign value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and assigns
the result to left operand c += a is equivalent to c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand
and assigns the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand
and assigns the result to left operand c *= a is equivalent to c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and
assigns the result to left operand c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and
assigns the result to left operand c %= a is equivalent to c = c % a
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20, then:
and- Called Logical AND operator. If both the operands are true, then the condition
becomes true. (a and b) is true.
or- Called Logical OR Operator. If any of the two operands are nonzero, then the
condition becomes true. (a or b) is true.
not- Called Logical NOT Operator. Used to reverse the logical state of its operand. If a
condition is true, then Logical NOT operator will make it false. not(a and b) is false
80
© Nex-G Exuberant Solutions Pvt. Ltd.