# Functions
# declaring a Function
# if there is no return in the Functions
# python will return the last command line
def func(para1, para2):
''' explain what happens here '''
sum = para1 + para2 # variables declared inside functions are local
return sum
#calling a function
sum = func(13,5) # 18 this sum is not related to the sum-variable in the function
print(sum)
#using default parameters
def def_func(x, y=3): # y=3 is a default parameter
return x + y
print(def_func(2)) # 5 - the function will use the default parameter
print(def_func(5,8)) # 13 - default parameters can be overwritten
# Examples:
def is_odd(num):
''' returns true if number is odd '''
if (num % 2 == 0):
return True
else:
return False
print(is_odd(4)) # True
def is_prime(x):
''' checks if number is prime '''
''' only natural number bigger 1 can be considered primes '''
if (x > 1):
return all(x % i for i in range(2, x))
else:
return False # if number is 1 or less
print(is_prime(3)) # True
Autor: robert
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
Day 31: Conditionals And If-Statements
# Conditionals in Python:
# < less than
# > greater than
# <= equal or less
# >= equal or greater
# == equal to
# != not equal to
# is identical object
# is not Not identical object
number = input("Enter a number: ")
if (int(number)%2 == 0):
print("Number is even")
else:
print("Number is odd")
# the conditionals 'is' and 'is not'
name_1 = "matt"
name_2 = "tim"
name_3 = name_1
if (name_1 is name_3): # statement is true
print("The same object!")
if (name_1 is not name_2): # this statement is also true
print("Two different objects!")
score = 78
if (score > 90):
grade = "A"
elif (score > 80):
grade = "B"
elif (score > 70):
grade = "C"
else:
grade = "Failed"
print(grade) # C
# combining conditionals
name = "Duff"
gunsnroses = False
if (name == "axl" or
name == "slash" or
name == "Duff" or
name == "steven" or
name == "izzy"):
gunsnroses = True
print(gunsnroses) # true
else:
gunsnroses = False
print(gunsnroses)
# a more efficent way to do the above
gunner = False
gnr = {"Axl", "Duff", "Steven", "Izzy", "Slash"}
gunner = name in gnr
print(gunner) # true
Day 28: A Simple Password Generator With random.choice()
What is the most elegant way to choose a random char from a string, list or tuple?
It’s random.choice(some_string)
I build a simple password generator that will build a password the length the user has chosen.
If the length is smaller than 8 though the user will have to redo his entry.
This is what the output looks like:
This is what the code looks like:
# A simple password generator
# creates a random String
# will ask anew if length was too short
import random
# the string contains all the chars we want to use.
alphabet = "1234567890abcdefghijklmnopqrstuvwxyz!@#$%^&<>?ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def pass_gen(pass_length):
i = 1
password = ""
if (int(pass_length) >= 8):
while i <= int(pass_length):
# random.choice() is the shortest and lean way
# to select a random char from a string, list or tuple
password = password + random.choice(alphabet)
i += 1
else:
pass_gen(input("Chosen length too short. Enter a length (min 8): "))
print(password)
pass_gen(input("Enter the maximum length of your password (min 8): "))
You find more information about random.choice() here.
Day 27: Renaming Image Files And Photos Bulkwise With Python
One of my most dreaded tasks on the computer is the renaming of images. When I import them from the digicam they’re usually just numbered.
I like to name my photos with a concrete name. For example „rome_2015“ or „linus“ when I have taken images of my dog. The images also get a numbered index 01,02,03,aso.
Well it’s dreaded not anymore because I wrote a little Python script that will do all the tedious work for me in an instance.
Not only do we rename the images, the program will also detect other files (like system files) and leave them untouched.
Here is a before and after:
To do this the python script needs to know the directory where the photos are located, the desired filename and what file type we like to change (.jpg)
Here is the code (the comments explain the function line by line)
import os
directory = "img/" # get the image-directory
absolute_dir = os.getcwd() # get your current working dir
complete_dir = absolute_dir + "/" + directory # built a complete path to the images
#if you would need the desktop dir on mac - use the line below
#complete_dir = os.path.expanduser("~/Desktop/test/")
num_of_files = 0 # set counter for image-numbers
name = "linus" # what you want to name you images
# go through every file in given dir
for filename in os.listdir(complete_dir):
if filename.endswith(".jpg"): # only operate on .jpg files, can be changed to any filetype
num_of_files += 1 # thats the number we indes our fotos with
new_name = name + "_" + str(num_of_files) + ".jpg" # build the new file name
# rename the file, we need complete_dir here because
# listdir and rename work on different (absolute and increment) directorys
# otherwise we will get an error
os.rename(complete_dir + filename, complete_dir + new_name)