from hashlib import pbkdf2_hmac
lower_case = list("abcdefghijklmnopqrstuvwxyz")
upper_case = list("ABCDEFGHJKLMNOPQRTUVWXYZ")
numbers = list("0123456789")
special_char = list("!§$%&/()=?[],.-")
password_chars = lower_case + upper_case + numbers + special_char
salt = "pepper"
def convert_bytes_to_password(hashed_bytes, length):
number = int.from_bytes(hashed_bytes, byteorder="big")
password = ""
while number > 0 and len(password) < length:
password = password + password_chars[number % len(password_chars)]
number = number // len(password_chars)
return password
master_password = input("Master Password: ")
domain = input("Website: ")
while len(domain) < 1:
print("Enter a Website you want to generate the password for: ")
domain = input("Website: ")
hash_string = domain + master_password
hashed_bytes = pbkdf2_hmac("sha512",
hash_string.encode("utf-8"),
salt.encode("utf-8"),
4096)
print("Passwort: " + convert_bytes_to_password(hashed_bytes, 10))
Kategorie: Basics
Day 67: Read A Binary File
Day 66: Being A Scribe – Read From And Write To Files
# Read and write files
# open the file with 'write'-mode
test_file = open("files_test.txt", "r")
# full list of file modes
# "w" - write text file (overwrite possible)
# "r" - read text file
# 'x' - write text file (includes error is file exists)
# 'a' - append to end of file
# 'rb' - read binary files
# 'wb' - write binary
# 'w+b' - read and write binary file
# 'xb' - write binary file (includes error is file exists)
# 'ab' - append to end of binary file
# Read files
print(test_file.read()) # This is a test - full text
# Read one line
print(test_file.readline()) # This is a test - one line
# iterate over text files
for line in test_file:
print(line) # This is a test - all lines
# readline() is not very well suited to iterate over big files
# close files - you should alway close a file after using it!!!
test_file.close()
# Write to files
texty = open("files_test.txt", 'w')
texty.write("11 This is a test\n")
print(texty.read())
texty.close()
Day 63: Indexing And Slicing
# Indexing
# note: sets can't be indexed
my_guitars = ["Gibson Les Paul", "Ibanez RG", "Fender Stratocaster"]
print(my_guitars[0]) # Gibson Les Paul
# Python allows negative indexing. -1 returns the last item aso
print(my_guitars[-1]) # Fender Stratocaster
print(my_guitars[-2]) # Ibanez RG
# indexing a tuple
print(("Marshall", "Laney", "Orange")[1]) # Laney
# indexing a string
print("Wampler"[3]) # p - index starts at 0
# slicing
print(my_guitars[0:2]) # ['Gibson Les Paul', 'Ibanez RG']
# note: the first index is optional. negative indexing works here as well
print(my_guitars[:2]) # ['Gibson Les Paul', 'Ibanez RG']
print(my_guitars[:-1]) # ['Gibson Les Paul', 'Ibanez RG']
#Examples
# get first and last letter
name = "Robert"
print(name[0]) # R
print(name[-1]) # t
# delete the file extension
filename = "document.txt"
print(filename[0:-4]) # document
Day 61: Functions Overview
# 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
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