0% found this document useful (0 votes)
28 views133 pages

UNIT-I by Chiru Sai

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views133 pages

UNIT-I by Chiru Sai

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 133

UNIT-I

Python Basics
Definition

Python is a high-level, interpreted, interactive


and object-oriented scripting language.

It has fewer syntactic constructions than other languages.


contd..

Python is Interpreted: Python is processed at runtime by the


interpreter. No need to compile your program before executing it. This
is similar to PERL and PHP.

Python is Interactive: You can actually sit at a Python prompt and


interact with the interpreter directly to write your programs.
contd..

Python is Object-Oriented: Python supports Object-Oriented style or


technique of programming by bundling related properties and
behaviors into individual objects

Python is a Beginner's Language: Python is a great language for the


beginner-level programmers and supports the development of a wide
range of applications from simple text processing to W W W browsers
to games.
History of Python

Python was developed by Guido van


Rossum in the late eighties and early nineties
of 19th century at the National Research
Institute for Mathematics and Computer
Science in Netherlands
contd..
● Python is derived from many other languages, including ABC,
Modula-3, C, C++, ALGOL-68, SmallTalk, UNIX Shell, and
other Scripting languages.
● At the time when he began implementing Python, Guido van
Rossum was also reading the published scripts from
"Monty Python's Flying Circus" (a BBC comedy series, in the
seventies).
● He needed a name that was short, unique, and slightly
mysterious, so, decided to call the language as Python.
Stable Version
Python 3.8.5 - July 20,
2020

https://www.python.org
/
Python Features

● Easy-to-learn: Python has few keywords, simple structure, and a


clearly defined syntax. This allows the student to pick up the
language quickly.
● Easy-to-read: Python code is more clearly defined and visible to
the eyes.
● Easy-to-maintain: Python's source code is fairly easy-to-
maintain.
● A broad standard library: Python's bulk of the library is very
portable and cross- platform compatible on UNIX, Windows, and
contd..

● Interactive Mode: Python has support for an interactive mode


which allows interactive testing and debugging of
snippets of code.
● Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
● Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more effcient.
contd..

● Databases: Python provides interfaces to all major commercial


databases.
● GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of UNIX.
● Scalable: Python provides a better structure and support for large
programs than shell scripting.
Who Uses Python Today?
Python Bytecode
● Python uses code modules that are interchangeable instead of a
single long list of instructions
● Python doesn’t convert its code into machine code, something that
hardware can understand.
● It actually converts it into something called bytecode.
● So within python, compilation happens, but it’s just not into a
machine language
contd..

● It is into bytecode and this bytecode can’t be understood by


CPU.
● So we need an interpreter called the Python Virtual Machine.
● The P VM executes the bytecode.
How the Python Interpreter Works?
Python Indentation

● Indentation refers to the spaces at the beginning of a code line.


● Where in other programming languages the indentation in code
is for readability only, the indentation in Python is very important.
● Python uses indentation to indicate a block of code.
● Python will give you an error if you skip the indentation.
Python Comments
● Comments can be used to make the code more readable.
● Comments starts with a #, and Python will ignore them
● Python does not really have a syntax for multi line comments, to
add a multiline comment you could insert # for each
a can add a multiline string (triple quotes) inline.
● You your code, and
place your comment inside it.

‘‘‘
--------------------------
--------------------------
’’’
Python Variables

● Variables are containers for storing data values.


● Unlike other programming languages, Python has no command for
declaring a variable.
● A variable is created the moment you first assign a value to it.

Example:

x = 10

y = "cse"
contd..
● Python allows you to assign values to multiple variables in one
line:

x, y, z = "Orange", "Banana", "Apple"

● You can assign the same value to multiple variables in one

line: x = y = z = "Orange"

● Variables that are created outside of a function are known as


global variables.
contd..
● If you create a variable with the same name inside a function,
this variable will be local, and can only be used inside the
function.
● The global variable with the same name will remain as it
● was,can
You global andawith
create thevariable
global original inside
value.a function using global
keyword.
Python Keywords
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


Program Output

● The print statement is used to display output to the screen

print ("Welcome to Python Programming")

● The print statement, paired with the string format operator


