[go: up one dir, main page]

0% found this document useful (0 votes)
6 views47 pages

Data Science

This document provides an introduction to Python, highlighting its characteristics, applications, and data types. It covers essential concepts such as classes, objects, data types, I/O operations, and operators, along with examples of Python syntax. Additionally, it discusses decision-making structures and functions in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views47 pages

Data Science

This document provides an introduction to Python, highlighting its characteristics, applications, and data types. It covers essential concepts such as classes, objects, data types, I/O operations, and operators, along with examples of Python syntax. Additionally, it discusses decision-making structures and functions in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Python

Introduction to Python: (DAY-1)


Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming
language.

Why to Learn Python?

Class

Object (data and function)

Python is a high-level, interpreted, interactive and object-oriented scripting language.


Pythonisdesigned to be highly readable.
∙ Python is Interpreted
∙ Python is Interactive
∙ Python is Object-Oriented
∙ Python is a Beginner's Language

Applications of Python

As mentioned before, Python is one of the most widely used language over the web. I'mgoingto list few
of them here:
∙ Easy-to-learn
∙ Easy-to-read
∙ Easy-to-maintain
∙ A broad standard library
∙ Portable

Characteristics of Python

Following are important characteristics of Python Programming − ∙ It supports functional and


structured programming methods as well as OOP.
∙ It can be used as a scripting language or can be compiled to byte-code for
buildinglargeapplications.
∙ It provides very high-level dynamic data types and supports dynamic type checking. ∙ It supports
automatic garbage collection.
∙ It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Program 1:

Print(“"Hello, Python!")

Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot usethem as constant or
variable or any other identifier names. All the Python keywords containlowercase letters only.s

assert final

break for

class from

continue global

def if

del impo

elif in

else is

except lamb

and exec

Data Types & I/O Operations: (Day-2)


Data Types:
The data stored in memory can be of many types. For example, a person's age is storedasanumeric value and
his or her address is stored as alphanumeric characters. Python has variousstandard data types that are used to
define the operations possible on themand the storagemethod for each of them.
Python has five standard data types −

∙ Numbers
∙ String
∙ List
∙ Tuple
∙ Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign a
valuetothem. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntaxofthe 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
Python supports four different numerical types −

∙ int (signed integers)


∙ long (long integers, they can also be represented in octal and hexadecimal) ∙ float (floating
point real values)
∙ complex (complex numbers)

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the quotationmarks. Python allows
for either pairs of single or double quotes. Subsets of strings can be takenusing the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the stringandworking their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetitionoperator. 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

Python Lists

Lists are the most versatile of Python's compound data types. A list contains items separatedbycommas and
enclosed within square brackets ([]). To some extent, lists are similar to arrays inC. One difference between them
is that all the items belonging to a list can be of different datatype.
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
Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number ofvalues separated by
commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) andtheirelements and size
can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot beupdated. 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 the complete tuple


print tuple[0] # Prints first element of the tuple print tuple[1:3] # Prints elements of the tuple starting
from 2nd till 3rdprint tuple[2:] # Prints elements of the tuple starting from 3rd element print tinytuple
2 # Prints the contents of the tuple twice print tuple + tinytuple # Prints concatenated tuples

Python Dictionary

Python's dictionaries are kind of hash table type. They work like associative arrays or hashesfound in Perl and
consist of key-value pairs. A dictionary key can be almost any Pythontype, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Pythonobject.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessedusingsquare braces ([]). For example −#!/usr/bin/python
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

I/O Operations:

Types of Operator
Python language supports the following types of operators.

∙ Arithmetic Operators
∙ Comparison (Relational) Operators
∙ Assignment Operators
∙ Logical Operators
∙ Bitwise Operators
∙ Membership Operators
∙ Identity Operators

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example

Adds values on either side of the operator.

- Subtraction Subtracts right hand operand from left hand operand. a

* Multiplies values on either side of the operator


Multiplication

Python Comparison Operators


/ Division Divides left hand operand by right hand operand
+b=

% Modulus Divides left hand operand by right


hand operand and returnsremainder
–b=-
** Exponent Performs exponential (power) calculation on operators
*b=

// Floor Division - The division of operands where the


result isthe quotient in which the digits after
/ a = 2 the
decimal point areremoved. But if one of the operands is
negative, the result isfloored, i.e., rounded away from
zero (towards negativeinfinity) − %a =

=10
the
20
=4 =-

4.0, -

These operators compare the values on either sides of them and decide the relation amongthem. They are also
called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Exampl
e

<= If the value of left operand is less tha


== If the values of two operands are equal, then the valueof right operand, then condition becomes true.
conditionbecomes true.

!= notthen
If values of two operands are not equal,
conditionbecomes true.
true.
true.
<> If values of two operands are not equal, then
conditionbecomes true.

> If the value of left operand is greater than the value


of rightoperand, then condition becomes true.

< If the value of left operand is less than the value


of rightoperand, then condition becomes true. not

true.
>= If the value of left operand is greater than or
equal tovalue of right operand, then condition becomes true.

Python Assignment Operators


Operator Description
> b) is
= Assigns values from right side operands to left side operand

< b) is

== b)
>= b)

!= b)
<= b)

<> b)

is

!=

=a+b

of a
b into c
/= Divide AND It divides left operand with the rig
AND It adds right operand to the left operand and result to left operand
assignto left operand

%= ModulusAND It takes modulus using two operands and assign


-= SubtractAND It subtracts right operand from the left operand andthe result to left operand
operand

**= Performs exponential (power) calcul


ANDresult to left
*= MultiplyAND It multiplies right operand with the left operand andthe Exponent
operand assign value to the left operand
Python
//= FloorDivision It performs floor division on operators and assign Bitwise
valuethe left Operators
operand
+= a is

c=c+

-= a is

c=c-

*= a is

c=c*

/= a is

c=c/

%= a is

c=c%

**= a is

c=c
a

//= a is

c = c //

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
andb=13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively. Followingtable lists out the bitwise operators supported by Python language
with an example eachinthose, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Operator Description

b) & Binary AND Operator copie


operands
1100)

| Binary ORIt copies a bit if it exist


61

1101)

^ Binary XOR It copies the bi


b) = 49 both.

0001)
~ Binary OnesComplement

) = -61
It is unary and has the effect

0011
2's

due to

<< Binary Left Shift The left operands value is moved left
a <<240
by
the numberof bits specified by the right operand. 1111
>> BinaryShift The left operands value is moved rightaby
>>(means
the
Right
number of bits specified by the right operand. 0000

2=
(means
0000)

2 = 15

1111)

Python Logical Operators


There are following logical operators supported by Python language. Assume variable a holds10 and variable b
holds 20 then
or Logical OR If any of the two operands are non-zero then condition
Operator Description becomes true.
true.

and LogicalAND nottrue then conditionUsed


If both the operands are to reverse
becomes true. the
(a logical state of its operand.
LogicalNOT
and b) or b)

true.
b) is

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings,
lists, ortuples. There are two membership operators as explained below −
Operator Description Example
in Evaluates to true if it finds a variable in the specified
sequenceand false otherwise.

not in Evaluates to true if it does not finds a variable in the


specifiedsequence and false otherwise.

Python Identity Operators

not in

in y,
in in
in 1 if x is
1 if x is

Identity operators compare the memory locations of two objects. There are two
Identityoperators explained below −
[ Show Example ]
is not Evaluates to false if the variables on either
Operator Description operatorpoint to the same object and true otherwise.

is Evaluates to true if the variables on either side of the


operatorpoint to the same object and false otherwise.
if id(x) in
id(y).

to

id(y).

Python Operators Precedence The following table lists all operators from
highest precedence to lowest.

last 3 * / % // Multiply, divide, modulo and fl


Sr.No.

1 ** 4 +-
Exponentiation (raise to the power)
Addition and subtraction

2 ~+- 5 >> <<


Complement, unary plus and minus (method names for thetwo are +@
Right and left bitwise shift
and -@)
6 & 7 ^|
Bitwise 'AND' Bitwise exclusive `OR' and regular `OR'

8 <= < > >=


Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **= Assignment operators

11 is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators

Example 2: Add Two Numbers


# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Conditional Exceptions (Day-3)
Decision making is anticipation of conditions occurring while execution of the programandspecifying
actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSEas outcome. You need to
determine which action to take and which statements to execute if outcomeisTRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of
theprogramming languages −

Python programming language assumes any non-zero and non-null values as TRUE, andif it iseither zero or
null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Clickthe following
links to check their detail.
S.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or morestatements.

2 if...else statements
An if statement can be followed by an optional else statement, whichexecutes
when the boolean expression is FALSE.

3 nested if statements
Example 3: Add Two Numbers
You can use one if or else if statement inside anotherifor
# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result


celsius = 37.5

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Functions (Day-4)
A function is a block of organized, reusable code that is used to perform a single, relatedaction. Functions provide
better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but youcanalso create
your own functions. These functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to defineafunction in Python.
∙ Function blocks begin with the keyword def followed by the function nameandparentheses ( ( ) ).
∙ Any input parameters or arguments should be placed within these parentheses. Youcanalso
define parameters inside these parentheses.
∙ The first statement of a function can be an optional statement - the documentationstringof the
function or docstring.
∙ The code block within every function starts with a colon (:) and is indented.
∙ The statement return [expression] exits a function, optionally passing back an expressionto the caller. A
return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to informthemin the sameorder that they were
defined.

Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be includedinthefunction and
structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
fromanotherfunction or directly from the Python prompt. Following is the example to
call printme() function−
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

O/P:
I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if
youchange what a parameter refers to within a function, the change also reflects back in
the callingfunction. For example −
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the
sameobject. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the referenceisbeing
overwritten inside the called function.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values
inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the functiondoes not affect
mylist. The function accomplishes nothing and finally this would producethefollowing
result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

Example 4: Using a flag variable


# Program to check if a number is prime or not

num = 29
# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

Iterations: (Day-5)
In general, statements are executed sequentially: The first statement in a function is executedfirst, followed by the
second, and so on. There may be a situation when you need to executeablock of code several number of times.
Programming languages provide various control structures that allow for more complicatedexecution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. Thefollowing diagram illustrates a loop statement −
Python programming language provides following types of loops to handle loopingrequirements.

Sr.No.
Loop Control Statements
1 while loop

Repeats a statement or group of statements while a given condition is TRUE. Itthe condition
before executing the loop body.
tests
2 for loop
Executes a sequence of statements multiple times and abbreviates the codemanages the loop
variable.
that
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

Loop control statements change execution from its normal sequence. When execution leavesascope, all automatic
objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their detail.
Let us go through the loop control statements briefly 3 pass statement
Sr.No. Control Statement & Description
The pass statement in Python is used when a statement
not want any command or code to execute.
1 break statement

Terminates the loop statement and transfers execution to the statementimmediately


following the loop.

2 continue statement
Causes the loop to skip the remainder of its body and immediatelycondition prior
to reiterating. retest its

Strings are amongst the most popular types in Python. We can create themsimply by
enclosingcharacters in quotes. Python treats single quotes the same as double quotes.
Creating stringsisas simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

Example 5:
# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Accessing Values in Strings(Day-6)


Python does not support a character type; these are treated as strings of length one, thus alsoconsidered a
substring.
To access substrings, use the square brackets for slicing along with the index or indices
toobtain your substring. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

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


var1[0]: H
var2[1:5]: ytho

Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The
newvaluecan 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

Escape Characters
Following table is a list of escape or non-printable characters that can be representedwithbackslash
notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
\cx

\C-x

\e 0x1b

\f 0x0c

\M-\C-x

\n 0x0a

\nnn

0.7
\r 0x0d

\s 0x20
Backslash Hexadecimal
notation character
\t 0x09

\a 0x07
\v 0x0b

\b 0x08
\x

\xnn Hexadecimal notation, where n is in the rangea.f, or A.F


String Special Operators
0.9,

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description
+ Concatenation - Adds values on either side of the operator

b will

* Repetition - Creates new strings, concatenating multiple


copiesthe same string

will
-
[] Slice - Gives the character from the given index

e given range a[1:4]


Range Slice - Gives the characters from the

will
in ell in the given
Membership - Returns true if a character exists

in a will
not in Membership - Returns true if a character does 1not exist in
string

r/R Raw String - Suppresses actual meaning of Escape characters. The


syntax for raw strings is exactly the same as for normal stringsthe exception of
the raw string operator, the letter "r," whichprecedes the quotation marks. The
"r" can be lowercase (r) oruppercase (R) and must be placed immediately
preceding the firstquote mark.
a

1
\n and

% Format - Performs String formatting See


section

at next

String Formatting Operator


One of Python's coolest features is the string format operator %. This operator is
uniquetostrings and makes up for the pack of having functions from C's printf()
family. Followingisasimple example −
print "My name is %s and weight is %d kg!" % ('Zara', 21)

When the above code is executed, it produces the following result − My name is
Zara and weight is 21 kg!

%d signed decimal integer


Format Symbol Conversion

%u unsigned decimal intege


