Python for DevOps
Week 1: Python Fundamentals
(cont.)
Agenda
● Loop (cont.)
● Module
● Package management
Loops (cont.)
● Range function: range([int start], int stop, [int step])
○ Start: (default = 0) The sequence start from this number.
○ Stop*: (required) The sequence stop before this number.
○ Step: (default=1) The difference between current and next
number in sequence.
● Example:
○ range(0,10,2) -> sequence is 0,2,4,6,8
○ range(7,12) -> sequence is 7,8,9,10,11
● Note:
○ range(10,2) -> sequence is empty. Default sequence cannot
decrease. Or if you want step=2, must define the start.
Boolean
● A data type. Only have 2 values: “True” and “False”
○ a = True
○ b = False
● Other data types as boolean:
Data type Value True/False Data type Value True/False
int / float not 0 True array emtpy [] False
Int / float 0 False array Not empty True
string empty “” False None Not defined False
string Not emtpty True
Exercise
● Write code that will do the following work:
○ Input ”n” as number of people.
○ Input ages of n people.
○ Ticket price is:
■ 100$ / 1 adult, 18 to 60 years old.
■ 25$/ 1 children, which is younger than 18.
■ 50$/1 person, which is older than 60.
○ Calculate the total money of those people’s tickets.
Modules
● Module is a file, containing statements and definitions only.
● Module can be called by keyword “from/import” and rename it
by “as”.
● Module in sub-directory be call as “[Link]”.
Modules
● Try not to name your module the same as default module: os,
random, math, time, sys, collections.
● A module can be imported multiple times.
Packages
● Like modules, a Python package contains definition that can be
reused. Module is a file, Package is a directory.
● Package contain sub-packages and modules.
● Import usage like modules.
● Package must have a file named __init__.py
Packages
● We can re-use packages from Python Package Index (PyPI).
● Use pip to install packages from PyPI.
● Pip is a python package management.
● Virtualenv to isolate the dependencies in local development to
shared folder of machine.
Installation
● Pip install
○ curl [Link] -o [Link]
○ python [Link]
● Upgrade:
○ python -m pip install --upgrade pip
● Usage:
○ pip install <package-name>
● Virtualenv usage:
○ pip install virtualenv
○ python -m virtualenv .venv
○ source .venv/bin/activate
Pip
● List all current package:
○ pip freeze
● Install specific version
○ pip install <package-name>==<version>
○ You can use >= or ~=
● Install many packages listed in file [Link]
○ pip install –r [Link]
Homework
● Writing a program that let user guess a secret number:
○ Using random package to generate a number.
○ User only has 5 tries to guess.
○ If it lower than the secret_number: print that user’s number is
lower.
○ If it higher than the secret_number: print that user’s number is
higher.
○ If user guess no more than 5 tries, they win the game.