( % ), behaves even more like C's printf() function:

print ("%s Programming is number %d" % ("Python", 1))


Program Input
● input() function is used to take values from the user.

user = input(“Enter User name: “)

● The type of the value stored is always a string.


● string type is converted to an integer type using int() function

user = int(user)
Python Operators

Arithmetic Comparison Logical Assignment

Identity Membership Bitwise


Arithmetic Operators
Operator Operator Name

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Division

// Floor Division

** Exponentiation
Comparison Operators
Operator Operator Name

< Less than

<= Less than or Equal to

> Greater than

>= Greater than or Equal to

== Equal to

!= Not Equal to
Logical Operators
Logical operators are used to combine comparison statements

Operator Description

and If both the operands are true then only true

or If any one of the two operands is true then


is true

not Used to reverse the logical state of


its operand
Assignment Operators

Assignment operators are used to assign values to variables:

Operator Operator Name

= Is Equal to

+= Plus Equals

-=, /=, %=, s=, ^=, etc., Shorthand Assignment


Identity Operators

Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location

Operator Description

is Returns True if both variables are the same


object

is not Returns True if both variables are not the same


object
Membership Operators

Membership operators are used to test if a sequence is presented in


an object

Operator Description

in Returns True if a sequence with the specified


value is present in the object

not in Returns True if a sequence with the specified


value is not present in the object
Bitwise Operators
Operator Operator Name

s AND

| OR

^ XOR

~ NOT

<< Shift Left

>> Shift Right


if Statement

The standard if conditional statement follows this syntax:

if expression:

if_suite
if-else Statement

Python supports an else statement that is used with if in the following


manner:

if expression:

if_suite

else:

else_suite
else-if Statement

Python has an "else-if" statement named elif which has the following
syntax:
if expression1:
if_suite
elif expression2:
elif_suite Surprise: There is no switch
else: or case statement in
Python.
else_suite
while Loop

The standard while conditional loop statement follows this syntax:

while expression:

while_suite

Surprise: There is no do-


while loop in Python.
for Loop
● A traditional for conditional loop that works like a counter in
other Programming Languages
● The for loop in Python is more like a foreach iterative-type loop
● Python's for loop takes what we will later describe as a
sequence type (list, tuple, or string) and iterates over each
element of that sequence.
● Syntax:

for iterating_var in sequence:

for_suite
break Statement
● The break statement in Python terminates the current loop and
resumes execution at the next statement, just like the
traditional break found in C.
● The most common use for break is when some external
condition is triggered (usually by testing with an if statement),
requiring a hasty exit from a loop.
● The break statement can be used in both while and for loops.
continue Statement
● The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the
top of the loop.
● The while loop is conditional, the conditional expression is
checked for validity before beginning the next iteration of the
loop
● The for loop is iterative, a determination must be made as
to whether there are any more arguments to iterate over
pass Statement

● One Python statement not found in C is the pass statement.


● Because Python does not use curly braces to delimit blocks
of code, there are places where code is syntactically required.
● If you use a Python statement that expects a sub-block of code
or suite, and one is not present, you will get a syntax error
condition.
● For this reason, we have pass, a statement that does absolutely
nothing, just to indicate "do nothing."
Python Objects

● Python uses the object model abstraction for data storage.


● Any construct which contains any type of value is an object.
● You can write a useful Python script without the use of classes and
instances.
contd..

● All Python objects have the following three characteristics:


○ an identity
○ a type
○ a value
contd..
Unique identifier that differentiates an object from all others. Any

IDENTITY object's identifier can be obtained using the id() built-in function.
This value is as close as you will get to a "memory address" in
Python.
An object's type indicates what kind of values an object can hold,
what operations can be applied to such objects, and what behavioral
TYPE
rules these objects are subject to. You can use the type() built-in
function to reveal the type of a Python object.

VALUE Data item that is represented by an object.


contd..

● All three are assigned on object creation and are read-only


with one exception, the value.
● If an object supports updates, its value can be changed; otherwise,
it is also read-only.
● Whether an object's value can be changed is known as an object's
mutability.
Standard Types

● Numbers (four separate sub-types)


