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

Module 3

The document explains the concept of variables in Python, including their definition, assignment, data types, and scope. It also covers Python identifiers, reserved keywords, built-in functions, and various data types such as numbers, strings, lists, and dictionaries. Additionally, it discusses comments, indentation, and multi-line statements in Python programming.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 3

The document explains the concept of variables in Python, including their definition, assignment, data types, and scope. It also covers Python identifiers, reserved keywords, built-in functions, and various data types such as numbers, strings, lists, and dictionaries. Additionally, it discusses comments, indentation, and multi-line statements in Python programming.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Using variables

What are Variables?

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

Assigning Values to 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.

© Nex-G Exuberant Solutions Pvt. Ltd.


• For example:

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print(counter)
print(miles)
print(name)

© Nex-G Exuberant Solutions Pvt. Ltd.


Variables and Datatypes

• Variables in Python follow the standard nomenclature of an alphanumeric name


beginning in a letter or underscore. Variable names are case sensitive. Variables do not
need to be declared and their datatypes are inferred from the assignment statement.
Python supports the following data types:
– boolean
– integer
– long
– float
– string
– list
– object
– None
Use the type function to see type of a variable.
For example:
>>>type(int)
output: <class 'NoneType'>

© Nex-G Exuberant Solutions Pvt. Ltd.


Scope of variable

• 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

© Nex-G Exuberant Solutions Pvt. Ltd.


Statements and Expressions

Some basic Python statements include:


• print: Output strings, integers, or any other datatype.

• The assignment statement: Assigns a value to a variable.

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Python Identifiers

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

Here are following identifier naming convention for Python:


• Class names start with an uppercase letter and all other identifiers with a lowercase letter.
• Starting an identifier with a single leading underscore indicates by convention that the
identifier is meant to be Private.
• Starting an identifier with two leading underscores indicates a strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.

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.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

7
© Nex-G Exuberant Solutions Pvt. Ltd.
Python expressions can include:

a = b = 5 #The assignment statement


b += 1 #post-increment
c = "test"
import os,math #Import the os and math modules
from math import * #Imports all functions from the math module

© Nex-G Exuberant Solutions Pvt. Ltd.


Multiple Assignment

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Lines and Indentation:

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"

However, the second block in this example will generate an error:

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:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Comments in Python

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

print "Hello, Python!"; # second comment

This will produce the following result:


Hello, Python!

A comment may be on the same line after a statement or expression:

Using Blank Lines:

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Built-in Functions

The Python interpreter has a number of functions built into it that are always available.

© Nex-G Exuberant Solutions Pvt. Ltd.


Built-in Functions
abs(x)

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.

© Nex-G Exuberant Solutions Pvt. Ltd.


Built-in Functions

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.

© Nex-G Exuberant Solutions Pvt. Ltd.


Built-in Functions
cmp(x, y)
Compare the two objects x and y and return an integer according to the outcome. The return
value is negative if x < y, zero if x == y and strictly positive if x > y.

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:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']


>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield(n, elem)
n += 1

© Nex-G Exuberant Solutions Pvt. Ltd.


Built-in Functions

getattr(object, name[, default])


Return the value of the named attribute of object. name must be a string. If the string is the
name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is
returned if provided, otherwise AttributeError is raised.

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Data Types

Standard Data Types:

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.

Python has five standard data types:

• Numbers
• String
• List
• Tuple
• Dictionary

21
© Nex-G Exuberant Solutions Pvt. Ltd.
Number

Python supports four different numerical types:


• int (signed integers)
• float (floating point real values)
• complex (complex numbers)

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

© Nex-G Exuberant Solutions Pvt. Ltd.


Number

Hexadecimal literals (base 16)


Hexadecimal literals have to be prefixed either by "0x" or "0X".
example:
>>> hex_number = 0xA0F
>>> print(hex_number) O/P : 2575
Floating-point numbers for example: 42.11, 3.1415e-10
Complex numbers
Complex numbers are written as <real part> + <imaginary part>j, examples:
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print(z)
(5+1j)

© Nex-G Exuberant Solutions Pvt. Ltd.


Numerical types

Python supports three different numerical types −


• int (signed integers): They are often called just integers or ints, are positive or negative
whole numbers with no decimal point.
• float (floating point real values) : Also called floats, they represent real numbers and
are written with a decimal point dividing the integer and fractional parts. Floats may also
be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10 2 = 250).
• complex (complex numbers) : are of the form a + bJ, where a and b are floats and J
(or j) represents the square root of -1 (which is an imaginary number). The real part of
the number is a, and the imaginary part is b. Complex numbers are not used much in
Python programming.

25
© Nex-G Exuberant Solutions Pvt. Ltd.
Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common


type for evaluation. But sometimes, you need to coerce a number explicitly from one type
to another to satisfy the requirements of an operator or function parameter.
• Type int(x) to convert x to a plain integer.
• Type float(x) to convert x to a floating-point number.
• Type complex(x) to convert x to a complex number with real part x and imaginary part
zero.
• Type complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions

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

• X / Y - Classic and true division


• X // Y - Floor division

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

>>> math.pi, math.e # Common constants

(3.1415926535897931, 2.7182818284590451)

>>> math.sin(2 * math.pi / 180) # Sine, tangent, cosine

0.034899496702500969

>>> math.sqrt(144), math.sqrt(2) # Square root

