0% found this document useful (0 votes)
33 views71 pages

Unit I Basics of Python

The document provides an overview of Python programming, covering its definition, history, features, and basic syntax. It explains key concepts such as variables, expressions, conditional statements, loops, and functions, along with examples. Additionally, it highlights the differences between data structures like lists and dictionaries, and introduces control statements like break and continue.

Uploaded by

Mahesh Kumar
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)
33 views71 pages

Unit I Basics of Python

The document provides an overview of Python programming, covering its definition, history, features, and basic syntax. It explains key concepts such as variables, expressions, conditional statements, loops, and functions, along with examples. Additionally, it highlights the differences between data structures like lists and dictionaries, and introduces control statements like break and continue.

Uploaded by

Mahesh Kumar
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/ 71

Python Programming for

Data Science
UNIT I
What is Python?

• Python is an example of a high-level language; other high-


level languages you might have heard of are C++, PHP, and
Java.
 Multi-purpose (Web, GUI, Scripting, etc.)

• Object Oriented

• Interpreted

• Strongly typed and Dynamically typed

• Focus on readability and productivity


History of Python:

• 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-learn: Python has few keywords, simple structure, and a clearly

defined syntax. This allows a 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 Macintosh.

• Interactive Mode: Python has support for an interactive mode, which

allows interactive testing and debugging of snippets of code.


Features of python:

• Python's features include-

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

• Databases: Python provides interfaces to all major commercial databases.

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

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and


Java.
Running Python program:

• There are three different ways to start Python-

(1) Interactive Interpreter

• You can start Python from Unix, DOS, or any other system
that provides you a command line interpreter or shell
window.

• Enter python the command line.


(2) Script from the Command-line

(3) Integrated Development Environment


The Difference Between Brackets, Braces, and Parentheses:
• Braces are used for different purposes. If you just want a list to contain some elements and
organize them by index numbers (starting from 0), just use the [] and add elements as
necessary. {} are special in that you can give custom id's to values like a = {"John": 14}.
Now, instead of making a list with ages and remembering whose age is where, you can
just access John's age by a["John"].

• The [] is called a list and {} is called a dictionary (in Python).

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

• A value is one of the fundamental things—like a letter or a number—that a


program manipulates. The values we have seen so far are 2 (the result when
we added 1 + 1), and “Hello, World!”. These values belong to different types:
2 is an integer, and “Hello, World!” is a string. You (and the interpreter) can
identify strings because they are enclosed in quotation marks.

• The print statement also works for integers.


Variables:

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

Variable names can be arbitrarily long.

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

• Bruce and bruce are different variables.

• The underscore character ( ) can appear in a name.

• It is often used in names with multiple words, such as myname or priceofteainchina.

If you give a variable an illegal name, you get a syntax error:


Keywords define the language’s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords:
Operators and Operands:

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:

• A + B here A and B are operands and + is operator

Expressions:

• An expression is a combination of values, variables, and operators. If you type an


expression on the command line, the interpreter evaluates it and displays the result:

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:

• The IF statement is similar to that of other languages. The if statement contains a


logical expression using which the data is compared and a decision is made based on
the result of the comparison.
Syntax:
if expression: statement(s)

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

• An else statement can be combined with an if statement.

• An else statement contains a block of code that executes if the conditional


expression in the if statement resolves to 0 or a FALSE value.

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

Syntax of for Loop:

for val in sequence:

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.

Syntax of while Loop in Python

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.

• Python Nested if Example

• # In this program, we input a number

• # check if the number is positive or

• # negative or zero and display

• # an appropriate message

• # This time we use nested if


num = float(input("Enter a number: "))

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)

• Not all functions take an argument, and some take


more than one (in which case the arguments are
separated by commas).

• The value or variable, which is called the argument


of the function, has to be enclosed in parentheses.

• It is common to say that a function “takes” an


argument and “returns” a result.

• The result is called the return value. 41


• Another useful function is len. It takes a Python sequence
as an argument.

• The only Python sequence we have met so far is a string.

• A string is a sequence of characters.

• For a string argument, len returns the number of


characters the string contains.

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

• indentation of four spaces3. IDLE automatically indents compound statements for

• Function definitions are the first of several compound statements we will see, all

• of which have the same pattern:

1. A header, which begins with a keyword and ends with a colon.

2. A body consisting of one or more Python statements, each indented the same

• amount – 4 spaces is the Python standard – from the header.

• 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

• parameter may be empty, or it may contain any number of parameters. In either

• case, the parentheses are required. The first couple of functions we are going to no

• write have parameters, so the syntax looks like this: 59


• This function is named new_line. The empty
parentheses indicate that it has no which parameters
(that is it takes no arguments). Its body contains only a
single statement, outputs a newline character. (That’s
what happens when you use a print command without
any arguments.)
• Defining a new function does not make the function
run. To do that we need a by a function call. Function
calls contain the name of the function to be executed
• followed list of values, called arguments, which are
assigned to the parameters in the function definition.
Our first examples have an empty parameter list, so the
do function calls not take any arguments. Notice,
however, that the parentheses are required in the
function call 60
Flow of Execution:
• In order to ensure that a function is defined before its
first use, you have to know the order in which statements
are executed, which is called the flow of execution.
• Execution always begins at the first statement of the
program. Statements are executed one at a time, in order
from top to bottom.
• Function definitions do not alter the flow of execution of
the program, but remember that statements inside the
function are not executed until the function is called.
• Although it is not common, you can define one function
inside another. In this case, the inner definition isn’t
executed until the outer function is called.
61
Parameters and Arguments:
• Most functions require arguments.
• Arguments are values that are input to the function and
these contain the data that the function works on.
• Some functions take more than one argument.
• Inside the function, the values that are passed get
assigned to variables called parameters.

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 :

• The functions that returns some value is known as


fruitful functions.

Void Functions :

• The functions that don’t return any value is known as


Void Functions.

• you can call one function from within another. This


ability is called composition
64
Boolean functions:

• Functions can return boolean values, which is often


convenient for hiding complicated tests inside functions.
For example:

65
Void Functions:

• Void functions are functions, like ‘print_twice’ (that we


defined earlier), that perform an action (either display
something on the screen or perform some other action).
However, they do not return a value.

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 :

>>> from math import*

• The advantage of importing everything from the math


module is that your code can be more concise.

• The disadvantage is that there might be conflicts between


names defined in different modules, or between a name
from a module and one of your variables.

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 :

• The functions that returns some value is known as fruitful functions.

Void Functions :

• The functions that don’t return any value is known as Void Functions.

71

You might also like