Add common library

This commit is contained in:
Oystein Kristoffer Tveit 2020-09-15 11:49:55 +02:00
parent e95460dd9d
commit 23d5a2ef59
8 changed files with 68 additions and 0 deletions

0
common/__init__.py Normal file
View File

View File

View File

@ -0,0 +1,15 @@
def removeEmptyDecimals(n):
"""
Removes .0 from a float if it doesn't add any extra value to the number.
Parameters:
n (float): the value to parse
```
>>> removeEmptyDecimals(2.0)
2
>>> removeEmptyDecimals(2.5)
2.5
```
"""
return int(n) if int(n) == n else n

View File

View File

@ -0,0 +1,18 @@
def boolInput(question, error='Skriv in J eller N\n', yesNoLetters=('j', 'n')):
"""
Asks the user a yes/no question and returns a bool based on the input.
Parameters: \\
prompt (str): The prompt asking the user for input \\
error? (str): The message to be printed on parsing error \\
yesNoLetters? ((str,str)): The letters to be used for representing yes and no in low caps
"""
yesLetters = [yesNoLetters[0], yesNoLetters[0].capitalize()]
noLetters = [yesNoLetters[1], yesNoLetters[1].capitalize()]
while True:
try:
choice = input(question)
assert choice in yesLetters + noLetters
return choice in yesLetters
except AssertionError:
print(error)

View File

@ -0,0 +1,16 @@
def safeQuestion(prompt, choices):
"""
Prompts the user to make a choice and asserts that the choice is valid.
Parameters: \\
prompt (str): The prompt asking the user for input \\
choices ([str]): The choices that the user can choose (in low caps)
"""
allChoices = choices + [choice.capitalize() for choice in choices]
while True:
try:
answer = input(prompt)
assert answer in allChoices
return answer.lower()
except AssertionError:
print('Skriv inn enten', ', '.join(choices[:-1]), 'eller', choices[-1])

View File

@ -0,0 +1,19 @@
def inputTypeCheck(
prompt,
type,
error="Kunne ikke tolke input. Har du skrevet det inn riktig?"
):
"""
Typechecks an input, and only returns the input when it could be successfully parsed.
Parameters: \\
prompt (str): The prompt asking the user for input \\
type (fun): The function to be used for parsing \\
error? (str): The message to be printed on parsing error
"""
while True:
inputValue = input(prompt)
try:
return type(inputValue)
except ValueError:
print(error)

0
common/test/__init__.py Normal file
View File