Unit I Basics of Python
Unit I Basics of Python
Data Science
UNIT I
What is Python?
• Object Oriented
• Interpreted
• Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherland
• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
• Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is
the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2.
The emphasis in Python 3 had been on the removal of duplicate programming constructs and
modules so that "There should be one -- and preferably only one -- obvious way to do it." Python
3.5.1 is the latest version of Python 3
Features of python:
• Python's features include-
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• A broad standard library: Python's bulk of the library is very portable and
• 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 efficient.
• GUI Programming: Python supports GUI applications that can be created and ported 4
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.
Apart from the above-mentioned features, Python has a big list of good
features. A few are listed below-
• 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 building large applications.
• It provides very high-level dynamic data types and supports
dynamic type checking.
• It supports automatic garbage collection.
• You can start Python from Unix, DOS, or any other system
that provides you a command line interpreter or shell
window.
• Dictionaries are basically a convenient form of list which allow you to access data in a
much easier way.
• However, there is a catch to dictionaries. Many times, the data that you put in the
dictionary doesn't stay in the same order as before. Hence, when you go through each
value one by one, it won't be in the order you expect. There is a special dictionary to get
around this, but you have to add this line from collections import OrderedDict and replace
{} with OrderedDict(). But, I don't think you will need to worry about that for now.
Variables and Expressions:
Values and Types:
• One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a
name that refers to a value. The assignment statement creates new variables and assigns them values:
Programmers generally choose names for their variables that are meaningful—they document what the variable is
used for.
• They can contain both letters and numbers, but they have to begin with a letter.
• Although it is legal to use uppercase letters, by convention we don’t. If you do, remember that case matters.
Operators are special symbols that represent computations like addition and multiplication.
The values the operator uses are called operands. The following are all legal Python
expressions whose meaning is more or less clear:
Expressions:
The evaluation of an expression produces a value, which is why expressions can appear on
the right hand side of assignment statements. A value all by itself is a simple expression, and
so is a variable.
Order of Operations:
• When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators
that mathematics does. The acronym PEMDAS is a useful way to remember the order of
operations:
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2*(3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in
(minute*100)/60, even though it doesn’t change the result.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27.
3. Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is -1,
not 1 (remember that in integer division, 2/3=0).
• Operators with the same precedence are evaluated from left to right. So in the expression
minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the
operations had been evaluated from right to left, the result would have been 59*1, which is 59,
which is wrong. Similarly, in evaluating 17-4-3,
• 22
• 17-4 is evaluated first.
• If in doubt, use parentheses.
Conditional Statements:
IF statement:
• If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. In Python, statements in a block are uniformly indented
after the : symbol. If boolean expression evaluates to FALSE, then the first set of code
after the end of block is executed.
• nested if statements You can use one if or else if statement inside another
if or else if statement(s).
Guess the output?
•3 is a positive number. This is always printed.
IF ELSE Statements:
• The else statement is an optional statement and there could be at the most
only one else statement following if.
Syntax
• The syntax of the if...else statement is
if expression:
statement(s)
else: statement(s)
Nested IF -ELSE Statements:
• There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct. In a nested if
construct, you can have an if...elif...else construct inside another if...elif...else construct.
Syntax The syntax of the nested if...elif...else construct may be
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else: statement(s)
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero Divisible by 3 and 2
enter number 5
not Divisible by 2 not divisible by 3
Looping:
For:
• The for loop in Python is used to iterate over a sequence (list, tuple, string)
or other iterable objects. Iterating over a sequence is called traversal.
Body of for
• Note :Here, val is the variable that takes the value of the item
inside the sequence on each iteration. Loop continues until
we reach the last item in the sequence. The body of for loop
is separated from the rest of the code using indentation.
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
for val in numbers:
• when you run the program, the output will be: The sum is 48
While Loop
• The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is
true. We generally use this loop when we don't know beforehand, the number of times to iterate.
while test_expression:
Body of while
• Note: In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one iteration, the
test expression is checked again. This process continues until the
test_expression evaluates to False.
• In Python, the body of the while loop is determined through indentation. Body
starts with indentation and the first unindented line marks the end. Python
interprets any non-zero value as True. None and 0 are interpreted as False.
Example: Python while Loop
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
#To take input from the user,
n = int(input("Enter n: ")) n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + I
i = i+1
# update counter
# print the sum
print("The sum is", sum)
output: Enter n: 10
The sum is 55
Nested loops:
• Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
• # an appropriate message
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
• Special note: while using nested if else statement make sure inner
block has proper indentation prior to outer block .
Control statements:
1. Terminating loops:
• The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.
• If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax of break
break
2. Skipping specific conditions:
• The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
continue
Example: # Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val) print("The end")
Output :
s
t
r
n
g
The end
UNIT II
38
Functions
• In python we have two kinds of functions .
• First is built –in functions .
• User defined functions (with def keyword).
• This functions (built-in functions ) can also be categories
into two types i.e.
1. Fruitful Function(returns value)
2. Void Function (doesn’t return any value)
39
Special Note :
• You can some use built-in functions in python without
any import .(for e.g . abs)
• You can use that on command prompt directly also.
• For some functions you need to import that function
based module for e.g suppose you want to calculate
ceiling value of a number using ceil function you need to
import math module first .
import math # This will import math module
print ("math.ceil(-45.17) : ", math.ceil(-45.17))
• If you use this kind functions directly with its module
importing you will get error .
40
• The syntax of a function call is simply
FUNCTION NAME(ARGUMENTS)
42
Math Functions:
43
44
abs() Method :
Description: The abs() method returns the absolute value of
x i.e. the positive distance between x and zero.
Syntax : Following is the syntax for abs() method-
abs(x)
Parameters :
x - This is a numeric expression.
Return : This method returns the absolute value of x.
The following example shows the usage of the abs()
method.
abs(-45): 45
abs(100.12) : 100.12 45
ceil() Method :
Description: The ceil() method returns the ceiling value of x
i.e. the smallest integer not less than x.
Syntax: Following is the syntax for the ceil() method
import math
math.ceil( x )
Parameters
x - This is a numeric expression.
Return Value
This method returns the smallest integer not less than x.
Note: This function is not accessible directly, so we need to
import math module and then we need to call this function
using the math static object. 46
exp() Method
Description
The exp() method returns exponential of x: ex.
Syntax
Following is the syntax for the exp() method
import math
math.exp( x )
Parameters
X - This is a numeric expression.
Return Value
This method returns exponential of x: ex.
Note: This function is not accessible directly. Therefore, we
need to import the math module and then we need to call
this function using the math static object. 47
fabs() Method
Description
The fabs() method returns the absolute value of x. Although similar
to the abs()
function, there are differences between the two functions. They are-
• abs() is a built in function whereas fabs() is defined in math
module.
• fabs() function works only on float and integer whereas abs()
works with complex number also.
Syntax
Following is the syntax for the fabs() method
import math
math.fabs( x )
Note: This function is not accessible directly, so we need to import
the math module And then we need to call this function using the
math static object. 48
floor() Method
Description
The floor() method returns the floor of x i.e. the largest integer not
greater than x.
Syntax
Following is the syntax for the floor() method
import math
math.floor( x )
Parameters
x - This is a numeric expression.
Return Value
This method returns the largest integer not greater than x.
The following example shows the usage of the floor() method.
Note: This function is not accessible directly, so we need to import
the math module and then we need to call this function using the 49
math static object.
log() Method
Description
The log() method returns the natural logarithm of x, for x > 0.
Syntax
Following is the syntax for the log() method
import math
math.log( x )
Parameter:
x - This is a numeric expression.
Return Value
This method returns natural logarithm of x, for x > 0.
Note: This function is not accessible directly, so we need to
import the math module and then we need to call this
function using the math static object. 50
log 10() Method
Description
The log10() method returns base-10 logarithm of x for x > 0.
Syntax
Following is the syntax for log10() method
import math
math.log10( x )
Parameters
x - This is a numeric expression.
Return Value
This method returns the base-10 logarithm of x for x > 0.
Note: This function is not accessible directly, so we need to
import the math module and then we need to call this
function using the math static object. 51
max() Method
Description
The max() method returns the largest of its arguments i.e.
the value closest to positive infinity.
Syntax
Following is the syntax for max() method
max(x, y, z, .... )
Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
• This method returns the largest of its arguments. 52
min() Method
Description
The method min() returns the smallest of its arguments
i.e. the value closest to negative infinity.
Syntax
Following is the syntax for the min() method
min(x, y, z, .... )
Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
• This method returns the smallest of its arguments. 53
modf() Method
Description
• The modf() method returns the fractional and integer parts of
x in a two-item tuple.
• Both parts have the same sign as x. The integer part is
returned as a float.
Syntax
Following is the syntax for the modf() method
import math
math.modf( x )
Parameters
x - This is a numeric expression.
Return Value
• This method returns the fractional and integer parts of x in a
two-item tuple. Both the parts have the same sign as x. The 54
pow() Method
• Return Value
• This method returns the value of xy.
Example
• The following example shows the usage of the pow()
method.
import math # This will import math module
print ("math.pow(100, 2) : ", math.pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))
NOTE: make sure you pass two arguments to pow ()
• Otherwise it will raise an exception . 55
round() Method
Description
• round() is a built-in function in Python. It returns x rounded
to n digits from the decimal point.
Syntax
Following is the syntax for the round() method
round(x [, n] )
Parameters
• x - This is a numeric expression.
• n - Represents number of digits from decimal point up to
which x is to be rounded.
Default is 0.
Return Value
• This method returns x rounded to n digits from the decimal
point. 56
sqrt() Method
• The sqrt() method returns the square root of x for x > 0.
Syntax
Following is the syntax for sqrt() method
import math
math.sqrt( x )
Parameters
x - This is a numeric expression.
Return Value
• This method returns square root of x for x > 0.
Note: This function is not accessible directly, so we need to
import the math module and then we need to call this function
using the math static object. 57
Adding New Functions
• A new function can be created in python using keyword
def followed by the function name and arguments in
parathesis and statements to be executed in function
Example:
def requiredArg (str,num):
Statements
Function definitions and use
• As well as the built-in functions provided by Python you
can define your own functions.
• In the context of programming, a function is a named
sequence of statements that performs a desired
operation. This operation is specified in a function
definition. In Python, the syntax for a function definition
is: 58
def NAME( LIST OF PARAMETERS ):
STATEMENTS
• There can be any number of statements inside the function, but they have to be you.
• indented from the def. In the examples in this book, we will use the standard
• Function definitions are the first of several compound statements we will see, all
2. A body consisting of one or more Python statements, each indented the same
• In a function definition, the keyword in the header is def, which is followed by the
• list name of the function and a list of parameters enclosed in parentheses. The
• case, the parentheses are required. The first couple of functions we are going to no
62
Fruitful functions and Void functions:
The return statement :
• The return statement allows you to terminate the
execution of a function before you reach the end. One
reason to use it is if you detect an error condition:
The function print square root has a parameter named x. The first thing it does is
check whether x is less than 0, in which case it displays an error message and
then uses return to exit the function. The flow of execution immediately returns
to the caller, and the remaining lines of the function are not executed.
63
Fruitful Functions :
Void Functions :
65
Void Functions:
66
Importing with from:
• We can use functions in modules in three different
ways:
Import a module object in Python:
• If you import math, you get a module object named
math. The module object contains constants like pi and
functions like sin and exp.
67
• Import an object from a module in Python:
68
Import all objects from a module in Python :
69
QUICK REVISION :
• In python we have two kinds of functions .
• First is built –in functions .
• User defined functions (with def keyword).
• This functions (built-in functions ) can also be
categories into two types i.e.
1. Fruitful Function(returns value)
2. Void Function (doesn’t return any value).
• A new function can be created in python using keyword
def followed by the function name and arguments in
parathesis and statements to be executed in function.
70
• Arguments are values that are input to the function and these
contain the data that the function works on.
• Inside the function, the values that are passed get assigned to
variables called parameters.
Fruitful Functions :
Void Functions :
• The functions that don’t return any value is known as Void Functions.
71