Python homework part.3

Python homework part.3

Pythonlogo

Soooo... I sort of got lost in doing the exercises and completed 15 exercises since the last one. I think I'll just post the more demanding ones so there will be between one to two examples of what I did per subject. I'll include some screenshots again on how the programs functioned. I've only got two subjects left after these ones. I hope I can manage to complete them today. First up is sub-functions.

Sub-functions

I'm not sure if this is the "right" term for the subject. The course material is in Finnish so some terminology might translate a bit weird. I think I'll only add one example from this set of exercises. These were pretty easy and simple so there is no use in showing the really basic ones.'

The program characters takes the user input, runs it through a function and returns the length of the word. I edited some stuff for the screenshot again. The returned code needs to be in Finnish but my posts here will be in English so I just find it more logical to have the screenshots be in English. If you can read the code the output language shouldn't matter.

wordlenreturn

 

def testlength(userword):
    wordlength = userword
    wordlength = len(userword)
    return wordlength
def main():
    gucci = True
    while gucci:
        userword = input("Anna syöte (Lopeta lopettaa): ")
        if userword == "Lopeta":
            gucci = False
        elif userword =="":
            print("Et antanut syötettä")
        else:
            print("Antamasi syöte oli",testlength(userword),"merkkiä pitkä.")

if __name__ == "__main__":
    main()

Importing libraries

A pretty basic part of python, I was familiar with "importing" both from my Java course and from stuff I've done previously. I'll show three exercises from this subject.

The first one is a funny little rock, paper, scissors simulator with the basic elements of the game swapped to "foot, nuke, cockroach". The game takes the user input and compares it against a randomized number translated into foot, nuke or cockroach. Foot beats cockroach, cockroach beats nuke etc. The game loops until the user input is "Lopeta". I think my solution could have been a lot better. I could have put the loop in another sub-function. But this is what I ended up with.

jalkatorakka

 

import random

def kps():
    a = random.randint(1,3)
    if a == 1:
        a = "Jalka"
    elif a == 2:
        a = "Ydinase"
    elif a == 3:
        a = "Torakka"
    return a
def main():
    i = True
    round = 0
    wins = 0
    draws = 0
    losses = 0
    while i:
        round = round + 1
        computerselection = kps()
        userselection = input("Jalka, Ydinase vai Torakka? (Lopeta lopettaa): ")
        
        if userselection != "Lopeta":
            print("Sinä valitsit:", userselection)
            print("Tietokone valitsi:", kps())
            if userselection == computerselection:
                print("Tasapeli!")
                draws = draws + 1
            elif computerselection == userselection:
                print("Tasapeli!")
                draws = draws
            elif userselection == "Jalka" and computerselection == "Ydinase":
                print("Hävisit!")
                losses = losses +1
            elif userselection == "Jalka" and computerselection == "Torakka":
                print("Voitit!")
                wins = wins + 1
            elif userselection == "Ydinase" and computerselection == "Torakka":
                print("Hävisit!")
                losses = losses + 1
            elif userselection == "Ydinase" and computerselection == "Jalka":
                print("Voitit!")
                wins = wins +1
            elif userselection == "Torakka" and computerselection == "Ydinase":
                print("Voitit!")
                wins = wins + 1
            elif userselection == "Torakka" and computerselection == "Jalka":
                print("Hävisit!")
                losses = losses + 1

        elif userselection == "Lopeta":
            round = round -1
            print("Pelasit",round,"kierrosta, joista voitit", wins,"ja pelasit tasan",draws,"peliä.")
            i = False
       
if __name__ == "__main__":
    main()

The next one was a "password" testing program. It takes the user given word and checks if it has letters and numbers. The program is a "self created" module for the library already in the program that checks our code. So no screenshot for this one.

 

import re
def testaa(testattava):
    if bool(re.search("[a-zA-Z]", testattava)):
        if bool(re.search("[0-9]",testattava)):
            if len(testattava) > 5:
                    
                return True

The last two exercises were to edit both the calculator program made previously to have options to calculate both sin and cos values, and to make the notebook include date and time values on the users notes, but I'll show those functions on the next subject because the subject had us edit those programs further.

Try: and handling errors

So the last subject was the try- and except functions built into python. Try tries the code first if the code is good it executes it if not the user can choose to include the except condition to the code to handle the outcome based off the error message. I think I'll just show the last two exercises here which had to do with the previously mentioned calculator and notebook.

The task was to make the calculator first check that the input is a number and only then continue the program. If the input was something else than a number the program should return an error message and ask for a number again. I solved this by throwing the user in a value check loop which checks if the input is a number an only lets the user out of it if the condition is True. You can also see the added sin and cos functionalities below

newcalc

 

import math

def askinput():

gucci = False

while (gucci == False):

asked = input("Anna luku: ")

try:

goodasked = int(asked)

gucci = True

except:

print("Virheellinen syöte!")

return goodasked

def countsin(number, number2):

    return math.sin(number/number2) 

def countcos(number, number2):

    return math.cos(number/number2)

def main():

number = askinput()

number2 = askinput()

while(True):

print("(1) +")

print("(2) -")

print("(3) *")

print("(4) /")

print("(5) sin(luku1/luku2)")

print("(6) cos(luku1/luku2)")

print("(7) Vaihda luvut")

print("(8) Lopeta"

print("Valitut luvut: ",number, number2)

choice = int(input("Tee valinta (1-8): "))

if (choice == 1):

print("Tulos on: ", number + number2)

elif (choice == 2):

print("Tulos on: ", number - number2)

elif (choice == 3):

print("Tulos on: ", number * number2)

elif (choice == 4):

print("Tulos on: ",float(number / number2))

elif (choice == 5):

print("Tulos on: ", countsin(number, number2))

elif (choice == 6):

print("Tulos on: ", countcos(number, number2))

elif (choice == 7):

number = askinput()

number2 = askinput()

elif (choice == 8):

break

else:

print("Valintaa ei tunnistettu.")

 

if __name__ == "__main__":

    main()  

The last one I'll show was the edited notebook. The task here was to have the notebook first test whether the default notebook called "muistio.txt" exists, if untrue the program creates the notebook. Also we were to make it so that the user could swap notebooks while using the program. My solution to the first puzzle was to run the testNote() function first which reads.

 

try:

testNote()

except IOError:

print("Oletusmuistiota ei löydy, luodaan tiedosto.")

createDefNote()

 

def testNote():

file = open("muistio.txt","r")

file.close()

It tests if the notebook exists. If not the except was to run a function called createDefNote()

 

def createDefNote():

file = open("muistio.txt","w")

file.close()

Pretty simple and effective.

The second "puzzle" was to have an option to swap notebooks. If said notebook does not exist the program creates one with the name the user gave.

 

elif userselection == 4:

newBooknote()

start = False

 

def newBooknote():

filename = input("Anna tiedoston nimi: ")

try:

file = open(filename,"r")

file.close()

usernamedLoop(filename)

except IOError:

print("Tiedostoa ei löydy, luodaan tiedosto.")

file = open(filename,"w")

file.close()

usernamedLoop(filename)

The program then throws the user in a new notebook loop which is named after the name the user gave the notebook

 

def usernamedLoop(filename):

stert = True

while stert:

print("Käytetään muistiota", filename)

print("(1) Lue muistikirjaa\n(2) Lisää merkintä\n(3) Tyhjennä muistikirja\n(4) Vaihda muistiota\n(5) Lopeta")

userselection = int(input("Mitä haluat tehdä? : "))

if userselection == 1:

file = open(filename,"r")

content = file.readlines()

for i in content:

print(i, end = "")

print("\n")

file.close()

elif userselection == 2:

file = open(filename,"a")

addText = "\n" + input("Lisää merkintä: ") + ":::" + addTime()

file.write(addText)

 

file.close()

 

elif userselection == 3:

file = open(filename,"w")

file.close()

print("Muistio tyhjennetty.")

 

elif userselection == 4:

newBooknote()

stert = False

 

elif userselection == 5:

print("Lopetetaan.")

stert = False

 

thisworks

I don't know if this is the prettiest solution to this problem. I feel like I could have combined the loops in to one simple notebook loop with the notebook name being a variable with an if-condition maybe. But I felt quite proud of my solution nevertheless. For the amount of time I've been coding I feel like I've improved a lot.

Sources:

  • Picture: https://commons.wikimedia.org/wiki/File:Python_icon_(black_and_white).svg