-
Notifications
You must be signed in to change notification settings - Fork 9
/
helpers.py
188 lines (174 loc) · 6.87 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import math
'''
Prompts the user for a String and returns whatever was entered.
@param prompt - the prompt text for the user
@return - the String entered by the user
'''
def getString(prompt):
try:
userInput = input(prompt + " ").strip()
except AttributeError:
userInput = input(prompt + " ")
return userInput
# Tests for getString
# print(getString("What's your name?")) # Expected: exactly what was entered
'''
Converts a list of strings to a list of lowercase strings
@param list - a list of strings
@return - the list of lowercase strings
'''
def listToLowercase(list):
for i in range(len(list)):
list[i] = list[i].lower()
return list
# Tests
# print(listToLowercase(["Yes", "Y", "No", "N"])) # Expected: ["yes", "y", "no", "n"]
'''
Converts a list of strings to a string with commas separating each
@param list - a list of strings
@return - the list converted to a string with commas separating each
'''
def listToString(list):
result = " ["
count = 0
for item in list:
count += 1
if(count == len(list)):
result += "or " + str(item)
elif(count == len(list) - 1):
result += str(item) + " "
else:
result += str(item) + ", "
result += "]:"
return result
# Tests
# nums = [1, 2, 3, 4, 5]
# print(listToString(nums))
# pets = ["Velcro", "Zipper", "Waffles"]
# print(listToString(pets))
# random = ["Marc", 39, 192.5, True]
# print(listToString(random))
# yesOrNo = ["Yes", "No"]
# print(listToString(yesOrNo))
'''
Validates that the user's input is included in a list of possible values
@param prompt - the prompt text for the user
@param possibleValues - a list of strings
@param totalAttempts - the maximum number of attempts allowed. Default value is infinity.
@return - the user's input if it was valid
@return - None if input wasn't valid within a number of attempts
'''
def validateUserString(prompt, possibleValues, displayPossibleValues = True, totalAttempts = float("inf"), invalidMsg = "Invalid input."):
attempts = 0
possibleValuesString = listToString(possibleValues)
possibleValuesLowercase = listToLowercase(possibleValues)
while (True):
newPrompt = prompt
invalidInputMsg = ""
if(totalAttempts == float("inf") and attempts > 0):
invalidInputMsg = "\n" + invalidMsg + " Try again...\n"
elif(totalAttempts < float("inf") and attempts > 0):
invalidInputMsg = "\n" + invalidMsg + " You have " + str(totalAttempts - attempts) + " attempt(s) remaining. Try again...\n"
newPrompt = invalidInputMsg + newPrompt
if(displayPossibleValues):
newPrompt = newPrompt + possibleValuesString
userInput = getString(newPrompt)
inputLowercase = userInput.lower()
if(inputLowercase in possibleValuesLowercase):
return userInput
attempts += 1
if(attempts == totalAttempts):
return None
# Tests
# print(validateUserString("Are you a student?", ["Yes", "No"]))
# print(validateUserString("Are you a student?", ["Yes", "No"], True, 3))
# print(validateUserString("Are you a student?", ["Yes", "No"], True, 3, "Incorrect Y/N value."))
# print(validateUserString("Are you a student?", ["Yes", "No"], True, float("inf"), "Incorrect Y/N value."))
# print(validateUserString("What is your account number?", ["9999"], False, 3, "That account number was not found."))
'''
Prompts the user to enter an integer. If the value is not an integer, it prints an invalid input message and tries again. Otherwise, it returns the integer that was entered.
@param prompt - the prompt text for the user
@return the integer entered
'''
def getInt(prompt):
invalidAttempt = False
while(True):
newPrompt = prompt
if(invalidAttempt):
newPrompt = "\nInvalid input. Try again...\n" + newPrompt
try:
userInput = getString(newPrompt + " [Enter a number without decimals]")
userInputInt = int(userInput)
return userInputInt
except ValueError:
invalidAttempt = True
# Tests
# print(getInt("What's your age?"))
'''
Prompts the user to enter a number. If the value is not a number, it prints an invalid input message and tries again. Otherwise, it returns the value that was entered.
@param prompt - the prompt text for the user
@param convertToInt - a boolean value. If true the function will convert a whole number (example: 10.0) to its integer representation (example: 10)
@return the number entered
'''
def getFloat(prompt, convertToInt = False):
invalidAttempt = False
while(True):
newPrompt = prompt
if(invalidAttempt):
newPrompt = "\nInvalid input. Try again...\n" + newPrompt
try:
userInput = getString(newPrompt + " [Enter a number]")
userInputNum = float(userInput)
if(convertToInt and userInputNum % 1 == 0):
userInputNum = int(userInputNum)
return userInputNum
except ValueError:
invalidAttempt = True
# Tests
# print(getFloat("What's your weight?"))
# print(getFloat("What's your weight?", True))
'''
Prompts the user to enter a whole number. If the value is not a whole
number, prints the notIntMessage and tries again. Otherwise, returns the
int that was entered.
@param prompt - the prompt text for the user
@param convertToInt - a boolean to determine if the input needs to be an int (True) or float (False)
@param notIntMessage the error message for not an int
@return the int entered
'''
def getNum(prompt, minValue = -float("inf"), maxValue = float("inf"), totalAttempts = float("inf"), convertToInt = False, invalidMsg = "Invalid number."):
attempts = 0
while(True):
newPrompt = prompt
if(minValue > -float("inf") and maxValue < float("inf")):
newPrompt = prompt + " [Enter a number between " + str(minValue) + " and " + str(maxValue) + "]:"
elif(minValue > -float("inf") and maxValue == float("inf")):
newPrompt = prompt + " [Enter a number greater than or equal to " + str(minValue) + "]:"
else:
newPrompt = prompt + " [Enter a number]:"
invalidInputMsg = ""
if(totalAttempts == float("inf") and attempts > 0):
invalidInputMsg = "\n" + invalidMsg + " Try again...\n"
elif(totalAttempts < float("inf") and attempts > 0):
invalidInputMsg = "\n" + invalidMsg + " You have " + str(totalAttempts - attempts) + " attempt(s) remaining. Try again...\n"
newPrompt = invalidInputMsg + newPrompt
userInput = getString(newPrompt)
try:
inputNum = float(userInput)
if(convertToInt):
inputNum = math.floor(inputNum)
if(inputNum >= minValue and inputNum <= maxValue):
return inputNum
attempts += 1
if(attempts == totalAttempts):
return None
except ValueError:
attempts += 1
if(attempts == totalAttempts):
return None
# Tests
# print(getNum("How much do you weigh?"))
# print(getNum("How much do you weigh?", 0))
# print(getNum("How much do you weigh?", 0, 1000))
# print(getNum("How much do you weigh?", 0, 1000, 3))
# print(getNum("How much do you weigh?", 0, 1000, 3, True))