2.0 Python - Introduction
2.0 Python - Introduction
2.0 Python - Introduction
• 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.
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.
a = “Hello”
Print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
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.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
b = “Analytics, World!"
print(b[2:5])
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
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
Replace String
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.
a = “Analytics"
b = "World"
c = a + b
print(c)
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:
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:
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
Methods isdigit() Returns True if all characters in the string are digits
rindex() Searches the string for a specified value and returns the
last position of where it was found
Boolean Values
print(10 > 9)
print(10 == 9)
print(10 < 9)
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Operators
Arithmetic Operators
== Equal x == y
!= Not equal x != y
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: