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)

Day 26: Elegant And Lean Python

 

Just something quick today I stumbled upon yesterday:

 

# checking if the variable name has a value
# using the most efficient way

name = input("Enter your name: ")


# this works, but dont do this
if (len(name) > 0):
    print("true")
else:
    print("false")

# this works also, but it's also bad style
if (name != ""):
    print("true")
else:
    print("false")

# This is the proper Python way
# if name has a value it checks out true automatically
if (name):
    print("true")
else:
    print("false")

Day 23: Dir, Help And Pdb – Make Use Of Pythons Little Helpers

 

The shell command dir lists all attributes an object has – and remember everything in Python is an object.

Start your terminal and enter „python“ to start the IDLE mode. Then type for example dir(‚linus‘) and you will

get all the attributes for „linus“ which in this case is a string.

 

 

Pretty neat isn’t it? But that’s not all Python will do for you. The help-function will deliver even deeper information

about other functions. We can use it on the command ‚linus‘.lower for example like this:

 

help(‚linus‘.lower)

 

Here is the output:

 

 

The help-function returns information about virtually everything in Python.

 

Your Python comes with its own Docs installed – amazing!

 

And there is even more you say? Yes indeed! With pdb Python has its own integrated debugger!

 

With the debugger you can go through your code line by line and look up any possible bugs!

 

To use pdb you will have to include the following lines in the code.

 

import pdb

pdb.set_trace()

 

Once you run the program the execution will stop once the interpreter comes across the pdb.set_trace() command.

You will be redirected to the shell where you can go through every line manually and see how your

code behaves. With „n“ or „next“ you can jump to the next line of code.

 

pdb can do a lot more for you actually. You find the complete documentation here

 

 

 

Day 21: A String Of Events – Some Basic String Consideration

 

Just some basic string paradigms. Explanation in comments

 

name =  "Robert"
age = 42

print("{} is {}".format(name, age))   # Output: Robert is 42


print("Name: {:*^22}".format("Ringo"))  # Output: ********Ringo*********

(5).conjugate()         # 5 needs to be in parantheses. Otherwise Python confuses the . with a float

filename = "hello.py"

# fyi: we use lower() to catch unformated user input
print(filename.lower().endswith(".java"))     # returns False
print(filename.lower().endswith(".py"))       # returns True

print(filename.lower().startswith("world"))   # return False
print(filename.lower().startswith("hello"))   # return True

print(filename.find("py"))                    # returns 6 - the index of "p"

print(filename.find("java"))                  # returns -1

Day 20: A Very Simple Music Player In Python

 

We use pyglet to play an mp3-file – this is a very simple example.

The player has no controls – I just wanted to make a point and play a Music-File from the Shell

We need AVBin installed on the computer to decode the MP3-File

 

#! A very simple Music player
# Pyglet handles the playing of the audio files
# we need AVBin to decode the mp3 file 
# otherwise we get an error

import pyglet           

music = pyglet.resource.media('music.mp3')  # get the media file
music.play()

pyglet.app.run()

Day 19: Count the Raven how many words?

This little script delivers the number of words in a text-file.

Our example uses the poem „The Raven“ by Edgar Allen Poe

but the program works for any .txt-File.

 

#! Count words in a .txt file
# open a given txt-file and read it line by line
# split the words from the string with line.split()

import os
num_words = 0

with open("the_raven.txt", 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)

print("Number of words:")           # Output: Number of words:
print(num_words)                    # Output: 1067

Day 13/14: Cracking the Code – the string maketrans function

 

In this episode we are cracking one challenge from the amazon Python Challenge

 

In entry two there is a encrypted code that needs some cracking!

If you look closely at the string you notice that all letters are shifted by two. Instead of „abc“ its „cde“ and so on.

To crack this code we use the maketrans-function.

 

Here is the code:

import string

raw = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle grgl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."

# the maketrans function transforms our coded string with a new set of letters
table = string.maketrans(
    "abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab"
)

# setting up the decoded string for printing.
result = raw.translate(table)

print(result)

The output looks like this:

 

Day 12: Do It Like The Greeks – Basic Arithmetic Operations In Python

 

Today just some samples of basic operation and their output on the shell.

 

print(type(1))      # class "int"
print(type(2.45))   # class "float"

#ADDITION
print(2 + 3.5)      # 5.5 <-- int gets converted to float auto


number = 5
number += 4         # 9 <-- number =  number + 4

print(number)

print(.4+.01)       # 0.4100000000003 <-- float will have some rounding error

#SUBSTRACTION
print(2 - 3.5)      # -1.5

#MULTIPLICATION
print(6 * 2)        # 12
print(6 * .25)      # 1.5
print(4.5 * 2.3)    # 10.35

#DIVISION
print(12 / 4)       # 3
print(3 / 4)        # 0.75 <-- output is a float
print(3 // 6)       # 0 integer division

#MODULO
print(4 % 3)        # 1
print(3 % 2)        # 1 <-- odd number
print(6 % 3)        # 0 <-- even number

#POWER
print(4 ** 2)       # 16
print(4 ** 6)       # 4096

#ORDER OF OPERATION
print(3 + 6 * 2)    # 15 <-- * and / before + and -
print((3 + 6) * 2)  # 18 <-- paranthesises come before * and /
print(((3 / 2) + 6 * .5) * 2)   # 9.0