Skip to content

Instantly share code, notes, and snippets.

@JanneSalokoski
Last active August 29, 2015 14:09
Show Gist options
  • Save JanneSalokoski/31dbe8c46b7c4c3e9062 to your computer and use it in GitHub Desktop.
Save JanneSalokoski/31dbe8c46b7c4c3e9062 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
###
# Copyright (c) 2014, Janne Salokoski
# All rights reserved.
###
"""
Performs all the tasks for the AT04 course
in Kouvolan Yhteiskoulun Lukio. (2014)
Doesn't care about the assumed skill level
of the task, just does at least the required.
"""
# Do all the imports.
import re
import sys
import json
import math
import datetime
# Define all the global variables. (As if they were truly globals.)
_debug_ = False # Apparently you can't use __debug__ in python.
_logUser_ = True # Whether to store given data about the user.
_lan_ = "FI"
logs = ["log.txt"]
# Define the classes not directly related to the tasks.
class users:
"""Stores info about the user."""
def __init__(self, data):
self.data = data
self.database = [] # A list for storing users' data.
def addData(self, data):
"""Adds data to the users table"""
self.database.append(data)
author = users("Janne") # Some information about the author, just in case.
author.addData("Name: Janne Salokoski")
author.addData("E-mail: [email protected]")
class logging: # For possible fancy cath/try error handling system.
"""Some logging tools."""
def __init__(self):
self.data = [] # Do I even need this?
def newEntry(self, string, logID = 0):
"""Writes a new log entry."""
f = open(logs[logID], "a")
f.write("[" + str(datetime.datetime.now()) + "] " + string + "\n")
f.close()
def newLog(self, name):
"""Initializes a new log."""
logs.append(name)
def flush(self, logID = 0):
"""Remove all the content from the given log."""
f = open(logs[logID], "w")
f.flush()
f.close()
class utilities:
"""Tools for miscellanious operations."""
def __init__(self):
self.data = [] #Why am I doing this?
def checkFormat(self, string, stirngFormat):
"""Check if the string matches given format."""
if string.find(stringFormat) != -1:
return True
else:
return False
string = str(string)
log.newEntry("\"" + string + "\" didn't match the given format.")
def checkType(self, string, stringType):
"""Checks if the string is the given type"""
if (stringType != "str" and
stringType != "int" and
stringType != "float"):
print("Invalid type given.")
log = logging()
log.newEntry("Invalid type given.")
else:
if str(type(string)).find("int") != -1:
return True
else:
return False
string = str(string)
log = logging()
log.newEntry("\"" + string + "\" was not the given type.")
def start(self, name, prompt = True):
"""Prints out a nice ASCII box for the name of the thask"""
if prompt == True:
input("\nJatka painamalle 'enter'.\n")
length = len(name)
wordLength = length
if length > 20:
length = length + 2
print("|", end="")
for i in range(0, length):
print("-", end="")
print("|")
print("| " + name + " |")
print("|", end="")
for i in range(0, length):
print("-", end="")
print("|\n")
else:
space = int((20 - wordLength) / 2)
if int((20 - wordLength) % 2) == 0:
print("|--------------------|\n|", end="")
for i in range(0, space):
print(" ", end="")
print(name, end="")
for i in range(0, space):
print(" ", end="")
print("|\n|--------------------|\n")
else:
print("|--------------------|\n|", end="")
for i in range(0, space):
print(" ", end="")
print(" " + name, end="")
for i in range(0, space):
print(" ", end="")
print("|\n|--------------------|\n")
def safeRun(self, function):
"""Run the program in a safe environment"""
try:
# function # This actually might not do anything due to the
# architecture of the program, but let's just leave it
# here for now.
pass
except ValueError:
if _lan_ == "EN":
print("There was a value error (wrong type of data).")
print("Let's try again.")
elif _lan_ == "FI":
print("Tapahtui arvovirhe (väärä datatyyppi).")
print("Yritetään uudelleen.")
log.newEntry("There was a value error:")
log.newEntry(sys.exc_info()[0])
except:
if _lan_ == "EN":
print("There was an unexcepted exception.")
print("Let's try again.")
elif _lan_ == "FI":
print("Tapahtui odottamaton virhe.")
print("Yritetään uudelleen.")
log.newEntry("There was an unexcepted exception:")
log.newEntry(sys.exc_info()[0])
def processHetu(self, hetu):
"""Extracts your birthdate, age and gender from the hetu."""
hetu = str(hetu)
birth = hetu[0:6]
separator = hetu[6]
random = hetu[7:10]
check = hetu[10]
months = [
"tammi", "helmi", "maalis", "huhti"
"touko", "kesä", "heinä", "elo",
"syys", "loka", "marras", "joulu"
]
alphabets = [
"A", "B", "C", "D", "E", "F", "H", "J", "K", "L",
"M","N", "P", "R", "S", "T", "U", "V", "W", "X", "Y"
]
bDay = birth[:2] # 'b' for birth.
if bDay[0] == "0":
bDay = bDay[1]
bMonth = str(months[int(int(birth[2:4]) - 2)]) + "kuu"
if separator == "-":
yearStart = "19"
elif separator == "A":
yearStart = "20"
else:
yearStart = "00"
# print("yearStart: " + yearStart) # DEBUG!
bYear = str(yearStart) + birth[4:]
# print("bYear: " + bYear) # DEBUG!
cYear = datetime.date.today().year # 'c' for current.
cMonth = datetime.date.today().month
cDay = datetime.date.today().day
years = cYear - int(bYear)
months = cMonth - int(birth[2:4])
days = cDay - int(bDay)
# print("Years: " + str(years))
# print("Months: " + str(months))
# print("Days: " + str(days))
if months < 0 or days < 0:
age = years - 1
else:
age = years
# print("Age: " + str(age)) # DEBUG!
checksum = int(str(int(birth)) + str(int(random))) % 31
if len(str(checksum)) == 1:
confirmation = checksum
elif len(str(checksum)) == 2:
confirmation = alphabets[checksum - 10]
if str(confirmation) == str(check):
correct = True
else:
correct = False
log = logging()
log.newEntry("Given henkikötunnus is incorrect.")
# If to print the message here, do so.
# print("Given henkikötunnus is incorrect.")
if int(random) % 2 == 0:
gender = "nainen"
else:
gender = "mies"
# Store the information about the user!
return bYear, bMonth, birth[2:4], bDay, age,
# Now we may do the actual tasks.
# The idea is to have each task on its own class. __init__() doing
# the task. Docstring should contain the assignment.
# Luento 2:
class muuttuja:
"""Defines variables and prints them"""
def __init__(self):
utilities().start("2.1: Muuttuja", False)
n = 2
string = "Täältä pesee"
print(n)
print(string)
class kokonaisluvut:
"""Asks for two integers, and prints their sum."""
def __init__(self):
utilities().start("2.2: Kokonaislukumuuttujien käyttö")
#x = int(input("Anna kokonaisluku: "))
#y = int(input("Anna toinen kokonaisluku: "))
x = input("Anna kokonaisluku: ")
y = input("Anna toinen kokonaisluku: ")
try:
x = int(x)
y = int(y)
if(utilities().checkType(x, "int") == True and
utilities().checkType(y, "int") == True):
print("Lukujen " + str(x) + " ja " + str(y) +
" summa on " + str(x + y) + ".")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
kokonaisluvut()
class nelio:
"""Asks length of squares side and prints the perimeter and the area."""
def __init__(self):
utilities().start("2.3: Neliön kehä ja pinta-ala")
x = input("Anna neliön sivun pituus: ")
try:
x = int(x)
if utilities().checkType(x, "int") == True:
p = x*4
A = x**2
print("Neliön kehän pituus on " + str(p) +
" ja ala on " + str(A))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
nelio()
class keskiarvo:
"""Asks for three integers and counts their average."""
def __init__(self):
utilities().start("2.4: Kolmen luvun keskiarvo.")
print("Tämä ohjelma laskee antamiesi kolmen luvun keskiarvon.")
x = input("Anna luku 1: ")
y = input("Anna luku 2: ")
z = input("Anna luku 3: ")
try:
x = int(x)
y = int(y)
z = int(z)
if (utilities().checkType(x, "int") == True and
utilities().checkType(y, "int") == True and
utilities().checkType(z, "int") == True):
avg = (x + y + z) / 3
print("Lukujen keskiarvo on " + str(avg))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
keskiarvo()
class desimaaliluku:
"""Asks for a radius, rounds up the perimeter and the area."""
def __init__(self):
utilities().start("2.5: Desimaaliluvun pyöristäminen.")
x = input("Anna säteen pituus: ")
try:
r = int(x)
if utilities().checkType(r, "int") == True:
p = 2 * math.pi * r
A = math.pi * r ** 2
print("Kehän pituus on " + str(p) + " ja ala on " + str(A))
p = str(round(p, 2))
A = str(round(A, 3))
print("Kehän pituus pyöristettynä on " + p + " ja ala on " + A)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
desimaaliluku()
class merkkijonot:
"""Asks for users name, prints it forwards and backwards."""
def __init__(self):
utilities().start("2.6: Käyttäjän nimi eli merkkijonot")
x = input("Anna etunimesi: ")
y = input("Anna sukunimesi: ")
try:
etu = str(x)
suku = str(y)
print("Hei, " + etu + " " + suku)
print("Hei, " + suku + " " + etu)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
merkkijonot()
class ympyra:
"""Asks for a radius, rounds up the perimeter and the area."""
def __init__(self):
utilities().start("3.1: Ympyrän kehä ja ala")
print("Tämä ohjelma laskee ympyrän kehän ja alan " +
"antamasi säteen perusteella.")
x = input("Anna säde: ")
try:
r = int(x)
if utilities().checkType(r, "int") == True:
pi = round(math.pi, 6)
p = 2 * pi * r
A = pi * r ** 2
p = str(round(p, 2))
A = str(round(A, 2))
print("Ympyrän kehä on " + p + " ja ala on " + A)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
ympyra()
class merkkijono:
"""Asks for a string and messes with it."""
def __init__(self):
utilities().start("3.2: Merkkijono.")
x = input("Anna merkkijono: ")
try:
string = str(x)
print("Annoit merkkijonon: '" + string + "'.")
print("Merkkijono alkaa kirjaimella " + string[0] + ".")
print("Merkkijono päättyy kirjaimeen " + string[-1:] + ".")
print("Merkkijono on takaperin '" + string[::-1] + "'.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
merkkijono()
class henkilotunnus:
"""Asks for 'henkilötunnus' and counts information from it."""
def __init__(self):
utilities().start("3.3: Henkilötunnus")
x = input("Anna henkilötunnus: ")
try:
hetu = str(x)
hetu = utilities().processHetu(hetu)
# print(hetu) # DEBUG!
y = hetu[0] # y for year.
m = hetu[1]; numM = hetu[2] # m for month, numM for numeral month.
d = hetu[3] # d for day.
a = hetu[4] # a for age.
date = d + "." + numM + "." + y
print("Olet syntynyt " +
d + ". päivänä " +
m + "ta vuonna " +
y + " eli " + date + ".")
print("[Olet siis " + str(a) + " vuotias.]")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
henkilotunnus()
class hinnoittelu:
"""Asks the user parts of a price and counts the total price."""
def __init__(self):
utilities().start("3.4: Tuotteen hinnoittelu.")
x = input("Anna tuotteen ostohinta: ")
y = input("Anna kateprosentti kokonaislukuna (esim. 100): ")
z = input("Anna arvonlisäveroprosentti kokonaislukuna (esim. 23): ")
try:
oH = str(x) # oH for 'ostohinta'
kP = str(y) # kP for 'kateprosentti'
aP = str(z) # aP for 'arvonlisäveroprosentti'
oH = int(oH)
kP = int(kP)/100
aP = int(aP)/100
nH = int(oH + (oH * kP)) # nH for 'nettohinta'
bH = int(nH + (nH * aP)) # bH for 'bruttohinta'
print("Tuotteen myyntihinta on " + str(bH) +
"€, alv-vapaa hinta on " + str(nH) +
"€, alv:n osuus on " + str(bH - nH) + "€.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
merkkijono()
class kahdenLuvunVertailu:
"""Asks for two integers. Prints out the grater one."""
def __init__(self):
utilities().start("4.1: Kahden luvun vertailu.")
x = input("Anna ensimmäinen kokonaisluku: ")
y = input("Anna toinen kokonaisluku: ")
try:
x = int(x)
y = int(y)
if x == y:
print("Luvut " + str(x) + " ja " +
str(y) + " ovat yhtä suuret.")
else:
print("Suurempi luku on " + str(max(x, y)) + ".")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
kahdenLuvunVertailu()
class kolmenLuvunVertailu:
"""Asks for three integers. Prints out the gratest one."""
def __init__(self):
utilities().start("4.3: Suurin luku.")
x = input("Anna ensimmäinen kokonaisluku: ")
y = input("Anna toinen kokonaisluku: ")
z = input("Anna kolmas kokonaisluku: ")
try:
x = int(x)
y = int(y)
z = int(z)
if x == y and y == z:
print("Luvut " + str(x) + ", " + str(y) +
" ja " + str(z) + " ovat yhtä suuret.")
else:
print("Suurempi luku on " + str(max(x, y)) + ".")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
kolmenLuvunVertailu()
class valikkotulostus:
"""Asks for a string, does weird things with it,
and prints out whatever is left.""" # Cruel little function...
def __init__(self):
utilities().start("4.3: Merkkijonon tulostus valikolla.")
x = input("Anna merkkijono: ")
try:
string = str(x)
y = input("Tämä ohjelma voi tulostaa merkkijonon " +
"seuraavilla tavoilla:\n\t1) Etuperin \n\t2) Takaperin\n" +
"\t3) Lopeta\nMitä haluat tehdä: ")
try:
option = int(y)
if option == 1:
print(string)
elif option == 2:
print(string[::-1])
elif option == 3:
z = input("Oletko varma, että haluat\n" +
"\t1) lopettaa koko ohjelman, vai\n" +
"\t2) jatkaa seuraavaan tehtävään?\n" +
"Lopeta ohjelma (1) / Lopeta tehtävä (2): ")
try:
opt2 = int(z)
if opt2 == 1:
if _lan_ == "EN":
input("Press any key to exit.\nBe warned, " +
"the shutdown may not be pretty. ")
elif _lan_ == "FI":
input("Paina mitä tahansa näppäintä " +
"lopettaaksesi ohjelman.\nHuomioi, " +
"että sammuminen ei välttämättä " +
"ole kaunista katseltavaa. ")
quit() # Could just do sys.exit() and except
elif opt2 == 2: # that. Would be better practise.
pass
elif opt2 > 2:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
valikkotulostus()
except:
if _lan_ == "EN":
print("Wrong datatype.\n" +
"Please try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\n" +
"Yritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
valikkotulostus()
elif option > 3:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
valikkotulostus()
except:
if _lan_ == "EN":
print("Wrong datatype.\n Please try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\n" +
"Yritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
valikkotulostus()
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
except:
if _lan_ == "EN":
print("Wrong datatype.\nPlease try a different value.")
elif _lan_ == "FI":
print("Väärä datatyyppi.\nYritä uudelleen toisella arvolla.")
log = logging()
log.newEntry("Wrong datatype.")
valikkotulostus()
class nelilaskin:
"""A basic desktop calculator."""
def __init__(self):
utilities().start("4.4: Alustava nelilaskin.")
x = input("Anna kaksi desimaalilukua ja sen " +
"jälkeen haluamasi laskutoimitus.\n" +
"Anna ensimmäinen desimaaliluku: ")
y = input("Anna toinen desimaaliluku: ")
z = input("Minkä laskutoimituksen haluat tehdä:\n" +
"\t1. Summa\n\t2. Erotus\n\t3. Tulo\n\t4. Osamäärä\n" +
"\t5. Laskutoimitus\n\t6. Lopeta\nMitä haluat tehdä: ")
try:
x = float(x)
y = float(y)
option = int(z)
if option == 1:
print(str(x + y))
elif option == 2:
print(str(x - y))
elif option == 3:
print(str(x * y))
elif option == 4:
print(str(x / y))
elif option == 5:
i = input("Anna laskutoimitus: ")
i = eval(i)
print(i)
elif option == 6:
#Exit the program.
opt2 = input("Oletko varma, että haluat\n" +
"\t1) lopettaa koko ohjelman, vai\n" +
"\t2) jatkaa seuraavaan tehtävään?\n" +
"Lopeta ohjelma (1) / Lopeta tehtävä (2): ")
opt2 = int(opt2)
if opt2 == 1:
print("Kiitos ohjelman käytöstä!")
sys.exit(0)
elif opt2 == 2:
pass
elif opt2 > 2:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
nelilaskin()
else:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
nelilaskin()
elif option > 6:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
nelilaskin()
else:
if _lan_ == "EN":
print(str(option) + " is not an option." +
"\n Please try a different value.")
elif _lan_ == "FI":
print(str(option) + " ei ole vaihtoehto." +
"\n Yritä uudelleen toisella arvolla.")
nelilaskin()
print("Kiitos ohjelman käytöstä!")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
nelilaskin()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class peruslaskuja:
"""Does the same exact basic things we've already done, again."""
def __init__(self):
utilities().start("4.5: Peruslaskuja")
try:
# Count the perimeter of a circle.
x = input("Anna säteen pituus: ")
r = int(x)
p = 2 * math.pi * r
print("Ympyrän kehä on " + str(p) + ".")
# Count the tax-included price of a product.
y = input("Anna tuotteen alkuperäinen hinta: ")
z = input("Anna veroprosentti (esim. 24): ")
aH = int(y) # aH = alkuperäisHinta.
vP = int(z) / 100 # vP = veroProsentti.
hinta = aH + aH * vP
print("Tuotteen verollinen hinta on: " + str(hinta) + "€.")
# Count the second and third exponent of a number.
i = input("Anna luku: ")
i = float(i)
print("Luvun " + str(i) + " toinen potenssi on " + str(i**2) +
" ja kolmas " + str(i**3) + ".")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
peruslaskuja()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class lauseenmuodostus:
"""Asks the user for words and makes a sentence from them."""
def __init__(self):
utilities().start("4.6: Lauseenmuodostus")
try:
# Get a word from the user.
x = input("Anna sana: ")
sana = str(x)
print("Annoit sanan " + sana + ".")
# Get various other words from the user.
subject = str(input("Anna tekijä: ")) + " "
verb = str(input("Anna verbi: ")) + " "
numeral = str(input("Anna luku: ")) + " "
adjective = str(input("Anna adjektiivi: ")) + " "
object = str(input("Anna objekti: ")) + "."
# Construct a sentence from the words.
print(subject + verb + numeral + adjective + object)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
lauseenmuodostus()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class merkkijonoja:
"""Asks for a string and prints parts of it."""
def __init__(self):
utilities().start("4.7: Merkkijonoja")
try:
# Get a long word from the user.
x = input("Anna pitkä sana: ")
word = str(x)
print("Sanasi oli '" + word +
"' ja sen pituus merkkeinä on " + str(len(word)) + ".")
# Get the first, and the last five letters of the word.
print("Antamasi sanan viisi ensimmäistä kirjainta ovat: " +
word[:5] + ".")
print("Antamasi sanan viisi viimeistä kirjainta ovat: " +
word[-5:] + ".") # Doesn't work!
# Get the letters 2, 3, 4 and 5.
print("Kirjaimet 2, 3, 4 ja 5 ovat " +
word[1:5] + ".")
# Print every second letter of the word.
print("Sanan joka toinen kirjain alkaen toisesta kirjaimesta: " +
word[1::2] + ".")
# Print the word backwards.
print("Antamasi sana on väärinpäin kirjoitettuna '" +
word[::-1] + "'.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
merkkijonoja()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class kasittelua:
"""Asks for a word and some parameters to split the word with."""
def __init__(self):
utilities().start("4.8: Merkkijonojen ja kokonaislukujen käsittelyä.")
try:
# Get a long word from the user.
x = input("Anna pitkä sana: ")
word = str(x)
print("Sanasi oli '" + word +
"' ja sen pituus on " + str(len(word)) + " merkkiä.")
# Get the split values from the user.
y = int(input("Anna aloituspaikka: "))
z = int(input("Anna lopetuspaikka: "))
i = int(input("Anna siirtymäväli: "))
# Split the word with the users' values.
print("Antamillasi asetuksilla sana " + word +
" tulostuu näin: " + str(word[y:z:i]) + ".")
# Get a numer from the user and substract 35 from it.
# Then print the length of the result.
j = int(input("Anna luku: ")) -35
print("Erotuksessa on " + str(len(str(j))) + " numeroa.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
kasittelua()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class valintarakenne:
"""Asks for a number, tells how great it is, and is it even.
Then asks for a word and tells if it's long enough."""
def __init__(self):
utilities().start("4.9: Valintarakenne.")
try:
# Get a number from the user.
x = int(input("Anna luku: "))
# Tell if the number is lesser than 0, greater than 100, or
# in between of 0 and 100.
if x > 0 and x < 100:
print("Luku on 0:n ja 100:n väliltä.")
elif x < 0:
print("Luku on pienempi kuin 0.")
elif x > 100:
print("Luku on suurempi kuin 100.")
# Tells if the number is even.
if x % 2 == 0:
print("Antamasi luku on parillinen.")
else:
print("Antamasi luku on pariton.")
# Get a long word from the user.
y = input("Anna pitkä sana: ")
word = str(y)
# Tell if the word is long enough (<9)
if len(word) > 9:
print("Antamasi sana oli tarpeeksi pitkä, " +
str(len(word)) + " merkkiä.")
else:
print("Antamasi sana oli liian lyhyt; vain " +
str(len(word)) + " merkkiä.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
valintarakenne()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class merkkijono_operaatioita:
"""Asks for strings, and compares them in various ways."""
def __init__(self):
utilities().start("4.10: Merkkijono-operaatioita.")
try:
# Get two words from the user.
x = input("Anna ensimmäinen sana: ")
y = input("Anna toinen sana: ")
word1 = str(x)
word2 = str(y)
# Print the 'greater' word.
print("'" + min(word1, word2) + "' on pienempi kuin '" +
max(word1, word2) + "'.")
# Tell if the letter 'z' is found on the words.
if "z" in word1 and "z" in word2:
print("'z' löytyi molemmista sanoista ('" + word1 + "', '" +
word2 + "').")
elif "z" in word1:
print("'z' löytyi sanasta 1 ('" + word1 + "').")
elif "z" in word2:
print("'z' löytyi sanasta 2 ('" + word2 + "').")
else:
print("'z' ei löytynyt kummastakaan sanasta.")
# Get another word, check if it's a palindrom,
# print it backwards and forwards.
z = input("Anna testattava sana: ")
wF = str(z) # fW = word Forwards.
wB = str(z)[::-1] # wB = word Backwards.
if wF == wB:
print("Antamasi sana on palindromi.")
else:
print("Antamasi sana ei ole palindromi.")
print("Se on väärinpäin '" + wB + "' ja oikein päin '" +
wF + "'.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
merkkijono_operaatioita()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class alkuehtoinenKeskiarvo:
"""Ask for numbers as long as user gives them, count the average."""
def __init__(self):
utilities().start("5.1: Toistorakenne, alkuehtoinen keskiarvon lasku.")
try:
print("Tämä ohjelma laskee antamiesi lukujen keskiarvon.")
numbers = []
cont = True
i = 1
while cont == True:
# Get the number and store it.
x = int(input("Anna " + str(i) + ". luku: "))
numbers.append(x)
y = int(input("Anna numero 1 jos haluat antaa lisää lukuja: "))
if y == 1:
i = i + 1
else:
cont = False
print("Antamiesi lukujen keskiarvo on:", end = "\n\t(")
print(*numbers, sep = " + ", end = ") ")
print("/ " + str(i) + " = " + str(sum(numbers) / i))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
alkuehtoinenKeskiarvo()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class lopetusehtoinenKeskiarvo:
"""Ask for numbers as long as user gives them, count the average."""
def __init__(self):
utilities().start("5.2: Toistorakenne, alkuehtoinen, " +
"syöte lopetusehtona.")
try:
print("Tämä ohjelma laskee antamiesi lukujen keskiarvon.")
numbers = []
cont = True
i = 0
while cont == True:
# Get the number and store it.
x = int(input("Anna " + str(i) + ". luku (0 lopettaa): "))
if x != 0:
numbers.append(x)
i = i + 1
else:
cont = False
print("Antamiesi lukujen keskiarvo on:", end = "\n\t(")
print(*numbers, sep = " + ", end = ") ")
print("/ " + str(i) + " = " + str(sum(numbers) / i))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
lopetusehtoinenKeskiarvo()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class alkuehtoinenMerkkiSyote:
"""Multiplies numbers as long as they keep coming."""
def __init__(self):
utilities().start("5.3: Toistorakenne, alkuehtoinen, syötteenä merkki")
try:
print("Tämä ohjelma laskee antamiesi kahden desimaaliluvun tulon." +
" Ohjelma pyytää uusia lukuja, mikäli annat pienen " +
"j-kirjaimen jatkon merkiksi.")
cont = True
while cont == True:
x = int(input("Anna 1. luku: "))
y = int(input("Anna 2. luku: "))
print("Antamiesi lukujen tulo on " + str(x * y) + ".")
z = str(input("Anna kirjain 'j' jos haluat jatkaa: "))
if z != "j":
cont = False
print("Kiitos ohjelman käytöstä.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
alkuehtoinenMerkkiSyote()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class parittomat:
"""Multiplies numbers as long as they keep coming."""
def __init__(self):
utilities().start("5.4: askeltava toisto, parittomien tulostus")
try:
for i in range(1, 30, 2):
print(i)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
parittomat()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class kertoma:
"""Counts the factorial of given number"""
def __init__(self):
utilities().start("5.5: askeltava toisto, parittomien tulostus")
try:
x = int(input("Anna luku, jonka kertoma lasketaan: "))
fact = math.factorial(x)
print("Luvun " + str(x) + " kertoma on " + str(fact) + ".")
# Could be done like this also.
# fact = x
# while x > 1:
# x = x - 1
# fact = fact * x
# print("Luvun " + str(y) + " kertoma on " + str(fact) + ".")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
kertoma()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class kertotaulu:
"""Prints the multiplication table of the given number."""
def __init__(self):
utilities().start("5.6: toistorakenne, kertotaulu")
try:
x = int(input("Minkä luvun kertotaulun haluat saada: "))
i = 1
while i < 11:
print(str(i) + " * " + str(x) + " = " + str(i * x))
i = i + 1
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
kertotaulu()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class parittomatLuvut:
"""Prints the odd numbers from given range."""
def __init__(self):
utilities().start("5.7: toistorakenne, parittomat luvut")
try:
x = int(input("Anna alueen yläraja: "))
y = int(input("Anna alueen alaraja: "))
if y % 2 == 0:
y = y +1
for i in range(y, x, 2):
print(i)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
parittomatLuvut()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class parillisetLuvut:
"""Prints even numbers starting from given number."""
def __init__(self):
utilities().start("5.8: toistorakenne, parillisten lukujen tulostus")
try:
print("Tämä ohjelma tulostaa haluamasi määrän parillisia lukuja, " +
"lähtien liikkeelle antamastasi luvusta.")
x = int(input("Anna luku, josta lähdetään liikkeelle: "))
y = int(input("Kuinka monta parillista lukua haluat: "))
i = 1
c = 0
while c < y:
x = x + 1
if x % 2 == 0:
print(x)
c = c + 1
i = i + 1
print(str(c) + " parillista lukua löytyi " +
str(i-1) + ". kierroksella.")
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
parillisetLuvut()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class funktiokertotaulu:
"""Prints a multiplication table of the given numberr."""
def __init__(self):
utilities().start("6.1: Kertolaskutaulukko funktiolla")
try:
cont = True
while cont:
x = input("Minkä luvun kertotaulun haluat saada (0 lopettaa): ")
x = int(x)
if x != 0:
funktiokertotaulu.printMultiplicationTable(x)
else:
cont = False
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
funktiokertotaulu()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def printMultiplicationTable(n):
# Does more or less this:
# For every row (a variable) in the range 1, n + 1,
# print an array of formatted col's (variables) from the same range.
for row in range(1, n + 1):
print( * ("{:3}".format(row * col) for col in range(1, n + 1)))
class reunat:
"""Prints a rectangle according to the given parameters."""
def __init__(self):
utilities().start("6.2: Neliön reunojen tulostus aliohjelmassa")
try:
x = int(input("Anna tulostettavan neliön sivun pituus: "))
y = str(input("Täytetäänkö alue merkeillä (k=kyllä): "))
reunat.rectangle(x, y)
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
reunat()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def rectangle(n, fill):
fill = str.lower(fill)
if fill == "k" or fill == "y":
for row in range(0, n):
print( * ("{:2}".format("*") for col in range(0, n)))
else:
print(n * ("{:2}".format("*")))
for row in range(2, n):
print("{:2}".format("*"), end = "")
print((n - 2) * "{:2}".format(" "), end = "")
print("{:2}".format("*"))
print(n * ("{:2}".format("*")))
class lampotila:
"""Converts temperatures."""
def __init__(self):
utilities().start("6.3: Lämpötilamuunnosohjelma")
try:
x = int(input("Anna lämpötila Celcius-asteina: "))
print(lampotila.celciusToFahrenheit(x))
y = int(input("Anna lämpötila Fahrenheit-asteina: "))
print(lampotila.fahrenheitToCelcius(y))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
lampotila()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def celciusToFahrenheit(t):
return (str(t) + " Celcius-astetta vastaa " + str(t * (9 / 5) + 32) +
" Fahrenheit-astetta.")
def fahrenheitToCelcius(t):
return (str(t) + " Fahrenheit-astetta vastaa " +
str((t - 32) * (5 / 9)) + " Celcius-astetta.")
class vertailu:
"""Compares numbers."""
def __init__(self):
utilities().start("6.4: Lukujen vertailu funktiossa")
try:
x = int(input("Anna ensimmäinen luku: "))
y = int(input("Anna toinen luku: "))
print(str(vertailu.suurin(x, y)))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
vertailu()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def suurin(i, j):
if i != j:
return("Testatuista luvuista " + max(i, j) +
" on suurempi kuin " + min(i, j) + ".")
else:
return i + " on yhtä suuri kuin " + j + "."
class sanojentoisto:
"""Repeats words"""
def __init__(self):
utilities().start("6.5: Sana ja lukumäärä aliohjelmalla")
try:
while True:
x = str(input("Anna sana: "))
if x.lower() == "lopeta":
break
y = int(input("Anna luku: "))
print(sanojentoisto.matkija(x, y))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
sanojentoisto()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def matkija(word, count):
return(count * (word + "\n"))
class suurin_pienin:
"""Compares numbers."""
def __init__(self):
utilities().start("6.6: aliohjelmat, suurin ja pienin")
try:
x = int(input("Syötä ensimmäinen kokonaisluku: "))
y = int(input("Syötä toinen kokonaisluku: "))
z = int(input("Syötä kolmas kokonaisluku: "))
suurinluku = suurin_pienin.suurin(x, y, z)
pieninluku = suurin_pienin.pienin(x, y, z)
print("Suurin luku on " + str(suurinluku))
print("Pienin luku on " + str(pieninluku))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
suurin_pienin()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def suurin(i, j, k):
return max(i, j, k)
def pienin(i, j, k):
return min(i, j, k)
class alkuluku:
"""Writes a string into a file."""
def __init__(self):
utilities().start("6.8: tiedostonkäsittely, kirjoitus ja luku")
try:
x = int(input("Anna positiivinen kokonaisluku: "))
print(alkuluku.tarkista(x))
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\nException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\nVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
alkuluku()
except:
if _lan_ == "EN":
print("\nThere was an unexpected exception.")
elif _lan_ == "FI":
print("\nTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def tarkista(a):
isPrime = a > 1 and all(a % i for i in range(2, a))
if isPrime:
return "Luku " + str(a) + " on alkuluku."
else:
return "Luku " + str(a) + " ei ole alkuluku."
class tiedosto:
"""Writes a string into a file."""
def __init__(self):
utilities().start("6.8: tiedostonkäsittely, kirjoitus ja luku")
try:
f = open("harjoitus.txt", "w")
f.write("Tämän tiedoston kirjoitti koodi. \n")
f.close()
x = str(input("Kirjoita joitain merkkejä: "))
f = open("harjoitus.txt", "a")
f.write(x + "\n")
f.close()
l = open("harjoitus.txt", "r+").read()
length = str(len(l) + len(str(len(l))))
f = open("harjoitus.txt", "a")
f.write(length)
f.close()
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\tException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\tVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
tiedosto()
except:
if _lan_ == "EN":
print("\tThere was an unexpected exception.")
elif _lan_ == "FI":
print("\tTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class palindromi:
"""Reads palindroms from a file"""
def __init__(self):
utilities().start("7.1: Tiedosto ja palindromien " +
"kopiointi uuteen tiedostoon")
try:
print("Tämä ohjelma lukee antamastasti tiedostosta rivejä ja " +
"tulostaa siinä olevat palindromit tiedostoon 'Palindromi.txt'.")
palindroms = []
fileName = str(input("Anna luettavan tiedoston nimi: "))
f = open(fileName, "r+")
for line in f:
for word in line.split():
if word == word[::-1]:
palindroms.append(word)
f.close()
f = open("Palindromi.txt", "w")
if not palindroms:
f.write("Palindromeja ei löytynyt.\n")
else:
for word in palindroms:
f.write(word + "\n")
f.close()
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\tException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\tVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
palindromi()
except:
if _lan_ == "EN":
print("\tThere was an unexpected exception.")
elif _lan_ == "FI":
print("\tTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
class puhelinluettelo:
"""A simple phonebook."""
def __init__(self):
utilities().start("7.2: Yksinkertainen puhelinluettelo-ohjelma")
try:
print("Tämä ohjelma ylläpitää tekstitiedostoon " +
"perustuvaa puhelinluetteloa.")
f = open("tietoja.txt", "w")
json.dump({" ": " "}, f)
f.close()
while True:
print("1) Lisää puhelinnumero")
print("2) Tulosta tiedot")
print("0) Lopeta")
opt = int(input("Valintasi: "))
if opt == 1:
puhelinluettelo.addContact()
elif opt == 2:
puhelinluettelo.printContacts()
elif opt == 0:
break
else:
print("Valintasi ei ole tuettu; yritä uudelleen.")
puhelinluettelo()
except SystemExit as e:
# Log the exit.
log = logging()
log.newEntry("Program exited by the request of user.")
sys.exit(0)
except Exception as e:
if _lan_ == "EN":
print("\tException: %s.\nPlease try a different value." % str(e))
elif _lan_ == "FI":
print("\tVirhe: %s.\nYritä uudelleen toisella arvolla." % str(e))
log = logging()
log.newEntry(str(e))
puhelinluettelo()
except:
if _lan_ == "EN":
print("\tThere was an unexpected exception.")
elif _lan_ == "FI":
print("\tTapahtui odottamaton virhe.")
log = logging()
log.newEntry("Unhandled exception: " + sys.exc_info())
def addContact():
f = open("tietoja.txt", "r+")
contacts = json.load(f)
f.close()
name = str(input("Anna uuden kontaktin nimi: "))
number = str(input("Anna hänen puhelinnumeronsa: "))
contacts[name] = number
f = open("tietoja.txt", "w+")
json.dump(contacts, f)
f.close()
def printContacts():
f = open("tietoja.txt", "r+")
contacts = json.load(f)
f.close()
print("")
for name in contacts:
if name != " ":
print(name + ": ", end = "")
for number in contacts[name]:
print(number, end = "")
print("")
print("")
class luento2:
def __init__(self):
utilities().safeRun(muuttuja())
utilities().safeRun(kokonaisluvut())
utilities().safeRun(nelio())
utilities().safeRun(keskiarvo())
utilities().safeRun(desimaaliluku())
utilities().safeRun(merkkijonot())
class luento3:
def __init__(self):
utilities().safeRun(ympyra())
utilities().safeRun(merkkijono())
utilities().safeRun(henkilotunnus())
utilities().safeRun(hinnoittelu())
class luento4:
def __init__(self):
utilities().safeRun(kahdenLuvunVertailu())
utilities().safeRun(kolmenLuvunVertailu())
utilities().safeRun(valikkotulostus())
utilities().safeRun(nelilaskin())
utilities().safeRun(peruslaskuja())
utilities().safeRun(lauseenmuodostus())
utilities().safeRun(merkkijonoja())
utilities().safeRun(kasittelua())
utilities().safeRun(valintarakenne())
utilities().safeRun(merkkijono_operaatioita())
class luento5:
def __init__(self):
utilities().safeRun(alkuehtoinenKeskiarvo())
utilities().safeRun(lopetusehtoinenKeskiarvo())
utilities().safeRun(alkuehtoinenMerkkiSyote())
utilities().safeRun(parittomat())
utilities().safeRun(kertoma())
utilities().safeRun(kertotaulu())
utilities().safeRun(parittomatLuvut())
utilities().safeRun(parillisetLuvut())
class luento6:
def __init__(self):
utilities().safeRun(funktiokertotaulu())
utilities().safeRun(reunat())
utilities().safeRun(lampotila())
utilities().safeRun(vertailu())
utilities().safeRun(sanojentoisto())
utilities().safeRun(suurin_pienin())
utilities().safeRun(alkuluku())
utilities().safeRun(tiedosto())
class luento7:
def __init__(self):
utilities().safeRun(palindromi())
utilities().safeRun(puhelinluettelo())
def main():
"""Runs the program."""
log = logging()
log.flush() # Required only for now. Remove from the final release.
log.newEntry("Program started.")
luento = luento2()
luento = luento3()
luento = luento4()
luento = luento5()
luento = luento6()
luento = luento7()
#Thank the user for being one.
if _lan_ == "EN":
print("\nThank you for being a user. I hope you enjoyed it.")
input("Press any key to quit.")
elif _lan_ == "FI":
print("\nKiitos kun olit käyttäjä. Toivottavasti nautit siitä.")
input("Paina mitä tahansa näppäintä lopettaaksesi.")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment