Day 58: Using Progress Bars In The Shell (Module)

 

The module ProgressBar generates timed progress bars in the terminal while you execute a program.

 

A progress bar is seldomly really necessary but sometimes it is just neat to display some progress for the user

 

You can find the documentation here

 

An easy example:

 

from time import sleep                          # to use the timer
from progressbar import ProgressBar             # progressbar module


print("Multiplying 987.000 * 1.210.100")        

num = 987000 * 1210100


bar = ProgressBar()                         
for i in bar(range(100)):
    sleep(0.01)
    bar.update(i)

print("Result: " + str(num))

And this is what it looks like in the terminal:

 

Day 57: Get Global Weather Data with OpenWeatherMap (Module)

 

OpenWeatherMap provides free weather data for every city worldwide.

 

#Takes the name of a city and delivers
# weather data via OpenWeatherMap

import pyowm               # OpenWeatherMap-module for python

owm = pyowm.OWM('a22ec5378101af24d94fb76fexxxxx')  # You MUST provide your own API key - this one will not work

city = input("Weather forecast: (Enter City): ")


# Search for current weather in city via OWM
observation = owm.weather_at_place(city)
w = observation.get_weather()

print(city.capitalize())
# extract and print the various data
get_str = str(w)
stat = get_str.find('status') + 7
print("Condition: " + get_str[stat:-1])

tempe = w.get_temperature('celsius')

print("Celsius: " + str(tempe['temp']))

print("Humidity: " + str(w.get_humidity()))

speed = w.get_wind()

print("Wind: " + str(speed['speed']) + " kph")

Day 52: The Wholesome World Of Dictionaries

# dictionaries
import collections
# creating a dictionary
data = {"first" : "Linus", "last" : "of Paros"}

# add keys and values
data["age"] = 3
data["job"] = "Dog"

print(data)                     # {'first': 'Linus', 'last': 'of Paros', 'age': 3, 'job': 'Dog'}

#retrieving values
print(data["first"])            # Linus

print(data["first"] + " " + data["last"] + " is a " + data["job"] ) # Linus of Paros is a Dog

# check if a key is in the dict with in operator
print("first" in data)          # True
print("car" in data)            # False

# with get you can set a default in case a key is not found in a dict
shortcut = data.get("address", "unknown")

print(shortcut)                 # unknown

# remove keys and values
numbers = {"1" : "true", "2" : "false","2" : "false", "3" : "true"}

del numbers["2"]

print(numbers)                  # {'1': 'true', '3': 'true'}

# iterating over dictionaries
age = {"Don" : 55, "Cindy" : 52, "James" : 42, "Sara" : 35}

for name in age:
    print(name)                 # Don, Cindy, James, Sara

for name in age.values():
    print(name)                 # 55, 52, 42, 35

Day 50: Iteration Examples

# Iteration examples

# get the average length of items in the list
list = ["Sara", "Christiano", "Dorothy", "Pete", "Peter"]
list.append("Robert")
average = 0

for name in list:
    average += len(name)                 # adds the length of every item to average

average_length = average / len(list)
print("The average length is: " + str(average_length))      #   ...length is: 6.0

# find an item in list
if "Sara" in list:
    print("found Sara")                 # found Sara
else:
    print("Not found")

if "Tucker" in list:
    print("found Tucker")
else:
    print("Not found")                  # Not found

# iterating with while loops

n = 10
numb = []
while n > 0:
    numb.append(n)
    n -= 1

print(numb)                     # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Day 44: Lists, Sets and Tuples

# list - holds a list of objects
# can be of any type and mix them
# lists are mutable

names = []                      # create an empty list
names_1 = ["Harvey", "Charles"] # create a populated list

# with list a string will return as individual chars
custom_list = list("Robert")

print(custom_list)              # ['R', 'o', 'b', 'e', 'r', 't']

# get specific items with index (index starts at 0)
print(names_1[0])               # Harvey
print(names_1[1])               # Charles

#list insertion

#insert an item with index
names_1.insert(1, "Dave")
print(names_1)                  # ['Harvey', 'Dave', 'Charles']

#append an item at the end of the list
names_1.append("Clara")
print(names_1)                  # ['Harvey', 'Dave', 'Charles', 'Clara']

#replace an item with index
names_1[1] = "Sophie"
print(names_1)                  # ['Harvey', 'Sophie', 'Charles', 'Clara']

# delete an list item
#1
names_1.remove("Harvey")
print(names_1)                  # ['Sophie', 'Charles', 'Clara']

#2
del names_1[2]
print(names_1)                  # ['Sophie', 'Charles']

# sorting a list

# sort strings alphabetically
names_1.sort()
print(names_1)                  # ['Charles', 'Sophie']

# sort numbers
numbers = [3,2,7,-3,99]
print(numbers)                  # [3, 2, 7, -3, 99]

numbers.sort()
print(numbers)                  # [-3, 2, 3, 7, 99]

# ATTENTION: You can't sort numbers and strings in one list -> error

#example

# tuples - holds unmutable items
# tuples can't be changed
# tuples can serve as keys in dictionaries
# ideal for unchanging values like pi or 24 hours

# crate a tuple
tuple_name = ("Steven", "Alice", "Vincent")

print (tuple_name)

print(tuple_name[1])                # Alice

# cannot append to tuples

# Sets
# sets are mutable and don't care about order
# they are great to check membership, remove duplicates and are hashable

digits = [0,1,1,2,3,4,4,5,6,7,8.5,9]

digit_set =  set(digits)        # removes duplicates

print(digit_set)                # Output: {0, 1, 2, 3, 4, 5, 6, 7, 8.5, 9}

print(9 in digit_set)           # True - checks if 9 is a member of the sets

# you can add or remove other Sets
even = {2,4,6,8,10}                # note we are using {} here instead of []

odd = digit_set - even              # remove even from digit_set

print(odd)                          # Output {0, 1, 3, 5, 7, 8.5, 9}

Day 39: Converting Inches In Fractions To Millimetres

 

I am back – it’s been a week. It was an unplanned break since my son got a fever and than I got an unexpected job offer.

 

I own a very beautiful Gibson Les Paul guitar that I love very much. But the action – the distance between fret and string – is a bit too far off.

 

That is no problem because the Gibson website tells me exactly that the correct distance should be 3/64 inches! Ok. What?

 

First of all I am European. Inches are not unheard of and I know that one inch are 25.4 millimetres. But 3/64 inches? Come on!

 

Thank god for Python:

 

inches = "3/64"                                 # the inch value

slash_pos = inches.find("/") + 1                # look where the slash seperates the numbers

first_num = inches[0]                           # get the numerator
sec_num = inches[slash_pos:]                    # get the denominator

dec_inch = 1 / int(sec_num) * int(first_num)    # create a decimal inch value

get_mm = 25.4 * dec_inch                        # convert it to mm

print(inches + " inches are ""%.2f" % get_mm + " mm")  # round the float to to decimals


# Output: 3/64 inches are 1.19 mm