%c character

%o octal integer
%s string conversion via str() prior to formatting

%x hexadecimal integer (low


%i signed decimal integer

%X hexadecimal integ

%e exponential notation (with lowercase 'e')


%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E

Other supported symbols and functionality are listed in the following table −
Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

# 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 '%'

(var) mapping variable (dictionary arguments)

m.n. m is the minimum total width and n is the number of digitsdisplay


after the decimal point (if appl.) Example 6:
to
#Accessing string characters in Python
str = 'programiz'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2])

Files (Day-7)
Until now, you have been reading and writing to the standard input and output. Now, wewill see how to use actual
data files.
Python provides basic functions and methods necessary to manipulate files by default. Youcando most of
the file manipulation using a file object.

The open Function


Before you can read or write a file, you have to open it using Python's built-in open() function. This function
creates a file object, which would be utilized to call other support methodsassociated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
∙ file_name − The file_name argument is a string value that contains the name of
thefilethat you want to access.
∙ access_mode − The access_mode determines the mode in which the file has tobeopened,
i.e., read, write, append, etc. A complete list of possible values is given belowinthe
table. This is optional parameter and the default file access mode is read (r).
∙ buffering − If the buffering value is set to 0, no buffering takes place. If the
bufferingvalue is 1, line buffering is performed while accessing a file. If you specify
the bufferingvalue as an integer greater than 1, then buffering action is performed
with the indicatedbuffer size. If negative, the buffer size is the system
default(default behavior).
Here is a list of the different modes of opening a file −
file. 2 rb
Opens a file for reading only in binary fo
file. This is the default mode.

at the
3 r+
Opens a file for both reading and writing

4 rb+
Opens a file for both reading and writing
beginning of the file.

does not
5 w
Sr.No. Modes & Description
Opens a file for writing only. Overwrites
file for writing.
1 r
Opens a file for reading only. The file pointer is placed at6the beginning
wb of theThis is the default
mode.
Opens a file for writing only in binary fo
not exist, creates a new file for writing.

7 w+
Opens a file for both writing and reading. Overwrites the existing file if theexists. If the file does
not exist, creates a new file for reading and writing.

8 wb+
Opens a file for both writing and reading in binary format. Overwrites thefile if the file exists. If the
file does not exist, creates a new file for readingandwriting.

9 a
Opens a file for appending. The file pointer is at the end of the file if the fileThat is, the file is in
the append mode. If the file does not exist, it creates afor writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of thethe file exists. That
is, the file is in the append mode. If the file does not exist,creates a new file for writing.

11 a+
Opens a file for both appending and reading. The file pointer is at the endif the file exists.
The file opens in the append mode. If the file does not exist,creates a new file for reading
and writing.

12 ab+
Opens a file for both appending and reading in binary format. The file pointerthe end of the
file if the file exists. The file opens in the append mode. If thenot exist, it creates a new file for
reading and writing.

file

existing

exists.
newfile

fileif
it

of the file
it
is at
file does

Example 7:
f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'

>>> f.read(4) # read the next 4 data


' is '

>>> f.read() # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

>>> f.read() # further reading returns empty sting


''

Python Lists (Day-8)


The list is a most versatile datatype available in Python which can be written as a list of comma-separated values
(items) between square brackets. Important thing about a list is that items inalist need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square
brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and soon. Accessing

Values in Lists

To access values in lists, use the square brackets for slicing along with the index or
indicestoobtain value available at that index. For example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-handsideofthe assignment
operator, and you can add to elements in a list with the append() method. Forexample –
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

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


Value available at index 2 :
1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, you can use either the del statement if you
knowexactlywhichelement(s) you are deleting or the remove() method if you do not
know. For example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1

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


['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

EXAMPLE 8:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']

print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)

Python – Dictionary(Day-9)
Each key is separated from its value by a colon (:), the items are separated by commas, andthewhole thing
is enclosed in curly braces. An empty dictionary without any items is writtenwithjust two curly braces, like
this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionarycanbeof any type, but
the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary


To access dictionary elements, you can use the familiar square brackets along with the keytoobtain its value.
Following is a simple example –
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

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


dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get
anerror as follows −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existingentry, or deleting an
existing entry as shown below in the simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

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


dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also
delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simpleexample −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

This produces the following result. Note that an exception is raised because after del dict dictionary does not
exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

EXAMPLE 9:
# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


# Output: 16

print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print(squares.popitem())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

