Python For Cloud
Python For Cloud
Bacis
What is Python? Data Type Conversion
Python History Python Operators
What is Python?
Python is an interpreted high-level general-purpose programming
language. It consistently ranks as one of the most popular programming
languages.
Its high-level built-in data structures, combined with dynamic typing and
dynamic binding, make it very attractive for Rapid Application
Development, as well as for use as a scripting or glue language to
connect existing components together.
Source: Wikipedia
Learn.sandipdas.in
1980
First Released as
1991
It took a long ... Python 2.0 was
released
2000
Python 3.0 was released
2008
Source: Wikipedia
Learn.sandipdas.in
Use Cases
Where Python getting used the most?
Python gets used for developing Python gets used to developing One of the most popular use
web applications, REST APIs, etc workflow automation scripts cases of Python is in the field of
including Cloud automation & Data Science and Machine
Using: Django, Pyramid, Bottle, resource provisioning. Learning
Tornado, Flask, web2py Notably: Ansible, Salt,
Openstack, xonsh written in Using: SciPy, Pandas, IPython,
Python NumPy etc
Learn.sandipdas.in
Our Goal
Our goal in this series will be to
have enough Python knowledge
to work on Cloud & DevOps
Projects, use different SDKs
provided by the Cloud Service
providers and other open-source
projects
Learn.sandipdas.in
Key Words
Python has reserved keywords
Python has multiple reserved keywords which we can not
use as variable names or any identifier and these
keywords have specific purposes/use cases while doing
programming with Python (We will cover in the next
sections)
List of keywords
if, elif, else, and, or, not, with, for, global, import, async,
await, None, pass, return, raise, except, lambda, try, while,
nonlocal, continue, finally, from, yield, True, False, class,
break, except, is, in, import etc
Variables Example
Variable name
myVar
There are certain rules in Python to define a variable name, as follow: my_var
1. Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) _myVar
2. Variable name must start with a letter or the _ character & cannot start with a number myVar31
Naming Covetion While Naming Multi Word Variable Camel Case: myVarName
Proper Case: MyVarName
While naming a multi-value variables, Camel Case, Proper Case, Snake Case are usually get Snake Case: my_var_ame
used, but most popular is Camel Case or Snake Case
x, y, z = "Red", "Green", "Blue"
Multi Value assignment and output print(x)
Python allow us to use multi-value assignment as showing in example print(y)
print(z)
Data Types
We can use
Example
"type()"
ck
function to che Numeric
type of ay a = 7 # int
variable b = 3.8 # float
01 Numeric c = 5j # complex
print(type(a))
There are Integers, floating-point, and complex numbers in Python. Defied as int,
print(type(b))
float and complex classes in Python print(type(c))
02 String String
The string is a sequence of Unicode characters, Strings in python are represented name = "Sandip Das"
print(type(name))
within a single quotation e.g. 'Sandip or double quotation "Sandip". Defined as
"str" class in Python list
simpleList = ["red",
03 list, tuple, set "green", "blue", 4, 5, 6]
print(type(simpleList))
List: Lists are used to store multiple items in a single variable in a mutable ordered
sequence. Items are separated by a comma and inside [ ], the index starts from 0. Touple
simpleList = ("red",
Tuple: Tuples are used to store multiple items in a single variable in an "green", "blue", 4, 5, 6)
immutable/unchangeable ordered sequence. Items are separated by a comma and print(type(simpleList))
defined by (), functions same as a list but values can not be changed.
Set
Set: set is a collection of unordered, unchangeable, and unindexed unique items. simpleSet = {4,2,5,8,1}
print(type(simpleSet))
The items are separated by a comma and inside {}
Note
Learn.sandipdas.in
Data Types
We can use
"type()"
ck
function to che
type of ay
Example
variable
Boolean
Dictionary(dict)
05 Mapping Type: Dictionary(dict) person = {
Dictionaries are used to store data values in key:value pairs. "name": "Sandip",
"age": 30,
"location" : "Kolkata"
}
print(type(person))
print(type(person['name']))
print(type(person["age"]))
Learn.sandipdas.in
01 Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations
Addition (+), Subtraction (-), Multiplication(*), Division (/), Modulus (%), Exponentiation(**), Floor division (//)
e.g. a+b , a-b, a*b, a/b etc
02 Comparison Operators
Comparison operators are used to compare two values
Equal(==), Not equal (!=), Greater Than (>), Less Than (<), Greater that equal (>=), Less than equal (<=)
e.g. a==b, a!=b, a>b, a<c, a>=b, a<=b, etc
Logic Table
03 Logical Operators
Logical operators are used to combine conditional statements
True if both statements are true (and), True if one of the statements is true (or),
Reverse the result, returns False if the result is true (not)
e.g. a > 5 and a<10 , a == 20 or a = 30 , not (a < 10 & a > 7)
04 Identity Operators
Identity operators are used to compare the objects
True if both variables are the same object (is), True if both variables are not the
same object (is not)
e.g. a is b, a is not b
Learn.sandipdas.in
Python Operators
05 Membership Operators
Membership operators are used to test if a sequence is presented in an object
True if a sequence with the specified value is present in the object, e.g. x in y, x not in y
06 Bitwise Operators
AND (&), OR (|), XOR (^), NOT (~), Zero fill left shift (<<), Signed right shift,(>>)
e.g. x & y = 0 , x | y = 14, ~x = -11
07 Assignment Operators
assignment operators are used to assigning values to variables
=, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=
e.g: x = 5, x += 3 (equivalent to x = x + 3) etc
Learn.sandipdas.in
If...else... Statement
When to use?
When have to execute a code only if certain condition matches / satisfies
If condition
Python relies on indentation (whitespace at the beginning of a line) to define the scope in the code, if not done properly, will throw an error
a = 10
b = 15
if b > a:
print("b is greater than a")
else
Elif The else keyword catches anything which
isn't caught by the preceding conditions.
The elif keyword is pythons way of saying "if the previous conditions were not true, then
a = 20
try this condition".
b = 10
a = 10
if b > a:
b = 10
print("b is greater than a")
if b > a:
elif a == b:
print("b is greater than a")
print("a and b are equal")
elif a == b:
else:
print("a and b are equal")
print("a is greater than b")
Learn.sandipdas.in
For Loop
Example
normal
colors = ["red", "green", "blue"]
for x in colors:
A for loop in python is used for iterating over a sequence (list, a tuple, a dictionary, a print(x)
for x in range(20):
To loop through a set of code a specified number of times, we can use the range()
print(x)
function (it start from 0)
Learn.sandipdas.in
While Loop
Example
normal
i=0
while i < 10:
The while loop we can iterate & execute a set of statements as long as an expression print(i)
(condition) is true. i += 1
Break statement
i=1
Break Statement while i < 10:
print(i)
break statement can stop the loop even if the while condition is true
if i == 5:
break
i += 1
Continue Statement Continue Statement
i=0
continue statement can stop the current iteration, and continue with the next while i < 10:
i += 1
if i == 5:
continue
print(i)
he else statement we can run a block of code once when the condition no longer is while i < 10:
print(i)
true
i += 1
else:
print("i is no longer less than 10")
Learn.sandipdas.in
Functions Example
What is a function ? defining a function
A function is a block of code that only runs when it is called. def my_hello_world_function():
print("Hello World from a
We can pass data, known as parameters, into a function and a function can return data function")
as a result.
Calling a function
In Python, we can define a function using def keyword
my_hello_world_function()
Calling a function Passing single parameter
We can call/execute a function by function name followed by parenthesis def greet_person(name):
print("Hi "+ name)
Passing Argumets
Passing multiple parameter
Information/Data can be passed into functions as arguments ad arguments can be def greet_full_name(first_name, last_name):
print("Hi "+ first_name + " " + last_name)
named arguments inside the parentheses, separated by a comma
Arbitrary Arguments
If not sure about how much argument will be there, add * before the parameter name,
def my_colours(*colours):
called Arbitrary Arguments. print("The first colours is " + colours[0])
If want named arguments but are not sure how many arguments could be there, then my_colours("Red", "Green", "Blue")
use ** before the parameter name, called Arbitrary Keyword Arguments Arbitrary Keyword Arguments
Modules Example
What is a Module in Python?
Module in Python is a file containing Python functions, statements and definitions, just
like a code library.
There are two types of Module
Types of Modules 1) System Module Using System Module
import platform
2) Custom Module
x = platform.system()
System Module print(x)
There are several built-in modules in Python, that come default with Python. we can use custom_module_example.py
the system module by using the import statement. Click here to check the full list def greet_person(name):
print("Hello, " + name)
Custom Module custom_module_useage_example.py
We can use modules to break down large programs into small manageable import custom_module_example
custom_module_example.greet_person("Sandip")
and organized files and furthermore modules provide reusability of code.
Alias example
To create a custom module, first, have to write code and save the file with .py import custom_module_example as cme
extension a = cme.personExample["age"]
print(a)
Then to use the module we just created, by using the import statement
Use dir() function
We can also utilize variables and use the "as" keyword to import modules import custom_module_example
with an alias x = dir(custom_module_example)
print(x)
We use dir() function to get all the variables and functions
Learn.sandipdas.in
Try..Except.. Example
Exception Handling in Python Simple Error Handlling
We as programmers make mistakes while writing programs, python program terminates as print("Handling simple error")
try:
soon as it encounters such errors, to prevent that we have to use exception handling. print(x)
In Python, these exceptions can be handled using the try ... except... statement except:
print("An exception occurred")
Finally
The final block will be executed regardless if the try block raises an error or not.
Learn.sandipdas.in
Contact Me
[email protected]
Support My Work
Via Patreon: https://www.patreon.com/learnwithsandip