○ Regular or "Plain" Integer
○ Long Integer
○ Floating Point Real Number
○ Complex Number
● String
● List
● Tuple
● Dictionary
NOTE
:
● All standard type objects can be tested for truth value and
compared to objects of the same type.
● Objects have inherent true or false values.
● Objects take a false value when they are empty, any numeric
representation of zero, or the Null object None.
contd..
● The following are defined as having false values in Python:

None Any numeric

zero: 0 ([plain] integer) 0.0 (float)

0L (long integer) 0.0+0.0j

(complex) " " (empty string) []

(empty list)
Other Built-in Types

● Type
● None
● File
● Function
● Module
● Class
● Class Instance
● Method
Types and type() built-in Function

● It may seem unusual perhaps, to call types themselves as


objects.
● However, if you keep in mind that an object's set of inherent
behaviors and characteristics, an object's type is a logical place for
this information.
● The amount of information necessary to describe a type cannot
fit into a single string; therefore types cannot simply be strings,
nor should this information be stored with the data, so we are
back to types as objects.
contd..

● The syntax of type() built-in function is:

type(object)

● The type() built-in function takes object and returns its type
object.
None

● Python has a special type known as the Null object.


● It has only one value, None.
● It does not have any operators or built-in functions.
● The None type is similar to C type void, while the None value
is similar to the C value of NULL.
Internal Types

● Code
● Frame
● Traceback
● Slice
● Ellipsis
● Xrange
Code Objects
● Code objects are executable pieces of Python source that are
byte-compiled, usually as return values from calling the compile()
built-in function.
● Such objects are appropriate for execution by either exec() or
by the eval() built-in function.
contd..

● Code objects themselves do not contain any information regarding


their execution environment, but they are at the heart of every
user-defined function, all of which do contain some execution
context.
● The actual byte-compiled code as a code object is one
attribute belonging to a function.
Frames

● These are objects representing execution stack frames in Python.


● Frame objects contain all the information the Python interpreter
needs to know during a runtime execution environment.
● Some of its attributes include a link to the previous stack frame,
the code object that is being executed, dictionaries for the
local and global namespaces, and the current instruction.
contd..

● Each function call results in a new frame object, and for


each frame object, a C stack frame is created as well.
● One place where you can access a frame object is in a
traceback object.
Tracebacks

● When you make an error in Python, an exception is raised.


● If exceptions are not caught or "handled," the interpreter exits
with some diagnostic information

Traceback (innermost last):

File "<stdin>", line N?,

in ??? ErrorName: error


contd..
● The traceback object is just a data item that holds the stack
trace information for an exception and is created when an
exception occurs.
● If a handler is provided for an exception, this handler is given
access to the traceback object.
Slice Objects
● Slice objects are created when using the Python extended slice
syntax.
● This extended syntax allows for different types of indexing.
● These various types of indexing include stride indexing,
multi-dimensional indexing, and indexing using the Ellipsis
type.
● The syntax for multi-dimensional indexing is:

sequence[start1 : end1, start2 : end2]


contd..
● The indexing using the ellipsis:

sequence[…, start1 : end1]

● Slice objects can also be generated by the slice() built-in function.


● Stride indexing for sequence types allows for a third slice element
that allows for "step" like access.

sequence[starting_index : ending_index : stride]


Ellipsis

● Ellipsis objects are used in extended slice notations.


● These objects are used to represent the actual ellipses in the slice
syntax (…).
● Like the Null object, ellipsis objects also have a single name,
Ellipsis, and has a Boolean true value at all times.
Xranges

● XRange objects are created by the built-in function xrange(), a


sibling of the range() built-in function.
● And used when memory is limited and for when range()
generates an unusually large data set.
Standard Type Operators

● Value Comparison
● Object Identity Comparison
● Boolean
Standard Type Built-in Functions
Python also provides some builtin functions that can be applied to all
the basic object types:

cmp()

repr()

str()

type()

back quotes ( '' ) operator, which is functionally equivalent to


Function Operation

cmp(obj1, obj2) compares obj1 and obj2, returns integer i


where: i < 0 if obj1 < obj2
i > 0 if obj1 > obj2
i == 0 if obj1 == obj2

repr(obj) / ' obj' returns evaluatable string representation of obj

str(obj) returns printable string representation of obj

type(obj) determines type of obj and return type object

repr() is Python-friendly while str() produces human friendly output


Categorizing the Standard Types
Python's standard types are called as "basic built-in data object
primitive types."

"Basic," indicating that these are the standard or core types that Python
provides

"Built-in," due to the fact that types these come default with Python.

"Data," because they are used for general data storage


contd...

"Object," because objects are the default abstraction for data


and functionality

"Primitive," because these types provide the lowest-level granularity of


data storage

"Types," because that's what they are: data types!


contd...

There are three different models we have come up with to


help categorize the standard types.

These models help us obtain a better understanding of how the types


are related, as well as how they work.

● Storage Model
● Update Model
● Access Model
Storage Model

● The first way we can categorize the types is by how many


objects can be stored in an object of this type.
● Python's types, can hold either single or multiple values.
● A type which holds a single object we will call literal or scalar
storage.
● A type which can hold multiple objects we will refer to as
container storage.
contd..

Storage model category Python types that fit category

literal/scalar numbers (all numeric types),


strings

container lists, tuples, dictionaries


Update Model
● Another way of categorizing the standard types is by asking the
question, "Once created, can objects be changed or their
values updated?"
● Mutable objects are those whose values can be changed,
● Immutable objects are those whose values cannot be changed.
contd...

Update model category Python types that fit category

mutable lists, dictionaries

immutable numbers, strings, tuples


Access Model

There are three categories under the access model:

● direct
● sequence
● Mapping
contd...

access model category types that fit category

direct numbers

sequence strings, lists, tuples

mapping dictionaries
Summary : Categorizing the Standard Types
Data Type Storage Model Update Model Access Model

numbers literal/scalar immutable direct

strings literal/scalar immutable sequence

lists container mutable sequence

tuples container immutable sequence

dictionaries container mutable mapping


Unsupported Types

The list of types that are not supported by Python


are:

● Boolean
● char or byte
● Pointer
● int vs. short vs. long
● float vs. double
Numbers
Introduction to Numbers
● Numbers provide literal or scalar storage and direct access.
● Numbers are also an immutable type, meaning that changing or
updating its value results in a newly allocated object.

How to Create and Assign Numbers (Number Objects)


anInt = 1
laLong = -9999999999999999L
aFloat = 3.1415926535897932384626433832795
aComplex = 1.23 + 4.56J
contd..
How to Update Numbers

● You can "update" an existing number by (re)assigning a variable to


another number.
● The new value can be related to its previous value or to
a completely different number altogether.

anInt = anInt + 1

aFloat =
contd..
How to Remove Numbers

● Under normal circumstances, you do not really "remove" a number;


you just stop using it!
● If you really want to delete a reference to a number object, just
use the del statement.
● You can no longer use the variable name, once removed, unless
you assign it to a new object; otherwise, you will cause a
NameError exception to occur.

del anInt del aLong, aFloat, aComplex


Integers

● Python has two types of integers.


● Plain integers are the generic vanilla (32-bit) integers recognized
on most systems today.
● Python also has a long integer size; however, these far exceed the
size provided by C longs.
contd..

(Plain) Integers

● Python's "plain" integers are the universal numeric type.


● Most machines (32-bit) running Python will provide a range of

-2^31 to 2^31-1, that is -2,147,483,648 to


2,147,483,647.

Integers in Python 3 are of unlimited size.


contd..
● Here are some examples of Python integers:

0101 84 -237 0x80 017 -680 -0X92

● Python integers are implemented as (signed) longs in C.


● Integers are normally represented in base 10 decimal format, but
they can also be specified in base eight or base sixteen
representation.
● Octal values have a "0" prefix, and hexadecimal values have either
"0x" or "0X" prefixes.
contd..
Long Integers (There is no 'long integer' in Python 3 anymore)

● The first thing we need to say about Python long integers is to not
get them confused with long integers in C or other compiled
languages.
● Python long integers are limited only by the amount of
(virtual) memory in your machine.
● In other words, they can be very L-O-N-G longs.
contd..