(12.0, 1.4142135623730951)

>>> pow(2, 4), 2 ** 4 # Exponentiation (power)

(16, 16)

>>> abs(-42.0), sum((1, 2, 3, 4)) # Absolute value, summation

(42.0, 10)

>>> min(3, 1, 2, 4), max(3, 1, 2, 4) # Minimum, maximum

(1, 4)
30
© Nex-G Exuberant Solutions Pvt. Ltd.
Strings

Strings in Python are identified as a contiguous set of characters in between quotation


marks. Python allows for either pairs of single or double quotes.

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:

str = 'Hello World!'


print(str) #Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST“) # Prints concatenated string

© Nex-G Exuberant Solutions Pvt. Ltd.


Strings

This will produce the following result:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

© Nex-G Exuberant Solutions Pvt. Ltd.


Strings

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] + ‘.’

© Nex-G Exuberant Solutions Pvt. Ltd.


Strings

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'

>>> len(S) # Length

>>> S[0] # The first item in S, indexing by zero-based position

'S'

>>> S[1] # The second item from the left

'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[0] = 'z' # Immutable objects cannot be changed

...error text omitted...

TypeError: 'str' object does not support item assignment

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

var1 = 'Hello World!'


var2 = "Python Programming"

print("var1[0]: ", var1[0])


print("var2[1:5]: ", var2[1:5])

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 −

var1 = 'Hello World!'


print("Updated String :- ", var1[:6] + 'Python’)

When the above code is executed, it produces the following result −

Updated String :- Hello Python

37
© Nex-G Exuberant Solutions Pvt. Ltd.
Common string literals and operations

• S = "" Empty string


• S = "spam's" Double quotes, same as
single
• S = 's\np\ta\x00m' Escape sequences
• S = """...""" Triple-quoted
block strings
• S = r'\temp\spam' Raw strings
• S1 + S2 Concatenate
• S*3 repeat
• S.find('pa') String method
calls: search,
• S.rstrip() remove whitespace
• S.replace('pa', 'xx') replacement,
• S.split(',') split on delimiter
• S.lower() case conversion
• S.endswith('') end test
38
© Nex-G Exuberant Solutions Pvt. Ltd.
String Built-in Functions

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'

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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

© Nex-G Exuberant Solutions Pvt. Ltd.


9) index() : This method is same as find(), but raises an exception if sub is not found. This
method returns index if found otherwise raises an exception if str is not found.

Example:
>>> x = "Hello, How are you"
>>> x.index('h')

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> x.index('H')
0
>>> x.index('How')
7

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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:

>>> x = " HELLO, HOW ARE YOU ?"


>>> x.lstrip()
'HELLO, HOW ARE YOU ?'
>>> x = "XXXXXXXXXXXXXXHELLO, HOW ARE YOU ?"
>>> x.lstrip('X')
'HELLO, HOW ARE YOU ?'
>>> x = "XXXXXXXXXXXXXXHELLO, HOW ARE YOU ?XXXX"
>>> x.lstrip('X')
'HELLO, HOW ARE YOU ?XXXX'

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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:

>>> x = "HELLO, HOW ARE YOU ?"


>>> x.rindex('ARE')
11
>>> x.rindex('YOU')
15
>>> x.rindex('Are')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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?']

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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?

© Nex-G Exuberant Solutions Pvt. Ltd.


String Built-in Functions.......

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

In python for pattern matching, we import a module called re.

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:

>>> match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack')


>>> match.groups()
('usr', 'home', 'lumberjack')

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:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists

© Nex-G Exuberant Solutions Pvt. Ltd.


This will produce the following result:

['abcd', 786, 2.23, 'john', 70.200000000000003]


abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

© Nex-G Exuberant Solutions Pvt. Ltd.


Tuples

A tuple is another sequence data type that is similar to the list.

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:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

© Nex-G Exuberant Solutions Pvt. Ltd.


This will produce the following result:
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

Following is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

© Nex-G Exuberant Solutions Pvt. Ltd.


Dictionaries

Python's dictionaries are kind of hash table type.

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'}

print(dict['one’) # Prints value for 'one' key


print(dict[2])) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values

© Nex-G Exuberant Solutions Pvt. Ltd.


This will produce the following result:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Data Type Conversion:

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.

© Nex-G Exuberant Solutions Pvt. Ltd.


int(x [,base]) Converts x to an integer. base specifies the base if x is a
string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a
string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value)
tuples.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

75
© Nex-G Exuberant Solutions Pvt. Ltd.
Python Basic Operators

Python language supports the following types of operators.


• Arithmetic Operators
• Comparison (i.e., Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

76
© Nex-G Exuberant Solutions Pvt. Ltd.
Arithmetic Operation

Assume variable a holds 10 and variable b holds 20, then:

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

Exponent (** )- Performs exponential (power) calculation on operators

Floor Division(//) - The division of operands where the result is the quotient in which the
digits after the decimal point are removed.

9//2 is equal to 4 and


9.0//2.0 is equal to 4.0

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:

Assume variable a holds 10 and variable b holds 20, then:

= 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

**= Exponent AND assignment operator, Performs exponential (power) calculation on


operators and assigns value to the left operand c **= a is equivalent to c = c ** a
79
© Nex-G Exuberant Solutions Pvt. Ltd.
Python Logical Operators:

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.

You might also like