Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

2.0 Python - Introduction

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

Python - Analytics

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


designed to be highly readable.

• Python is Interpreted
• Python is Interactive
• Python is Object-Oriented
• Python is a Beginner's Language

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 Netherlands.
Python - Features
 Easy-to-learn
 Easy-to-read
 Easy-to-maintain
 A broad standard library
 Interactive Mode
 Portable
 Extendable
 Databases
 GUI Programming
 Scalable
 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.
Environment
 Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS,
IRIX, etc.)
 Win 9x/NT/2000
 Macintosh (Intel, PPC, 68K)
 OS/2
 DOS (multiple versions)
 Windows CE
 Acorn/RISC OS
 BeOS
 Amiga
 VMS/OpenVMS
 QNX
Installation

 Unix or Ubuntu

 Windows

 Cloud - Databricks
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example −

if True:
print "True"
else:
print "False"
Multiline statements
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as
the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following
are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to
the end of the physical line are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment
Data Types
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

Python has five standard data types −


 Numbers
 String
 List
 Tuple
 Dictionary
Numbers
There are three numeric types in Python:

 int
 float
 complex
Int
Int, or integer, is a whole number, positive or negative, without
decimals, of unlimited length.

x = 1
y = 35656222554887711
z = -3255522
float
Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.

x = 1.10
y = 1.0
z = -35.59
Complex
Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j
Random
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers

import random

print(random.randrange(1, 10))
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

‘hello’ is the same as “hello”.

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign
and the string.

a = “Hello”
Print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Looping through a String
Since strings are arrays, we can loop through the characters in a string, with a for
loop

for x in “Analytics":
print(x)

String Length
To get the length of a string, use the len() function.

a = “Analytics, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.

Check if “spark" is present in the following text:

txt = "The best skills in analytics are Hadoop spark!"


print(“spark" in txt)

Print only if “spark” is present:

txt = "The best skills in analytics are Hadoop spark!!"


if “spark" in txt:
print("Yes, ‘spark' is present.")
Check String
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.

Check if "expensive" is NOT present in the following text:

txt = "The best skills in analytics are Hadoop spark!"


print(“expressive" not in txt)

print only if "expensive" is NOT present:

txt = "The best skills in analytics are Hadoop spark!!"


if “expressive" not in txt:
print(“No, ‘expressive’ is NOT present.")
Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the
string.

Get the characters from position 2 to position 5 (not included):

b = “Analytics, World!"
print(b[2:5])

Note: The first character has index 0.

Slice From the Start


By leaving out the start index, the range will start at the first character:

Get the characters from the start to position 5 (not included):


b = “Analytics, World!"
print(b[:5])
Slicing
Slice To the End
By leaving out the end index, the range will go to the end:

Get the characters from position 2, and all the way to the end:

b = “Analytics, World!"
print(b[2:])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):

b = “Analytics, World!"
print(b[-5:-2])
Modify
Python has a set of built-in methods that you can use on strings.

Upper Case

The upper() method returns the string in upper case:

a = “Analytics, World!"
print(a.upper())

Lower Case
Example
The lower() method returns the string in lower case:

a = “Analytics, World!"
print(a.lower())
Modify
Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.

The strip() method removes any whitespace from the beginning or the end

a = "Analytics, World! "


print(a.strip()) # returns "Hello, World!“

Replace String

The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))
Split
The split() method returns a list where the text between the specified separator
becomes the list items.

The split() method splits the string into substrings if it finds instances of the
separator:

a = “Analytics, World!"
print(a.split(",")) # returns [‘Analytics', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Merge variable a with variable b into variable c:

a = “Analytics"
b = "World"
c = a + b
print(c)

To add a space between them, add a “ “:

a = “Analytics"
b = "World"
c = a + " " + b
print(c)
Format - Strings
We cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method !
The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are:

Use the format() method to insert numbers into strings:


age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
Format Strings
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Characters
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:

You will get an error if you use double quotes inside a string that is surrounded by double
quotes:

txt = "We are the so-called "Vikings" from the north.“

To fix this problem, use the escape character \”


The escape character allows you to use double quotes when you normally would not be
allowed:

txt = "We are the so-called \"Vikings\" from the north."


Escape Characters
Other escape characters used in Python:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
capitalize() Converts the first character to upper case

String casefold() Converts string into lower case

Methods center() Returns a centered string

count() Returns the number of times a specified value


occurs in a string

encode() Returns an encoded version of the string


•Python has a set of built-in endswith() Returns true if the string ends with the specified
methods that you can use on value
strings.
expandtabs() Sets the tab size of the string
•Note: All string methods find() Searches the string for a specified value and returns
returns new values. They do the position of where it was found
not change the original string.
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and
returns the position of where it was found
isalnum() Returns True if all characters in the string are
alphanumeric
isalpha() Returns True if all characters in the string are in the
alphabet

String isdecimal() Returns True if all characters in the string are


decimals

Methods isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier


islower() Returns True if all characters in the string are lower
case
isnumeric() Returns True if all characters in the string are
numeric
isprintable() Returns True if all characters in the string are
printable
isspace() Returns True if all characters in the string are
whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper


case

join() Joins the elements of an iterable to the end of the


String ljust()
string

Returns a left justified version of the string


Methods lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three


parts

replace() Returns a string where a specified value is replaced


with a specified value
rfind() Searches the string for a specified value and returns the
last position of where it was found

rindex() Searches the string for a specified value and returns the
last position of where it was found

rjust() Returns a right justified version of the string


rpartition() Returns a tuple where the string is parted into three
parts
String rsplit() Splits the string at the specified separator, and returns a
Methods list

rstrip() Returns a right trim version of the string


split() Splits the string at the specified separator, and returns a
list

splitlines() Splits the string at line breaks and returns a list


startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes
upper case and vice versa

title() Converts the first character of


each word to upper case
String
translate() Returns a translated string
Methods
upper() Converts a string into upper case

zfill() Fills the string with a specified


number of 0 values at the
beginning
Booleans
Booleans represent one of two values: True or False

Boolean Values

In programming you often need to know if an expression is True or False


When you compare two values, the expression is evaluated, and Python returns the
Boolean answer:

print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False


Booleans
Print a message based on whether the condition is True or False
a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give you True or False in return
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))

Evaluate two variables:


x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Operators
Python divides the operators in the following groups:

1. Arithmetic operators

2. Assignment operators

3. Comparison operators

4. Logical operators

5. Identity operators

6. Membership operators

7. Bitwise operators
Operators
Arithmetic Operators

Arithmetic operators are used with numeric values to perform common


mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Operators
Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Operators
Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Operators
Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true
Operators
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not x is not y


the same object
Operators
Membership Operators
Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the
object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

You might also like