● Long integers are denoted by an upper- or lowercase (L) or


(l), appended to the integer's numeric value.
● Values can be expressed in decimal, octal, or hexadecimal.
● The following are examples of long integers:

16384L -0x4E8L 017L -2147483648l


052144364L

299792458l 0xDECADEDEADBEEFBADFEEDDEAL
contd..
Floating Point Real Numbers

● Floats in Python are implemented as C doubles, double precision


floating point real Numbers.
● Values which can be represented in straight forward decimal or
scientific notations.
● These 8-byte (64-bit) values conform to the IEEE 754
definition (52M/11E/1S)
contd..

Here are some floating point values:

0.0 -777. 1.6 -5.555567119 96e3 * 1.0


9.384e-23 -2.172818 float(12) 1.000000001
3.1416 4.2E-10 -90. 6.022e23 -1.609E-19
4.3e25
contd..

Complex Numbers

A long time ago, mathematicians were stumped by the following


equation:

The reason for this is because any


real number (positive or negative)
multiplied by itself results in a
positive number.
contd..

● How can you multiply any number with itself to get a


negative number? No such real number exists.
● So in the eighteenth century, mathematicians invented something
called an imaginary number j such that:
contd..
● Combining a real number with an imaginary number forms a
single entity known as a complex number.
● A complex number is any ordered pair of floating point real
numbers (x, y) denoted by x + y j where x is the real part and
y is the imaginary part of a complex number.
● Both real and imaginary components are floating point values.
contd..

● Imaginary part is suffxed with either lowercase ( j) or upper


(J)
● The following are examples of complex numbers:
64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j
6.23+1.5j -1.23-875J 0+1j 9.80665-8.31441J
-.0224+0j
contd..

Complex Number Built-in Attributes

attribute description

num. real real component of complex


number num

num. imag imaginary component of complex


number num

num. conjugate() returns complex conjugate of num


Numeric
coercion
Built-in Functions

Numeric Type Functions

Some convert from one numeric type to another while others are more
operational, performing some type of calculation.

Conversion

The int(), long(), float(), and complex() built-in functions are used
to convert from any numeric type to another.
contd..
Operational

Python has five operational built-in functions for numeric types:


abs(), coerce(), divmod(), pow(), and round().
function operation

abs( num ) returns the absolute value of num

coerce( num1, num2 ) converts num1 and num2 to the same numeric
type and returns the converted pair as a tuple
Not Available in Python 3
divmod( num1, num2 ) division-modulo combination returns (num1 /
num2, num1 % num2) as a tuple. For floats and
complex, the quotient is rounded down
(complex uses only real component of
quotient)

pow( num1, num2, mod =1) raises num1 to num2 power, quantity modulo
mod if provided

round( flt, ndig = 0) (floats only) takes a float flt and rounds it to


ndig digits, defaulting to zero if not provided
contd..
● int() chops off the decimal point and everything after
(a.k.a. truncation).
● floor() rounds you to the next smaller integer, i.e., the next
integer moving in a negative direction (towards the left on the
number line).
● round() (rounded zero digits) rounds you to the nearest integer
period.
contd..
Integer-only Functions

Python supports a few that are specific only to integers.

Base Representation

● Python integers automatically support octal and hexadecimal


representations in addition to the decimal standard.
● Python has two built-in functions which return string
representations of an integer's octal or hexadecimal equivalent.
contd..

function operation

hex( num ) converts num to hexadecimal and


return as string

oct( num ) converts num to octal and return as


string
contd..
ASCII Conversion

● Python also provides functions to go back and forth between ASCII


characters and their ordinal integer values.
● Each character is mapped to a unique number in a
table numbered from 0 to 255.
contd..
function operation

chr( num ) takes ASCII value num and returns


ASCII character as string; 0 <= num
<= 255 only

ord( chr ) takes ASCII chr and returns


corresponding ordinal ASCII value;
chr must be a string of length 1
Related Modules

● There are a number of modules in the Python standard library that


add-on to the functionality of the operators and built-in functions
for numeric types.
● For advanced numerical and scientific mathematics applications,
there is also a well known external module called NumPy which
may be of interest to you.
Numeric Type Related Modules contd..
module contents