Python – Tuples (Day-10)


A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just likelists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists andtuples use parentheses,
whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally
youcanput these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing − tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
thereisonly one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on. Accessing

Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or
indicestoobtain value available at that index. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

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


tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following exampledemonstrates −
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;

When the above code is executed, it produces the following result − (12, 34.56,
'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrongwithputting together
another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";

print tup;

This produces the following result. Note an exception raised, this is because after del tuptupledoes
not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
EXAMPLE 10:
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and
Dictionary, all with different qualities and usage.

A set is a collection which is both unordered and unindexed.

Sets are written with curly brackets.

Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

Duplicates Not Allowed Sets cannot have two items with the same value.
Example:

thisset = {"apple", "banana", "cherry", "apple"}

Output:

{'banana', 'cherry', 'apple'}


Accessing Item in the Set:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print(thisset)
Add Items to Set:
Update:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)
Add:
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Remove Item To remove an item in a set, use the remove(), or the discard() method.
Example:
Remove():
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
discard():
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)
Pop():
thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

Join Set:
Union():

The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Output:
{'c', 'a', 1, 3, 'b', 2}
Update():

The update() method inserts the items in set2 into set1:


set1 = {"a", "b", "c"}
set2 = {1, 2, 3}

set1.update(set2)
print(set1)

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or astring).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in
other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Python Classes/Objects Python is an object oriented


programming language.
Almost everything in Python is an object, with its properties and methods. A Class is like an

object constructor, or a "blueprint" for creating objects. Create a Class

To create a class, use the keyword class:

Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5

Example
Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)

Object Methods:
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Create a Parent Class Any class can be a parent class, so the syntax is the
same as creating any other class: Example

Create a class named Person, with firstname and lastname properties, and a printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()

Example
Create a class named Student, which will inherit the properties and methods from the Person class:

class Student(Person):
pass

Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Example:

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be usedinside that function.

Example:

def myfunc():
x = 300
print(x)
myfunc()

Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope.

Global variables are available from within any scope, global and local. Example:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Python Dates
Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()
print(x)

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime()

class requires three parameters to create a date: year, month, day. Example

Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

The strftime() Method The datetime object has a method for formatting
date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returnedstring:

Example:
import datetime

x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))

Built-in Math Functions Min and Max:


The min() and max() functions can be used to find the lowest or highest value in an iterable: Example

x = min(5, 10, 25)


y = max(5, 10, 25)

print(x)
print(y)
Abs:

The abs() function returns the absolute (positive) value of the specified number: Example

x = abs(-7.25)

print(x)
Pow:

The pow(x, y) function returns the value of x to the power of y (xy).


Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4): x = pow(4, 3)

print(x)

Square Root:

The math.sqrt() method for example, returns the square root of a number: Example

import math

x = math.sqrt(64)

print(x)
Ceil and Floor:

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() methodrounds a
number downwards to its nearest integer, and returns the result:

Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1
PI:

The math.pi constant, returns the value of PI (3.14...):

Example
import math

x = math.pi
print(x)

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Else
You can use the else keyword to define a block of code to be executed if no errors were raised: Example

In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not. Example

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise)

an exception, use the raise keyword.

Example
Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Example: User-Defined Exception in Python


In this example, we will illustrate how user-defined exceptions can be used inaprogram to raise and
catch errors.

This program will ask the user to enter a number until they guess a stored number correctly. To help
them figure it out, a hint is provided whether their guess is greaterthan or less than the stored
number.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10

# user guesses a number until he/she gets it right


while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

Here is a sample run of this program.


Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used

to check if a string contains the specified search pattern.

RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions. Import the re

module:

import re
import re

txt = "The rain in Spain"


x = re.search("^The.*Spain$", txt)

RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Function Description
findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the stringsplit Returns a list

where the string has been split at each match sub Replaces one or many matches with a string

The findall() Function The findall() function returns a list containing all
matches.

Example
Print a list of all matches:

import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)

The search() Function The search() function searches the string for a match, and returns a
Match object if there is a match. If there is more than one match, only the first occurrence of the match will be

returned: Example

Search for the first white-space character in the string:

import re
txt = "The rain in Spain"
x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start()) The split()


Function
The split() function returns a list where the string has been split at each match: Example

Split at each white-space character:

import re

txt = "The rain in Spain"


x = re.split("\s", txt)
print(x)

The sub() Function The sub() function replaces the matches with the
text of your choice: Example

Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)

You might also like