array implements array types… a restricted sequence type

math/cmath supplies standard C library mathematical functions; most


functions available in math are implemented for complex
numbers in the cmath module

operator contains numeric operators available as function calls, i.e.,


operator.sub(m, n) is equivalent to the difference (m - n)
for numbers m and n

random is default RNG module for Python… obsoletes rand and


whrandom
Sequences: Strings, Lists, and Tuples
Sequences

The next family of Python types are those whose items are ordered
and sequentially accessible via index, known as sequences.

● Strings
● Lists
● Tuples
contd..
contd..
Sequence Operator Functionality

seq[ind] element located at index ind of seq

seq[ind1:ind2] elements from index ind1 to ind2 of seq

seq * expr seq repeated expr times

seq1 + seq2 concatenates sequences seq1 and seq2

obj in seq tests if obj is a member of sequence seq

obj not in seq tests if obj is not a member of sequence seq


contd..
Built-in Functions

Conversion

Function Operation

list (seq) converts seq to list

str (obj) converts obj to string

tuple (seq) converts seq to tuple


contd..
Operational

Function Operation
len (seq) returns length (number of items) of seq

max (seq) returns "largest" element in seq

min (seq) returns "smallest" element in seq


Strings

● Strings are amongst the most popular types in Python.


● We can create them simply by enclosing characters in quotes.
● Python treats single quotes the same as double quotes.

How to Create and Assign Strings

aString = 'Hello World!'

anotherString = "Python is cool!"


contd..
How to Access Values(Characters and Substrings) 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.

aString[0] aString[1:5] aString[6:]


contd..
How to Update 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.

aString = aString[:6] + 'Python!'


aString = 'different string altogether'
contd..
How to Remove Characters and Strings

● You cannot remove individual characters from an existing string.


● What you can do, however, is to empty the string, or to put
together another string which drops the pieces you were not
interested in.
Strings do not
aString = 'Hello World!' explicitly
need to bedeleted, are
automatically garbage
aString = aString[:3] + collected.
String-only Operators
Format Operator (%)

● One of Python's coolest features is the string format operator.


● This operator is unique to strings and makes up for the pack of
having functions from C's printf() family.
● The syntax for using the format operator is as follows:

format_string % (arguments_to_convert)
Format Operator Conversion Symbols
Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%d signed decimal integer

%o octal integer

%x or %X hexadecimal integer

%e or %E exponential notation

%f floating point real number

%g or %G the shorter of %f and %e or %E


Format Operator Auxiliary Directives

Symbol Functionality

- left justification

+ display the sign

# add the octal leading zero ( '0' ) or hexadecimal


leading '0x' or '0X', depending on whether 'x' or 'X' were
used.
0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'


String Built-in Methods

These methods are intended to replace most of the functionality in


the string module as well as to bring new functionality.

Method Description

capitalize() capitalizes first letter of string

center(width) returns a space-padded string with the


original string centered to a total of width
columns
count(str, beg= 0, counts how many times str occurs in string, or in
end=len(string)) a substring of string if starting
Method Description

endswith(str, beg=0, determines if string or a substring of string ends


end=len(string)) with str; returns 1 if so, and 0 otherwise

find(str, beg=0 end=len(string)) determine if str occurs in string, returns index


if found and -1 otherwise

index(str, beg=0, end=len(string)) same as find(), but raises an exception if str


not found

isalnum() returns 1 if string has at least 1 character and


all characters are alphanumeric and 0
otherwise
isalpha() returns 1 if string has at least 1 character and
all characters are alphabetic and 0 otherwise

isdecimal() returns 1 if string contains only decimal digits and


0 otherwise
Method Description

isdigit() returns 1 if string contains only digits and


0 otherwise

islower() returns 1 if string has at least 1 cased character


and all cased characters are in lowercase and 0
otherwise

isupper() returns 1 if string has at least one cased


character and all cased characters are in
uppercase and 0 otherwise

isspace() returns 1 if string contains only whitespace


characters and 0 otherwise

isnumeric() returns 1 if string contains only numeric characters


and 0 otherwise
Method Description

string.join(seq) merges (concatenates) the string representations


of elements in sequence seq into a string, with
separator string

lower() converts all uppercase letters in string to


lowercase

upper() converts lowercase letters in string to uppercase

lstrip() removes all leading whitespace in string

replace(str1, str2, replaces all occurrences of str1 in string with str2,


num=string.count(str1)) or at most num occurrences if num given

split(str="", num=string.count(str)) splits string according to delimiter str (space if not


provided) and returns list of substrings; split into
at most num substrings if given
Lists

Like strings, lists provide sequential storage through an index offset


and access to single or consecutive elements through slices.

How to Create and Assign Lists

Creating lists is as simple as assigning a value to a

variable. Lists are delimited by surrounding square

brackets [ ]
contd..

aList = [123, 'abc', 4.56]

How to Access Values in Lists

Slicing works similar to strings; use the square bracket slice operator
[ ] along with the index or indices.

aList[0] aList[1:4] aList[:3] aList[3][1]


contd..
How to Update Lists

You can update single or multiple elements of lists by giving the slice
on the left-hand side of the assignment operator.

You can add to elements in a list with the append() method.

How to Remove List Elements and Lists

To remove a list element, you can use either the del statement
or remove() method
List Type Built-in Methods
List Method Operation

append(obj) appends object obj to list

count(obj) returns count of how many times obj occurs in list

extend(seq) appends the contents of seq to list

index(obj) returns the lowest index in list that obj appears

insert(index, obj) inserts object obj into list at offset index

pop(obj=list[-1]) removes and returns last object or obj from list

remove(obj) removes object obj from list

reverse() reverses objects of list in place

sort() sorts objects of list


Special Features of Lists
Creating Other Data Structures Using Lists

● Stack
● Queue
Tuples

Tuples are another container type extremely similar in nature to lists.

The only visible difference between tuples and lists is that tuples use
parentheses and lists use square brackets.

How to Create and Assign Tuples

Creating and assigning lists are practically identical to lists.

Any set of multiple objects, comma-separated, written without brackets or


parentheses, will be considered defaultly as a Tuple.
contd..
Ever try to create a tuple with a single element? To do it, place a
trailing comma (,)

How to Access Values in Tuples

Slicing works similar to lists: Use the square bracket slice operator
([ ]) along with the index or indices.

How to Update Tuples

Like numbers and strings, tuples are immutable which means you
cannot update them or change values of tuple elements.
contd..
How to Remove Tuple Elements and Tuples

Removing individual tuple elements is not possible.

To explicitly remove an entire list, just use the del


statement.
Dictionaries
The last standard type is the dictionary, the sole mapping type in
Python, dictionary entries are enclosed in braces { }.

What makes dictionaries different from sequence type containers like


lists and tuples is the way the data is stored and accessed.

Python dictionaries are implemented as resizable hash tables.

The syntax of a dictionary entry is:

key:value
contd..
How to Create and Assign Dictionaries

Creating dictionaries simply involves assigning a dictionary to a


variable, regardless of whether the dictionary has elements or not.

How to Access Values in Dictionaries

To access dictionary elements, you use the square brackets along with
the key to obtain its value.
contd..
How to Update Dictionaries

You can update a dictionary by:

● adding a new entry or element (i.e., a key-value


pair)
● modifying an existing entry
● deleting an existing entry
contd..
How to Remove Dictionary Elements and Dictionaries

Generally, you either remove individual dictionary elements or clear the


entire contents of a dictionary.

However, if you really want to "remove" an entire dictionary, use the


del statement.
Dictionary Type Built-in Methods

Dictionary Method Operation

clear() removes all elements of dictionary

copy() returns a shallow copy of dictionary

get(key, default=None) for key, returns value or None if key not in dictionary

items() returns a list of dict's (key, value) tuple pairs

keys() returns list of dictionary dict's keys

dict.update(dict2) adds dictionary dict2's key-values pairs to dict

values() returns list of dictionary values


Set Types

A set is a collection, these are written with curly brackets.

How to Create and Assign Sets

aSet = {"apple", "banana", "Orange"}

The frozenset() is an inbuilt function in Python which takes an iterable


object as input and makes them immutable.

You might also like